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