]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
Revert unintended part of commit that was causing changed output.
[lyx.git] / src / output_latex.cpp
1 /**
2  * \file output_latex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "Encoding.h"
18 #include "Font.h"
19 #include "InsetList.h"
20 #include "Language.h"
21 #include "Layout.h"
22 #include "LyXRC.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "TextClass.h"
27
28 #include "insets/InsetBibitem.h"
29 #include "insets/InsetArgument.h"
30
31 #include "frontends/alert.h"
32
33 #include "support/lassert.h"
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/lstrings.h"
37 #include "support/lyxalgo.h"
38 #include "support/textutils.h"
39 #include "support/gettext.h"
40
41 #include <QThreadStorage>
42
43 #include <list>
44 #include <stack>
45
46 using namespace std;
47 using namespace lyx::support;
48
49
50 namespace lyx {
51
52 namespace {
53
54 enum OpenEncoding {
55         none,
56         inputenc,
57         CJK
58 };
59
60
61 struct OutputState
62 {
63         OutputState() : open_encoding_(none), cjk_inherited_(0),
64                         prev_env_language_(0), nest_level_(0)
65         {
66         }
67         OpenEncoding open_encoding_;
68         int cjk_inherited_;
69         Language const * prev_env_language_;
70         int nest_level_;
71         stack<int> lang_switch_depth_;          // Both are always empty when
72         stack<string> open_polyglossia_lang_;   // not using polyglossia
73 };
74
75
76 OutputState * getOutputState()
77 {
78         // FIXME An instance of OutputState should be kept around for each export
79         //       instead of using local thread storage
80         static QThreadStorage<OutputState *> outputstate;
81         if (!outputstate.hasLocalData())
82                 outputstate.setLocalData(new OutputState);
83         return outputstate.localData();
84 }
85
86
87 string const & openPolyglossiaLang(OutputState const * state)
88 {
89         // Return a reference to the last active language opened with
90         // polyglossia. If none or when using babel, return a reference
91         // to an empty string.
92
93         static string const empty;
94
95         return state->open_polyglossia_lang_.empty()
96                 ? empty
97                 : state->open_polyglossia_lang_.top();
98 }
99
100
101 bool atSameLastLangSwitchDepth(OutputState const * state)
102 {
103         // Return true if the actual nest level is the same at which the
104         // language was switched when using polyglossia. Instead, return
105         // always true when using babel.
106
107         return state->lang_switch_depth_.size() == 0
108                         ? true
109                         : abs(state->lang_switch_depth_.top()) == state->nest_level_;
110 }
111
112
113 bool isLocalSwitch(OutputState const * state)
114 {
115         // Return true if the language was opened by the \text<lang> command.
116
117         return state->lang_switch_depth_.size()
118                 && state->lang_switch_depth_.top() < 0;
119 }
120
121
122 bool langOpenedAtThisLevel(OutputState const * state)
123 {
124         // Return true if the language was opened at the current nesting level.
125
126         return state->lang_switch_depth_.size()
127                 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
128 }
129
130
131 string const getPolyglossiaEnvName(Language const * lang)
132 {
133         string result = lang->polyglossia();
134         if (result == "arabic")
135                 // exceptional spelling; see polyglossia docs.
136                 result = "Arabic";
137         return result;
138 }
139
140
141 string const getPolyglossiaBegin(string const & lang_begin_command,
142                                  string const & lang, string const & opts)
143 {
144         string result;
145         if (!lang.empty())
146                 result = subst(lang_begin_command, "$$lang", lang);
147         string options = opts.empty() ?
148                     string() : "[" + opts + "]";
149         result = subst(result, "$$opts", options);
150
151         return result;
152 }
153
154
155 struct TeXEnvironmentData
156 {
157         bool cjk_nested;
158         Layout const * style;
159         Language const * par_language;
160         Encoding const * prev_encoding;
161         bool leftindent_open;
162 };
163
164
165 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
166                                         Text const & text,
167                                         ParagraphList::const_iterator pit,
168                                         otexstream & os,
169                                         OutputParams const & runparams)
170 {
171         TeXEnvironmentData data;
172
173         BufferParams const & bparams = buf.params();
174
175         // FIXME This test should not be necessary.
176         // We should perhaps issue an error if it is.
177         Layout const & style = text.inset().forcePlainLayout() ?
178                 bparams.documentClass().plainLayout() : pit->layout();
179
180         ParagraphList const & paragraphs = text.paragraphs();
181         ParagraphList::const_iterator const priorpit =
182                 pit == paragraphs.begin() ? pit : prev(pit, 1);
183
184         OutputState * state = getOutputState();
185         bool const use_prev_env_language = state->prev_env_language_ != 0
186                         && priorpit->layout().isEnvironment()
187                         && (priorpit->getDepth() > pit->getDepth()
188                             || (priorpit->getDepth() == pit->getDepth()
189                                 && priorpit->layout() != pit->layout()));
190
191         data.prev_encoding = runparams.encoding;
192         data.par_language = pit->getParLanguage(bparams);
193         Language const * const doc_language = bparams.language;
194         Language const * const prev_par_language =
195                 (pit != paragraphs.begin())
196                 ? (use_prev_env_language ? state->prev_env_language_
197                                          : priorpit->getParLanguage(bparams))
198                 : doc_language;
199
200         bool const use_polyglossia = runparams.use_polyglossia;
201         string const par_lang = use_polyglossia ?
202                 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
203         string const prev_par_lang = use_polyglossia ?
204                 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
205         string const doc_lang = use_polyglossia ?
206                 getPolyglossiaEnvName(doc_language) : doc_language->babel();
207         string const lang_begin_command = use_polyglossia ?
208                 "\\begin{$$lang}" : lyxrc.language_command_begin;
209         string const lang_end_command = use_polyglossia ?
210                 "\\end{$$lang}" : lyxrc.language_command_end;
211
212         // For polyglossia, switch language outside of environment, if possible.
213         if (par_lang != prev_par_lang) {
214                 if (!lang_end_command.empty() &&
215                     prev_par_lang != doc_lang &&
216                     atSameLastLangSwitchDepth(state) &&
217                     !prev_par_lang.empty()) {
218                         os << from_ascii(subst(
219                                 lang_end_command,
220                                 "$$lang",
221                                 prev_par_lang))
222                           // the '%' is necessary to prevent unwanted whitespace
223                           << "%\n";
224                         if (use_polyglossia)
225                                 popPolyglossiaLang();
226                 }
227
228                 // If no language was explicitly opened and we are using
229                 // polyglossia, then the current polyglossia language is
230                 // the document language.
231                 string const & pol_lang = use_polyglossia
232                                           && state->lang_switch_depth_.size()
233                                                   ? openPolyglossiaLang(state)
234                                                   : doc_lang;
235
236                 if ((lang_end_command.empty() ||
237                     par_lang != doc_lang ||
238                     par_lang != pol_lang) &&
239                     !par_lang.empty()) {
240                             string bc = use_polyglossia ?
241                                         getPolyglossiaBegin(lang_begin_command, par_lang,
242                                                             data.par_language->polyglossiaOpts())
243                                       : subst(lang_begin_command, "$$lang", par_lang);
244                             os << bc;
245                             // the '%' is necessary to prevent unwanted whitespace
246                             os << "%\n";
247                             if (use_polyglossia)
248                                     pushPolyglossiaLang(par_lang);
249                 }
250         }
251
252         data.leftindent_open = false;
253         if (!pit->params().leftIndent().zero()) {
254                 os << "\\begin{LyXParagraphLeftIndent}{"
255                    << from_ascii(pit->params().leftIndent().asLatexString())
256                    << "}\n";
257                 data.leftindent_open = true;
258         }
259
260         if (style.isEnvironment()) {
261                 state->nest_level_ += 1;
262                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
263                 if (!style.latexargs().empty()) {
264                         OutputParams rp = runparams;
265                         rp.local_font = &pit->getFirstFontSettings(bparams);
266                         latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
267                 }
268                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
269                         os << '{'
270                            << pit->params().labelWidthString()
271                            << "}\n";
272                 } else if (style.labeltype == LABEL_BIBLIO) {
273                         if (pit->params().labelWidthString().empty())
274                                 os << '{' << bibitemWidest(buf, runparams) << "}\n";
275                         else
276                                 os << '{'
277                                   << pit->params().labelWidthString()
278                                   << "}\n";
279                 } else
280                         os << from_ascii(style.latexparam()) << '\n';
281         }
282         data.style = &style;
283
284         // in multilingual environments, the CJK tags have to be nested properly
285         data.cjk_nested = false;
286         if (data.par_language->encoding()->package() == Encoding::CJK &&
287             state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
288                 if (prev_par_language->encoding()->package() == Encoding::CJK)
289                         os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
290                            << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
291                 state->open_encoding_ = CJK;
292                 data.cjk_nested = true;
293         }
294         return data;
295 }
296
297
298 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
299                               TeXEnvironmentData const & data)
300 {
301         OutputState * state = getOutputState();
302         // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
303         if (state->open_encoding_ == CJK && data.cjk_nested) {
304                 // We need to close the encoding even if it does not change
305                 // to do correct environment nesting
306                 os << "\\end{CJK}\n";
307                 state->open_encoding_ = none;
308         }
309
310         if (data.style->isEnvironment()) {
311                 os << breakln;
312                 // Close any polyglossia language opened at this nest level
313                 if (runparams.use_polyglossia) {
314                         while (langOpenedAtThisLevel(state)) {
315                                 if (isLocalSwitch(state)) {
316                                         os << "}";
317                                 } else {
318                                         os << "\\end{"
319                                            << openPolyglossiaLang(state)
320                                            << "}%\n";
321                                 }
322                                 popPolyglossiaLang();
323                         }
324                 }
325                 state->nest_level_ -= 1;
326                 os << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
327                 state->prev_env_language_ = data.par_language;
328                 if (runparams.encoding != data.prev_encoding) {
329                         runparams.encoding = data.prev_encoding;
330                         os << setEncoding(data.prev_encoding->iconvName());
331                 }
332         }
333
334         if (data.leftindent_open) {
335                 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
336                 state->prev_env_language_ = data.par_language;
337                 if (runparams.encoding != data.prev_encoding) {
338                         runparams.encoding = data.prev_encoding;
339                         os << setEncoding(data.prev_encoding->iconvName());
340                 }
341         }
342
343         // Check whether we should output a blank line after the environment
344         if (!data.style->nextnoindent)
345                 os << '\n';
346 }
347
348
349 void TeXEnvironment(Buffer const & buf, Text const & text,
350                     OutputParams const & runparams,
351                     pit_type & pit, otexstream & os)
352 {
353         ParagraphList const & paragraphs = text.paragraphs();
354         ParagraphList::const_iterator par = paragraphs.constIterator(pit);
355         LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
356
357         Layout const & current_layout = par->layout();
358         depth_type const current_depth = par->params().depth();
359         Length const & current_left_indent = par->params().leftIndent();
360
361         // This is for debugging purpose at the end.
362         pit_type const par_begin = pit;
363         for (; pit < runparams.par_end; ++pit) {
364                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
365
366                 // check first if this is an higher depth paragraph.
367                 bool go_out = (par->params().depth() < current_depth);
368                 if (par->params().depth() == current_depth) {
369                         // This environment is finished.
370                         go_out |= (par->layout() != current_layout);
371                         go_out |= (par->params().leftIndent() != current_left_indent);
372                 }
373                 if (go_out) {
374                         // nothing to do here, restore pit and go out.
375                         pit--;
376                         break;
377                 }
378
379                 if (par->layout() == current_layout
380                         && par->params().depth() == current_depth
381                         && par->params().leftIndent() == current_left_indent) {
382                         // We are still in the same environment so TeXOnePar and continue;
383                         TeXOnePar(buf, text, pit, os, runparams);
384                         continue;
385                 }
386
387                 // We are now in a deeper environment.
388                 // Either par->layout() != current_layout
389                 // Or     par->params().depth() > current_depth
390                 // Or     par->params().leftIndent() != current_left_indent)
391
392                 // FIXME This test should not be necessary.
393                 // We should perhaps issue an error if it is.
394                 bool const force_plain_layout = text.inset().forcePlainLayout();
395                 Layout const & style = force_plain_layout
396                         ? buf.params().documentClass().plainLayout()
397                         : par->layout();
398
399                 if (!style.isEnvironment()) {
400                         // This is a standard paragraph, no need to call TeXEnvironment.
401                         TeXOnePar(buf, text, pit, os, runparams);
402                         continue;
403                 }
404
405                 // This is a new environment.
406                 TeXEnvironmentData const data =
407                         prepareEnvironment(buf, text, par, os, runparams);
408                 // Recursive call to TeXEnvironment!
409                 TeXEnvironment(buf, text, runparams, pit, os);
410                 finishEnvironment(os, runparams, data);
411         }
412
413         if (pit != runparams.par_end)
414                 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
415 }
416
417
418 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
419                   map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
420 {
421         unsigned int const argnr = latexargs.size();
422         if (argnr == 0)
423                 return;
424
425         // Default and preset args are always output, so if they require
426         // other arguments, consider this.
427         Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
428         Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
429         for (; lit != lend; ++lit) {
430                 Layout::latexarg arg = (*lit).second;
431                 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
432                                 vector<string> req = getVectorFromString(arg.requires);
433                                 required.insert(required.end(), req.begin(), req.end());
434                         }
435         }
436
437         for (unsigned int i = 1; i <= argnr; ++i) {
438                 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
439                 bool inserted = false;
440                 if (lit != ilist.end()) {
441                         InsetArgument const * ins = (*lit).second;
442                         if (ins) {
443                                 Layout::LaTeXArgMap::const_iterator const lait =
444                                                 latexargs.find(ins->name());
445                                 if (lait != latexargs.end()) {
446                                         Layout::latexarg arg = (*lait).second;
447                                         docstring ldelim = arg.mandatory ?
448                                                         from_ascii("{") : from_ascii("[");
449                                         docstring rdelim = arg.mandatory ?
450                                                         from_ascii("}") : from_ascii("]");
451                                         if (!arg.ldelim.empty())
452                                                 ldelim = arg.ldelim;
453                                         if (!arg.rdelim.empty())
454                                                 rdelim = arg.rdelim;
455                                         ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
456                                         inserted = true;
457                                 }
458                         }
459                 }
460                 if (!inserted) {
461                         Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
462                         Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
463                         for (; lait != laend; ++lait) {
464                                 string const name = prefix + convert<string>(i);
465                                 if ((*lait).first == name) {
466                                         Layout::latexarg arg = (*lait).second;
467                                         docstring preset = arg.presetarg;
468                                         if (!arg.defaultarg.empty()) {
469                                                 if (!preset.empty())
470                                                         preset += ",";
471                                                 preset += arg.defaultarg;
472                                         }
473                                         if (arg.mandatory) {
474                                                 docstring ldelim = arg.ldelim.empty() ?
475                                                                 from_ascii("{") : arg.ldelim;
476                                                 docstring rdelim = arg.rdelim.empty() ?
477                                                                 from_ascii("}") : arg.rdelim;
478                                                 os << ldelim << preset << rdelim;
479                                         } else if (!preset.empty()) {
480                                                 docstring ldelim = arg.ldelim.empty() ?
481                                                                 from_ascii("[") : arg.ldelim;
482                                                 docstring rdelim = arg.rdelim.empty() ?
483                                                                 from_ascii("]") : arg.rdelim;
484                                                 os << ldelim << preset << rdelim;
485                                         } else if (find(required.begin(), required.end(),
486                                                    (*lait).first) != required.end()) {
487                                                 docstring ldelim = arg.ldelim.empty() ?
488                                                                 from_ascii("[") : arg.ldelim;
489                                                 docstring rdelim = arg.rdelim.empty() ?
490                                                                 from_ascii("]") : arg.rdelim;
491                                                 os << ldelim << rdelim;
492                                         } else
493                                                 break;
494                                 }
495                         }
496                 }
497         }
498 }
499
500
501 } // namespace anon
502
503
504 void pushPolyglossiaLang(string const & lang_name, bool localswitch)
505 {
506         OutputState * state = getOutputState();
507
508         int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
509         state->lang_switch_depth_.push(nest_level);
510         state->open_polyglossia_lang_.push(lang_name);
511 }
512
513
514 void popPolyglossiaLang()
515 {
516         OutputState * state = getOutputState();
517
518         state->lang_switch_depth_.pop();
519         state->open_polyglossia_lang_.pop();
520 }
521
522
523 void latexArgInsets(Paragraph const & par, otexstream & os,
524         OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
525 {
526         map<int, InsetArgument const *> ilist;
527         vector<string> required;
528
529         InsetList::const_iterator it = par.insetList().begin();
530         InsetList::const_iterator end = par.insetList().end();
531         for (; it != end; ++it) {
532                 if (it->inset->lyxCode() == ARG_CODE) {
533                         InsetArgument const * ins =
534                                 static_cast<InsetArgument const *>(it->inset);
535                         if (ins->name().empty())
536                                 LYXERR0("Error: Unnamed argument inset!");
537                         else {
538                                 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
539                                 unsigned int const nr = convert<unsigned int>(name);
540                                 ilist[nr] = ins;
541                                 Layout::LaTeXArgMap::const_iterator const lit =
542                                                 latexargs.find(ins->name());
543                                 if (lit != latexargs.end()) {
544                                         Layout::latexarg const & arg = (*lit).second;
545                                         if (!arg.requires.empty()) {
546                                                 vector<string> req = getVectorFromString(arg.requires);
547                                                 required.insert(required.end(), req.begin(), req.end());
548                                         }
549                                 }
550                         }
551                 }
552         }
553         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
554 }
555
556
557 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
558         otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
559         string const & prefix)
560 {
561         map<int, InsetArgument const *> ilist;
562         vector<string> required;
563
564         depth_type const current_depth = pit->params().depth();
565         Layout const current_layout = pit->layout();
566
567         // get the first paragraph in sequence with this layout and depth
568         pit_type offset = 0;
569         while (true) {
570                 if (lyx::prev(pit, offset) == pars.begin())
571                         break;
572                 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
573                 if (priorpit->layout() == current_layout
574                     && priorpit->params().depth() == current_depth)
575                         ++offset;
576                 else
577                         break;
578         }
579
580         ParagraphList::const_iterator spit = lyx::prev(pit, offset);
581
582         for (; spit != pars.end(); ++spit) {
583                 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
584                         break;
585                 if (spit->params().depth() > current_depth)
586                         continue;
587                 InsetList::const_iterator it = spit->insetList().begin();
588                 InsetList::const_iterator end = spit->insetList().end();
589                 for (; it != end; ++it) {
590                         if (it->inset->lyxCode() == ARG_CODE) {
591                                 InsetArgument const * ins =
592                                         static_cast<InsetArgument const *>(it->inset);
593                                 if (ins->name().empty())
594                                         LYXERR0("Error: Unnamed argument inset!");
595                                 else {
596                                         string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
597                                         unsigned int const nr = convert<unsigned int>(name);
598                                         if (ilist.find(nr) == ilist.end())
599                                                 ilist[nr] = ins;
600                                         Layout::LaTeXArgMap::const_iterator const lit =
601                                                         latexargs.find(ins->name());
602                                         if (lit != latexargs.end()) {
603                                                 Layout::latexarg const & arg = (*lit).second;
604                                                 if (!arg.requires.empty()) {
605                                                         vector<string> req = getVectorFromString(arg.requires);
606                                                         required.insert(required.end(), req.begin(), req.end());
607                                                 }
608                                         }
609                                 }
610                         }
611                 }
612         }
613         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
614 }
615
616 namespace {
617
618 // output the proper paragraph start according to latextype.
619 void parStartCommand(Paragraph const & par, otexstream & os,
620                      OutputParams const & runparams, Layout const & style) 
621 {
622         switch (style.latextype) {
623         case LATEX_COMMAND:
624                 os << '\\' << from_ascii(style.latexname());
625
626                 // Command arguments
627                 if (!style.latexargs().empty())
628                         latexArgInsets(par, os, runparams, style.latexargs());
629                 os << from_ascii(style.latexparam());
630                 break;
631         case LATEX_ITEM_ENVIRONMENT:
632         case LATEX_LIST_ENVIRONMENT:
633                 os << "\\" + style.itemcommand();
634                 // Item arguments
635                 if (!style.itemargs().empty())
636                         latexArgInsets(par, os, runparams, style.itemargs(), "item:");
637                 os << " ";
638                 break;
639         case LATEX_BIB_ENVIRONMENT:
640                 // ignore this, the inset will write itself
641                 break;
642         default:
643                 break;
644         }
645 }
646
647 } // namespace anon
648
649 // FIXME: this should be anonymous
650 void TeXOnePar(Buffer const & buf,
651                Text const & text,
652                pit_type pit,
653                otexstream & os,
654                OutputParams const & runparams_in,
655                string const & everypar,
656                int start_pos, int end_pos)
657 {
658         BufferParams const & bparams = runparams_in.is_child
659                 ? buf.masterParams() : buf.params();
660         ParagraphList const & paragraphs = text.paragraphs();
661         Paragraph const & par = paragraphs.at(pit);
662         // FIXME This check should not really be needed.
663         // Perhaps we should issue an error if it is.
664         Layout const & style = text.inset().forcePlainLayout() ?
665                 bparams.documentClass().plainLayout() : par.layout();
666
667         if (style.inpreamble)
668                 return;
669
670         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
671                 << everypar << "'");
672
673         OutputParams runparams = runparams_in;
674         runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
675         // We reinitialze par begin and end to be on the safe side
676         // with embedded inset as we don't know if they set those
677         // value correctly.
678         runparams.par_begin = 0;
679         runparams.par_end = 0;
680
681         bool const maintext = text.isMainText();
682         // we are at the beginning of an inset and CJK is already open;
683         // we count inheritation levels to get the inset nesting right.
684         OutputState * state = getOutputState();
685         if (pit == 0 && !maintext
686             && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
687                 state->cjk_inherited_ += 1;
688                 state->open_encoding_ = none;
689         }
690
691         if (text.inset().isPassThru()) {
692                 Font const outerfont = text.outerFont(pit);
693
694                 // No newline before first paragraph in this lyxtext
695                 if (pit > 0) {
696                         os << '\n';
697                         if (!text.inset().getLayout().parbreakIsNewline())
698                                 os << '\n';
699                 }
700
701                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
702                 return;
703         }
704
705         Paragraph const * nextpar = runparams.isLastPar
706                 ? 0 : &paragraphs.at(pit + 1);
707
708         if (style.pass_thru) {
709                 Font const outerfont = text.outerFont(pit);
710                 parStartCommand(par, os, runparams, style);
711
712                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
713
714                 // I did not create a parEndCommand for this minuscule
715                 // task because in the other user of parStartCommand
716                 // the code is different (JMarc)
717                 if (style.isCommand())
718                         os << "}\n";
719                 else
720                         os << '\n';
721                 if (!style.parbreak_is_newline) {
722                         os << '\n';
723                 } else if (nextpar && !style.isEnvironment()) {
724                         Layout const nextstyle = text.inset().forcePlainLayout()
725                                 ? bparams.documentClass().plainLayout()
726                                 : nextpar->layout();
727                         if (nextstyle.name() != style.name())
728                                 os << '\n';
729                 }
730
731                 return;
732         }
733
734         // This paragraph's language
735         Language const * const par_language = par.getParLanguage(bparams);
736         Language const * const nextpar_language = nextpar ?
737                 nextpar->getParLanguage(bparams) : 0;
738         // The document's language
739         Language const * const doc_language = bparams.language;
740         // The language that was in effect when the environment this paragraph is
741         // inside of was opened
742         Language const * const outer_language =
743                 (runparams.local_font != 0) ?
744                         runparams.local_font->language() : doc_language;
745
746         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
747
748         // The previous language that was in effect is the language of the
749         // previous paragraph, unless the previous paragraph is inside an
750         // environment with nesting depth greater than (or equal to, but with
751         // a different layout) the current one. If there is no previous
752         // paragraph, the previous language is the outer language.
753         bool const use_prev_env_language = state->prev_env_language_ != 0
754                         && priorpar
755                         && priorpar->layout().isEnvironment()
756                         && (priorpar->getDepth() > par.getDepth()
757                             || (priorpar->getDepth() == par.getDepth()
758                                     && priorpar->layout() != par.layout()));
759         Language const * const prev_language =
760                 (pit != 0)
761                 ? (use_prev_env_language ? state->prev_env_language_
762                                          : priorpar->getParLanguage(bparams))
763                 : outer_language;
764
765
766         bool const use_polyglossia = runparams.use_polyglossia;
767         string const par_lang = use_polyglossia ?
768                 getPolyglossiaEnvName(par_language): par_language->babel();
769         string const prev_lang = use_polyglossia ?
770                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
771         string const outer_lang = use_polyglossia ?
772                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
773         string const nextpar_lang = nextpar_language ? (use_polyglossia ?
774                 getPolyglossiaEnvName(nextpar_language) :
775                 nextpar_language->babel()) : string();
776         string lang_begin_command = use_polyglossia ?
777                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
778         string lang_end_command = use_polyglossia ?
779                 "\\end{$$lang}" : lyxrc.language_command_end;
780         // the '%' is necessary to prevent unwanted whitespace
781         string lang_command_termination = "%\n";
782
783         // In some insets (such as Arguments), we cannot use \selectlanguage
784         bool const localswitch = text.inset().forceLocalFontSwitch()
785                         || (use_polyglossia && text.inset().forcePlainLayout());
786         if (localswitch) {
787                 lang_begin_command = use_polyglossia ?
788                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
789                 lang_end_command = "}";
790                 lang_command_termination.clear();
791         }
792
793         if (par_lang != prev_lang
794                 // check if we already put language command in TeXEnvironment()
795                 && !(style.isEnvironment()
796                      && (pit == 0 || (priorpar->layout() != par.layout()
797                                           && priorpar->getDepth() <= par.getDepth())
798                                   || priorpar->getDepth() < par.getDepth())))
799         {
800                 if (!lang_end_command.empty() &&
801                     prev_lang != outer_lang &&
802                     !prev_lang.empty() &&
803                     (!use_polyglossia || !style.isEnvironment()))
804                 {
805                         os << from_ascii(subst(lang_end_command,
806                                 "$$lang",
807                                 prev_lang))
808                            << lang_command_termination;
809                         if (use_polyglossia)
810                                 popPolyglossiaLang();
811                 }
812
813                 // We need to open a new language if we couldn't close the previous
814                 // one (because there's no language_command_end); and even if we closed
815                 // the previous one, if the current language is different than the
816                 // outer_language (which is currently in effect once the previous one
817                 // is closed).
818                 if ((lang_end_command.empty() || par_lang != outer_lang
819                      || (!use_polyglossia
820                          || (style.isEnvironment() && par_lang != prev_lang)))
821                         && !par_lang.empty()) {
822                         // If we're inside an inset, and that inset is within an \L or \R
823                         // (or equivalents), then within the inset, too, any opposite
824                         // language paragraph should appear within an \L or \R (in addition
825                         // to, outside of, the normal language switch commands).
826                         // This behavior is not correct for ArabTeX, though.
827                         if (!use_polyglossia
828                             // not for ArabTeX
829                                 && par_language->lang() != "arabic_arabtex"
830                                 && outer_language->lang() != "arabic_arabtex"
831                             // are we in an inset?
832                             && runparams.local_font != 0
833                             // is the inset within an \L or \R?
834                             //
835                             // FIXME: currently, we don't check this; this means that
836                             // we'll have unnnecessary \L and \R commands, but that
837                             // doesn't seem to hurt (though latex will complain)
838                             //
839                             // is this paragraph in the opposite direction?
840                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
841                                 // FIXME: I don't have a working copy of the Arabi package, so
842                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
843                                 // or not...
844                                 if (par_language->lang() == "farsi")
845                                         os << "\\textFR{";
846                                 else if (outer_language->lang() == "farsi")
847                                         os << "\\textLR{";
848                                 else if (par_language->lang() == "arabic_arabi")
849                                         os << "\\textAR{";
850                                 else if (outer_language->lang() == "arabic_arabi")
851                                         os << "\\textLR{";
852                                 // remaining RTL languages currently is hebrew
853                                 else if (par_language->rightToLeft())
854                                         os << "\\R{";
855                                 else
856                                         os << "\\L{";
857                         }
858                         // With CJK, the CJK tag has to be closed first (see below)
859                         if (runparams.encoding->package() != Encoding::CJK
860                             && par_lang != openPolyglossiaLang(state)
861                             && !par_lang.empty()) {
862                                 string bc = use_polyglossia ?
863                                           getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
864                                           : subst(lang_begin_command, "$$lang", par_lang);
865                                 os << bc;
866                                 os << lang_command_termination;
867                                 if (use_polyglossia)
868                                         pushPolyglossiaLang(par_lang, localswitch);
869                         }
870                 }
871         }
872
873         // Switch file encoding if necessary; no need to do this for "default"
874         // encoding, since this only affects the position of the outputted
875         // \inputencoding command; the encoding switch will occur when necessary
876         if (bparams.inputenc == "auto"
877                 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding  (see also switchEncoding())
878                 && runparams.encoding->package() != Encoding::none) {
879                 // Look ahead for future encoding changes.
880                 // We try to output them at the beginning of the paragraph,
881                 // since the \inputencoding command is not allowed e.g. in
882                 // sections. For this reason we only set runparams.moving_arg
883                 // after checking for the encoding change, otherwise the
884                 // change would be always avoided by switchEncoding().
885                 for (pos_type i = 0; i < par.size(); ++i) {
886                         char_type const c = par.getChar(i);
887                         Encoding const * const encoding =
888                                 par.getFontSettings(bparams, i).language()->encoding();
889                         if (encoding->package() != Encoding::CJK
890                                 && runparams.encoding->package() == Encoding::inputenc
891                                 && isASCII(c))
892                                 continue;
893                         if (par.isInset(i))
894                                 break;
895                         // All characters before c are in the ASCII range, and
896                         // c is non-ASCII (but no inset), so change the
897                         // encoding to that required by the language of c.
898                         // With CJK, only add switch if we have CJK content at the beginning
899                         // of the paragraph
900                         if (i != 0 && encoding->package() == Encoding::CJK)
901                                 continue;
902
903                         pair<bool, int> enc_switch = switchEncoding(os.os(),
904                                                 bparams, runparams, *encoding);
905                         // the following is necessary after a CJK environment in a multilingual
906                         // context (nesting issue).
907                         if (par_language->encoding()->package() == Encoding::CJK
908                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
909                                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
910                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
911                                 state->open_encoding_ = CJK;
912                         }
913                         if (encoding->package() != Encoding::none && enc_switch.first) {
914                                 if (enc_switch.second > 0) {
915                                         // the '%' is necessary to prevent unwanted whitespace
916                                         os << "%\n";
917                                 }
918                                 // With CJK, the CJK tag had to be closed first (see above)
919                                 if (runparams.encoding->package() == Encoding::CJK
920                                     && par_lang != openPolyglossiaLang(state)
921                                     && !par_lang.empty()) {
922                                         os << from_ascii(subst(
923                                                 lang_begin_command,
924                                                 "$$lang",
925                                                 par_lang))
926                                         << lang_command_termination;
927                                         if (use_polyglossia)
928                                                 pushPolyglossiaLang(par_lang, localswitch);
929                                 }
930                                 runparams.encoding = encoding;
931                         }
932                         break;
933                 }
934         }
935
936         runparams.moving_arg |= style.needprotect;
937         Encoding const * const prev_encoding = runparams.encoding;
938
939         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
940         if (par.allowParagraphCustomization()) {
941                 if (par.params().startOfAppendix()) {
942                         os << "\n\\appendix\n";
943                 }
944
945                 if (!par.params().spacing().isDefault()
946                         && (pit == 0 || !priorpar->hasSameLayout(par)))
947                 {
948                         os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
949                             << '\n';
950                 }
951
952                 if (style.isCommand()) {
953                         os << '\n';
954                 }
955         }
956
957         parStartCommand(par, os, runparams, style);
958         Font const outerfont = text.outerFont(pit);
959
960         // FIXME UNICODE
961         os << from_utf8(everypar);
962         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
963
964         // Make sure that \\par is done with the font of the last
965         // character if this has another size as the default.
966         // This is necessary because LaTeX (and LyX on the screen)
967         // calculates the space between the baselines according
968         // to this font. (Matthias)
969         //
970         // We must not change the font for the last paragraph
971         // of non-multipar insets, tabular cells or commands,
972         // since this produces unwanted whitespace.
973
974         Font const font = par.empty()
975                  ? par.getLayoutFont(bparams, outerfont)
976                  : par.getFont(bparams, par.size() - 1, outerfont);
977
978         bool const is_command = style.isCommand();
979
980         if (style.resfont.size() != font.fontInfo().size()
981             && (nextpar || maintext
982                 || (text.inset().paragraphs().size() > 1
983                     && text.inset().lyxCode() != CELL_CODE))
984             && !is_command) {
985                 os << '{';
986                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
987         } else if (is_command) {
988                 os << '}';
989                 if (!style.postcommandargs().empty())
990                         latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
991                 if (runparams.encoding != prev_encoding) {
992                         runparams.encoding = prev_encoding;
993                         os << setEncoding(prev_encoding->iconvName());
994                 }
995         }
996
997         bool pending_newline = false;
998         bool unskip_newline = false;
999         bool close_lang_switch = false;
1000         switch (style.latextype) {
1001         case LATEX_ITEM_ENVIRONMENT:
1002         case LATEX_LIST_ENVIRONMENT:
1003                 if ((nextpar && par_lang != nextpar_lang
1004                              && nextpar->getDepth() == par.getDepth())
1005                     || (atSameLastLangSwitchDepth(state) && nextpar
1006                             && nextpar->getDepth() < par.getDepth()))
1007                         close_lang_switch = use_polyglossia;
1008                 if (nextpar && par.params().depth() < nextpar->params().depth())
1009                         pending_newline = true;
1010                 break;
1011         case LATEX_ENVIRONMENT: {
1012                 // if its the last paragraph of the current environment
1013                 // skip it otherwise fall through
1014                 if (nextpar
1015                     && ((nextpar->layout() != par.layout()
1016                            || nextpar->params().depth() != par.params().depth())
1017                         || (!use_polyglossia || par_lang != nextpar_lang)))
1018                 {
1019                         close_lang_switch = use_polyglossia;
1020                         break;
1021                 }
1022         }
1023
1024         // fall through possible
1025         default:
1026                 // we don't need it for the last paragraph!!!
1027                 if (nextpar)
1028                         pending_newline = true;
1029         }
1030
1031         if (par.allowParagraphCustomization()) {
1032                 if (!par.params().spacing().isDefault()
1033                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1034                         if (pending_newline)
1035                                 os << '\n';
1036
1037                         string const endtag =
1038                                 par.params().spacing().writeEnvirEnd(useSetSpace);
1039                         if (prefixIs(endtag, "\\end{"))
1040                                 os << breakln;
1041
1042                         os << from_ascii(endtag);
1043                         pending_newline = true;
1044                 }
1045         }
1046
1047         // Closing the language is needed for the last paragraph; it is also
1048         // needed if we're within an \L or \R that we may have opened above (not
1049         // necessarily in this paragraph) and are about to close.
1050         bool closing_rtl_ltr_environment = !use_polyglossia
1051                 // not for ArabTeX
1052                 && (par_language->lang() != "arabic_arabtex"
1053                     && outer_language->lang() != "arabic_arabtex")
1054                 // have we opened an \L or \R environment?
1055                 && runparams.local_font != 0
1056                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1057                 // are we about to close the language?
1058                 &&((nextpar && par_lang != nextpar_lang)
1059                    || (runparams.isLastPar && par_lang != outer_lang));
1060
1061         if (closing_rtl_ltr_environment
1062             || ((runparams.isLastPar || close_lang_switch)
1063                 && (par_lang != outer_lang || (use_polyglossia
1064                                                 && style.isEnvironment()
1065                                                 && par_lang != nextpar_lang)))) {
1066                 // Since \selectlanguage write the language to the aux file,
1067                 // we need to reset the language at the end of footnote or
1068                 // float.
1069
1070                 if (pending_newline || close_lang_switch)
1071                         os << '\n';
1072
1073                 // when the paragraph uses CJK, the language has to be closed earlier
1074                 if (font.language()->encoding()->package() != Encoding::CJK) {
1075                         if (lang_end_command.empty()) {
1076                                 // If this is a child, we should restore the
1077                                 // master language after the last paragraph.
1078                                 Language const * const current_language =
1079                                         (runparams.isLastPar && runparams.master_language)
1080                                                 ? runparams.master_language
1081                                                 : outer_language;
1082                                 string const current_lang = use_polyglossia
1083                                         ? getPolyglossiaEnvName(current_language)
1084                                         : current_language->babel();
1085                                 if (!current_lang.empty()
1086                                     && current_lang != openPolyglossiaLang(state)) {
1087                                         string bc = use_polyglossia ?
1088                                                     getPolyglossiaBegin(lang_begin_command, current_lang,
1089                                                                         current_language->polyglossiaOpts())
1090                                                   : subst(lang_begin_command, "$$lang", current_lang);
1091                                         os << bc;
1092                                         pending_newline = !localswitch;
1093                                         unskip_newline = !localswitch;
1094                                         if (use_polyglossia)
1095                                                 pushPolyglossiaLang(current_lang, localswitch);
1096                                 }
1097                         } else if (!par_lang.empty()) {
1098                                 // If we are in an environment, we have to close the "outer" language afterwards
1099                                 string const & pol_lang = openPolyglossiaLang(state);
1100                                 if (!style.isEnvironment()
1101                                     || (close_lang_switch
1102                                         && atSameLastLangSwitchDepth(state)
1103                                         && par_lang != outer_lang
1104                                         && (par_lang != pol_lang
1105                                             || (pol_lang != outer_lang
1106                                                 && nextpar
1107                                                 && style != nextpar->layout())))
1108                                     || (atSameLastLangSwitchDepth(state)
1109                                         && state->lang_switch_depth_.size()
1110                                         && pol_lang != par_lang))
1111                                 {
1112                                         if (use_polyglossia && !localswitch)
1113                                                 os << breakln;
1114                                         os << from_ascii(subst(
1115                                                 lang_end_command,
1116                                                 "$$lang",
1117                                                 par_lang));
1118                                         pending_newline = !localswitch;
1119                                         unskip_newline = !localswitch;
1120                                         if (use_polyglossia)
1121                                                 popPolyglossiaLang();
1122                                 }
1123                         }
1124                 }
1125         }
1126         if (closing_rtl_ltr_environment)
1127                 os << "}";
1128
1129         bool const last_was_separator =
1130                 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1131
1132         if (pending_newline) {
1133                 if (unskip_newline)
1134                         // prevent unwanted whitespace
1135                         os << '%';
1136                 if (!os.afterParbreak() && !last_was_separator)
1137                         os << '\n';
1138         }
1139
1140         // if this is a CJK-paragraph and the next isn't, close CJK
1141         // also if the next paragraph is a multilingual environment (because of nesting)
1142         if (nextpar
1143                 && state->open_encoding_ == CJK
1144                 && (nextpar_language->encoding()->package() != Encoding::CJK
1145                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1146                 // inbetween environments, CJK has to be closed later (nesting!)
1147                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1148                 os << "\\end{CJK}\n";
1149                 state->open_encoding_ = none;
1150         }
1151
1152         // If this is the last paragraph, close the CJK environment
1153         // if necessary. If it's an environment, we'll have to \end that first.
1154         if (runparams.isLastPar && !style.isEnvironment()) {
1155                 switch (state->open_encoding_) {
1156                         case CJK: {
1157                                 // do nothing at the end of child documents
1158                                 if (maintext && buf.masterBuffer() != &buf)
1159                                         break;
1160                                 // end of main text
1161                                 if (maintext) {
1162                                         os << "\n\\end{CJK}\n";
1163                                 // end of an inset
1164                                 } else
1165                                         os << "\\end{CJK}";
1166                                 state->open_encoding_ = none;
1167                                 break;
1168                         }
1169                         case inputenc: {
1170                                 os << "\\egroup";
1171                                 state->open_encoding_ = none;
1172                                 break;
1173                         }
1174                         case none:
1175                         default:
1176                                 // do nothing
1177                                 break;
1178                 }
1179         }
1180
1181         // If this is the last paragraph, and a local_font was set upon entering
1182         // the inset, and we're using "auto" or "default" encoding, and not
1183         // compiling with XeTeX or LuaTeX, the encoding
1184         // should be set back to that local_font's encoding.
1185         if (runparams.isLastPar && runparams_in.local_font != 0
1186             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1187             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1188                 && !runparams.isFullUnicode()
1189            ) {
1190                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1191                 os << setEncoding(runparams_in.encoding->iconvName());
1192         }
1193         // Otherwise, the current encoding should be set for the next paragraph.
1194         else
1195                 runparams_in.encoding = runparams.encoding;
1196
1197
1198         // we don't need a newline for the last paragraph!!!
1199         // Note from JMarc: we will re-add a \n explicitly in
1200         // TeXEnvironment, because it is needed in this case
1201         if (nextpar && !os.afterParbreak() && !last_was_separator) {
1202                 // Make sure to start a new line
1203                 os << breakln;
1204                 Layout const & next_layout = nextpar->layout();
1205                 // A newline '\n' is always output before a command,
1206                 // so avoid doubling it.
1207                 if (!next_layout.isCommand()) {
1208                         // Here we now try to avoid spurious empty lines by
1209                         // outputting a paragraph break only if: (case 1) the
1210                         // paragraph style allows parbreaks and no \begin, \end
1211                         // or \item tags are going to follow (i.e., if the next
1212                         // isn't the first or the current isn't the last
1213                         // paragraph of an environment or itemize) and the
1214                         // depth and alignment of the following paragraph is
1215                         // unchanged, or (case 2) the following is a
1216                         // non-environment paragraph whose depth is increased
1217                         // but whose alignment is unchanged, or (case 3) the
1218                         // paragraph is not an environment and the next one is a
1219                         // non-itemize-like env at lower depth, or (case 4) the
1220                         // paragraph is a command not followed by an environment
1221                         // and the alignment of the current and next paragraph
1222                         // is unchanged, or (case 5) the current alignment is
1223                         // changed and a standard paragraph follows.
1224                         DocumentClass const & tclass = bparams.documentClass();
1225                         if ((style == next_layout
1226                              && !style.parbreak_is_newline
1227                              && !text.inset().getLayout().parbreakIsNewline()
1228                              && style.latextype != LATEX_ITEM_ENVIRONMENT
1229                              && style.latextype != LATEX_LIST_ENVIRONMENT
1230                              && style.align == par.getAlign()
1231                              && nextpar->getDepth() == par.getDepth()
1232                              && nextpar->getAlign() == par.getAlign())
1233                             || (!next_layout.isEnvironment()
1234                                 && nextpar->getDepth() > par.getDepth()
1235                                 && nextpar->getAlign() == par.getAlign())
1236                             || (!style.isEnvironment()
1237                                 && next_layout.latextype == LATEX_ENVIRONMENT
1238                                 && nextpar->getDepth() < par.getDepth())
1239                             || (style.isCommand()
1240                                 && !next_layout.isEnvironment()
1241                                 && style.align == par.getAlign()
1242                                 && next_layout.align == nextpar->getAlign())
1243                             || (style.align != par.getAlign()
1244                                 && tclass.isDefaultLayout(next_layout))) {
1245                                 os << '\n';
1246                         }
1247                 }
1248         }
1249
1250         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1251                 << &par << " next " << nextpar);
1252
1253         return;
1254 }
1255
1256
1257 // LaTeX all paragraphs
1258 void latexParagraphs(Buffer const & buf,
1259                      Text const & text,
1260                      otexstream & os,
1261                      OutputParams const & runparams,
1262                      string const & everypar)
1263 {
1264         LASSERT(runparams.par_begin <= runparams.par_end,
1265                 { os << "% LaTeX Output Error\n"; return; } );
1266
1267         BufferParams const & bparams = buf.params();
1268
1269         bool const maintext = text.isMainText();
1270         bool const is_child = buf.masterBuffer() != &buf;
1271
1272         // Open a CJK environment at the beginning of the main buffer
1273         // if the document's language is a CJK language
1274         // (but not in child documents)
1275         OutputState * state = getOutputState();
1276         if (maintext && !is_child
1277             && bparams.encoding().package() == Encoding::CJK) {
1278                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1279                 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1280                 state->open_encoding_ = CJK;
1281         }
1282         // if "auto begin" is switched off, explicitly switch the
1283         // language on at start
1284         string const mainlang = runparams.use_polyglossia
1285                 ? getPolyglossiaEnvName(bparams.language)
1286                 : bparams.language->babel();
1287         string const lang_begin_command = runparams.use_polyglossia ?
1288                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1289
1290         if (maintext && !lyxrc.language_auto_begin &&
1291             !mainlang.empty()) {
1292                 // FIXME UNICODE
1293                 string bc = runparams.use_polyglossia ?
1294                             getPolyglossiaBegin(lang_begin_command, mainlang,
1295                                                 bparams.language->polyglossiaOpts())
1296                           : subst(lang_begin_command, "$$lang", mainlang);
1297                 os << bc;
1298                 os << '\n';
1299                 if (runparams.use_polyglossia)
1300                         pushPolyglossiaLang(mainlang);
1301         }
1302
1303         ParagraphList const & paragraphs = text.paragraphs();
1304
1305         if (runparams.par_begin == runparams.par_end) {
1306                 // The full doc will be exported but it is easier to just rely on
1307                 // runparams range parameters that will be passed TeXEnvironment.
1308                 runparams.par_begin = 0;
1309                 runparams.par_end = paragraphs.size();
1310         }
1311
1312         pit_type pit = runparams.par_begin;
1313         // lastpit is for the language check after the loop.
1314         pit_type lastpit = pit;
1315         // variables used in the loop:
1316         bool was_title = false;
1317         bool already_title = false;
1318         DocumentClass const & tclass = bparams.documentClass();
1319
1320         // Did we already warn about inTitle layout mixing? (we only warn once)
1321         bool gave_layout_warning = false;
1322         for (; pit < runparams.par_end; ++pit) {
1323                 lastpit = pit;
1324                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1325
1326                 // FIXME This check should not be needed. We should
1327                 // perhaps issue an error if it is.
1328                 Layout const & layout = text.inset().forcePlainLayout() ?
1329                                 tclass.plainLayout() : par->layout();
1330
1331                 if (layout.intitle) {
1332                         if (already_title) {
1333                                 if (!gave_layout_warning) {
1334                                         gave_layout_warning = true;
1335                                         frontend::Alert::warning(_("Error in latexParagraphs"),
1336                                                         bformat(_("You are using at least one "
1337                                                           "layout (%1$s) intended for the title, "
1338                                                           "after using non-title layouts. This "
1339                                                           "could lead to missing or incorrect output."
1340                                                           ), layout.name()));
1341                                 }
1342                         } else if (!was_title) {
1343                                 was_title = true;
1344                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1345                                         os << "\\begin{"
1346                                                         << from_ascii(tclass.titlename())
1347                                                         << "}\n";
1348                                 }
1349                         }
1350                 } else if (was_title && !already_title) {
1351                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1352                                 os << "\\end{" << from_ascii(tclass.titlename())
1353                                                 << "}\n";
1354                         }
1355                         else {
1356                                 os << "\\" << from_ascii(tclass.titlename())
1357                                                 << "\n";
1358                         }
1359                         already_title = true;
1360                         was_title = false;
1361                 }
1362
1363
1364                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1365                         // This is a standard top level paragraph, TeX it and continue.
1366                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1367                         continue;
1368                 }
1369                 
1370                 TeXEnvironmentData const data =
1371                         prepareEnvironment(buf, text, par, os, runparams);
1372                 // pit can be changed in TeXEnvironment.
1373                 TeXEnvironment(buf, text, runparams, pit, os);
1374                 finishEnvironment(os, runparams, data);
1375         }
1376
1377         if (pit == runparams.par_end) {
1378                         // Make sure that the last paragraph is
1379                         // correctly terminated (because TeXOnePar does
1380                         // not add a \n in this case)
1381                         //os << '\n';
1382         }
1383
1384         // It might be that we only have a title in this document
1385         if (was_title && !already_title) {
1386                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1387                         os << "\\end{" << from_ascii(tclass.titlename())
1388                            << "}\n";
1389                 } else {
1390                         os << "\\" << from_ascii(tclass.titlename())
1391                            << "\n";
1392                 }
1393         }
1394
1395         // if "auto end" is switched off, explicitly close the language at the end
1396         // but only if the last par is in a babel or polyglossia language
1397         string const lang_end_command = runparams.use_polyglossia ?
1398                 "\\end{$$lang}" : lyxrc.language_command_end;
1399         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1400                 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1401                 os << from_utf8(subst(lang_end_command,
1402                                         "$$lang",
1403                                         mainlang))
1404                         << '\n';
1405                 if (runparams.use_polyglossia)
1406                         popPolyglossiaLang();
1407         }
1408
1409         // If the last paragraph is an environment, we'll have to close
1410         // CJK at the very end to do proper nesting.
1411         if (maintext && !is_child && state->open_encoding_ == CJK) {
1412                 os << "\\end{CJK}\n";
1413                 state->open_encoding_ = none;
1414         }
1415         // Likewise for polyglossia
1416         string const & pol_lang = openPolyglossiaLang(state);
1417         if (maintext && !is_child && !pol_lang.empty()) {
1418                 os << from_utf8(subst(lang_end_command,
1419                                         "$$lang",
1420                                         pol_lang))
1421                    << '\n';
1422                 if (runparams.use_polyglossia)
1423                         popPolyglossiaLang();
1424         }
1425
1426         // reset inherited encoding
1427         if (state->cjk_inherited_ > 0) {
1428                 state->cjk_inherited_ -= 1;
1429                 if (state->cjk_inherited_ == 0)
1430                         state->open_encoding_ = CJK;
1431         }
1432 }
1433
1434
1435 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1436                    OutputParams const & runparams, Encoding const & newEnc,
1437                    bool force)
1438 {
1439         // XeTeX/LuaTeX use only one encoding per document:
1440         // * with useNonTeXFonts: "utf8plain",
1441         // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1442         // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1443         if (runparams.isFullUnicode())
1444                 return make_pair(false, 0);
1445
1446         Encoding const & oldEnc = *runparams.encoding;
1447         bool moving_arg = runparams.moving_arg;
1448         // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1449         bool const from_to_cjk = 
1450                 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1451                 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1452         if (!force && !from_to_cjk
1453             && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1454                 return make_pair(false, 0);
1455
1456         // Do nothing if the encoding is unchanged.
1457         if (oldEnc.name() == newEnc.name())
1458                 return make_pair(false, 0);
1459
1460         // FIXME We ignore encoding switches from/to encodings that do
1461         // neither support the inputenc package nor the CJK package here.
1462         // This does of course only work in special cases (e.g. switch from
1463         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1464         // but it is the best we can do
1465         if (oldEnc.package() == Encoding::none
1466                 || newEnc.package() == Encoding::none)
1467                 return make_pair(false, 0);
1468
1469         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1470                 << oldEnc.name() << " to " << newEnc.name());
1471         os << setEncoding(newEnc.iconvName());
1472         if (bparams.inputenc == "default")
1473                 return make_pair(true, 0);
1474
1475         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1476         OutputState * state = getOutputState();
1477         switch (newEnc.package()) {
1478                 case Encoding::none:
1479                 case Encoding::japanese:
1480                         // shouldn't ever reach here, see above
1481                         return make_pair(true, 0);
1482                 case Encoding::inputenc: {
1483                         int count = inputenc_arg.length();
1484                         if (oldEnc.package() == Encoding::CJK &&
1485                             state->open_encoding_ == CJK) {
1486                                 os << "\\end{CJK}";
1487                                 state->open_encoding_ = none;
1488                                 count += 9;
1489                         }
1490                         else if (oldEnc.package() == Encoding::inputenc &&
1491                                  state->open_encoding_ == inputenc) {
1492                                 os << "\\egroup";
1493                                 state->open_encoding_ = none;
1494                                 count += 7;
1495                         }
1496                         if (runparams.local_font != 0
1497                             &&  oldEnc.package() == Encoding::CJK) {
1498                                 // within insets, \inputenc switches need
1499                                 // to be embraced within \bgroup...\egroup;
1500                                 // else CJK fails.
1501                                 os << "\\bgroup";
1502                                 count += 7;
1503                                 state->open_encoding_ = inputenc;
1504                         }
1505                         // with the japanese option, inputenc is omitted.
1506                         if (runparams.use_japanese)
1507                                 return make_pair(true, count);
1508                         os << "\\inputencoding{" << inputenc_arg << '}';
1509                         return make_pair(true, count + 16);
1510                 }
1511                 case Encoding::CJK: {
1512                         int count = inputenc_arg.length();
1513                         if (oldEnc.package() == Encoding::CJK &&
1514                             state->open_encoding_ == CJK) {
1515                                 os << "\\end{CJK}";
1516                                 count += 9;
1517                         }
1518                         if (oldEnc.package() == Encoding::inputenc &&
1519                             state->open_encoding_ == inputenc) {
1520                                 os << "\\egroup";
1521                                 count += 7;
1522                         }
1523                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1524                            << from_ascii(bparams.fonts_cjk) << "}";
1525                         state->open_encoding_ = CJK;
1526                         return make_pair(true, count + 15);
1527                 }
1528         }
1529         // Dead code to avoid a warning:
1530         return make_pair(true, 0);
1531
1532 }
1533
1534 } // namespace lyx