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