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