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