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