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