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