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