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