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