]> git.lyx.org Git - features.git/blob - src/output_latex.cpp
Try to be more pedantic wrt blank lines in lyx2lyx output
[features.git] / src / output_latex.cpp
1 /**
2  * \file output_latex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "BiblioInfo.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "Encoding.h"
19 #include "Font.h"
20 #include "InsetList.h"
21 #include "Language.h"
22 #include "LyXRC.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "texstream.h"
27 #include "TextClass.h"
28
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetArgument.h"
31
32 #include "frontends/alert.h"
33
34 #include "support/lassert.h"
35 #include "support/convert.h"
36 #include "support/debug.h"
37 #include "support/lstrings.h"
38 #include "support/textutils.h"
39 #include "support/gettext.h"
40
41 #include <QThreadStorage>
42
43 #include <list>
44 #include <stack>
45
46 using namespace std;
47 using namespace lyx::support;
48
49
50 namespace lyx {
51
52 namespace {
53
54 enum OpenEncoding {
55         none,
56         inputenc,
57         CJK
58 };
59
60
61 struct OutputState
62 {
63         OutputState() : prev_env_language_(nullptr), open_encoding_(none),
64                 cjk_inherited_(0), nest_level_(0)
65         {
66         }
67         Language const * prev_env_language_;
68         stack<int> lang_switch_depth_;          // Both are always empty when
69         stack<string> open_polyglossia_lang_;   // not using polyglossia
70         OpenEncoding open_encoding_;
71         int cjk_inherited_;
72         int nest_level_;
73 };
74
75
76 OutputState * getOutputState()
77 {
78         // FIXME An instance of OutputState should be kept around for each export
79         //       instead of using local thread storage
80         static QThreadStorage<OutputState *> outputstate;
81         if (!outputstate.hasLocalData())
82                 outputstate.setLocalData(new OutputState);
83         return outputstate.localData();
84 }
85
86
87 string const & openLanguageName(OutputState const * state)
88 {
89         // Return a reference to the last active language opened with
90         // polyglossia or when using begin/end commands. If none or when
91         // using babel with only a begin command, return a reference to
92         // an empty string.
93
94         static string const empty;
95
96         return state->open_polyglossia_lang_.empty()
97                 ? empty
98                 : state->open_polyglossia_lang_.top();
99 }
100
101
102 bool atSameLastLangSwitchDepth(OutputState const * state)
103 {
104         // Return true if the actual nest level is the same at which the
105         // language was switched when using polyglossia or begin/end
106         // commands. Instead, return always true when using babel with
107         // only a begin command.
108
109         return state->lang_switch_depth_.empty()
110                         ? true
111                         : abs(state->lang_switch_depth_.top()) == state->nest_level_;
112 }
113
114
115 bool isLocalSwitch(OutputState const * state)
116 {
117         // Return true if the language was opened by a local command switch.
118
119         return !state->lang_switch_depth_.empty()
120                 && state->lang_switch_depth_.top() < 0;
121 }
122
123
124 bool langOpenedAtThisLevel(OutputState const * state)
125 {
126         // Return true if the language was opened at the current nesting level.
127
128         return !state->lang_switch_depth_.empty()
129                 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
130 }
131
132
133 string const getPolyglossiaEnvName(Language const * lang)
134 {
135         string result = lang->polyglossia();
136         if (result == "arabic")
137                 // exceptional spelling; see polyglossia docs.
138                 result = "Arabic";
139         return result;
140 }
141
142
143 string const getPolyglossiaBegin(string const & lang_begin_command,
144                                  string const & lang, string const & opts,
145                                  bool const localswitch = false)
146 {
147         string result;
148         if (!lang.empty()) {
149                 // we need to revert the upcasing done in getPolyglossiaEnvName()
150                 // in case we have a local polyglossia command (\textarabic).
151                 string language = localswitch ? ascii_lowercase(lang) : lang;
152                 result = subst(lang_begin_command, "$$lang", language);
153         }
154         string options = opts.empty() ?
155                     string() : "[" + opts + "]";
156         result = subst(result, "$$opts", options);
157
158         return result;
159 }
160
161
162 struct TeXEnvironmentData
163 {
164         Layout const * style;
165         Language const * par_language;
166         Encoding const * prev_encoding;
167         bool cjk_nested;
168         bool leftindent_open;
169 };
170
171
172 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
173                                         Text const & text,
174                                         ParagraphList::const_iterator pit,
175                                         otexstream & os,
176                                         OutputParams const & runparams)
177 {
178         TeXEnvironmentData data;
179
180         BufferParams const & bparams = buf.params();
181
182         // FIXME This test should not be necessary.
183         // We should perhaps issue an error if it is.
184         Layout const & style = text.inset().forcePlainLayout() ?
185                 bparams.documentClass().plainLayout() : pit->layout();
186
187         ParagraphList const & paragraphs = text.paragraphs();
188         bool const firstpar = pit == paragraphs.begin();
189         ParagraphList::const_iterator const priorpit =
190                 firstpar ? pit : prev(pit, 1);
191
192         OutputState * state = getOutputState();
193         bool const use_prev_env_language = state->prev_env_language_ != nullptr
194                         && priorpit->layout().isEnvironment()
195                         && (priorpit->getDepth() > pit->getDepth()
196                             || (priorpit->getDepth() == pit->getDepth()
197                                 && priorpit->layout() != pit->layout()));
198
199         data.prev_encoding = runparams.encoding;
200         data.par_language = pit->getParLanguage(bparams);
201         Language const * const doc_language = bparams.language;
202         Language const * const prev_par_language =
203                 // use font at inset or document language in first paragraph
204                 firstpar ? (runparams.local_font ?
205                                     runparams.local_font->language()
206                                   : doc_language)
207                          : (use_prev_env_language ?
208                                     state->prev_env_language_
209                                   : priorpit->getParLanguage(bparams));
210
211         bool const use_polyglossia = runparams.use_polyglossia;
212         string const par_lang = use_polyglossia ?
213                 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
214         string const prev_par_lang = use_polyglossia ?
215                 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
216         string const doc_lang = use_polyglossia ?
217                 getPolyglossiaEnvName(doc_language) : doc_language->babel();
218         string const lang_begin_command = use_polyglossia ?
219                 "\\begin{$$lang}" : lyxrc.language_command_begin;
220         string const lang_end_command = use_polyglossia ?
221                 "\\end{$$lang}" : lyxrc.language_command_end;
222         bool const using_begin_end = use_polyglossia ||
223                                         !lang_end_command.empty();
224
225         // For polyglossia, switch language outside of environment, if possible.
226         // However, if we are at the start of an inset, do not close languages
227         // opened outside.
228         if (par_lang != prev_par_lang) {
229                 if (!firstpar
230                     && (!using_begin_end || langOpenedAtThisLevel(state))
231                     && !lang_end_command.empty()
232                     && prev_par_lang != doc_lang
233                     && !prev_par_lang.empty()) {
234                         os << from_ascii(subst(
235                                 lang_end_command,
236                                 "$$lang",
237                                 prev_par_lang))
238                           // the '%' is necessary to prevent unwanted whitespace
239                           << "%\n";
240                         if (using_begin_end)
241                                 popLanguageName();
242                 }
243
244                 // If no language was explicitly opened and we are using
245                 // polyglossia or begin/end commands, then the current
246                 // language is the document language.
247                 string const & cur_lang = using_begin_end
248                                           && !state->lang_switch_depth_.empty()
249                                                   ? openLanguageName(state)
250                                                   : doc_lang;
251
252                 if ((lang_end_command.empty() ||
253                     par_lang != doc_lang ||
254                     par_lang != cur_lang) &&
255                     !par_lang.empty()) {
256                             string bc = use_polyglossia ?
257                                         getPolyglossiaBegin(lang_begin_command, par_lang,
258                                                             data.par_language->polyglossiaOpts())
259                                       : subst(lang_begin_command, "$$lang", par_lang);
260                             os << bc;
261                             // the '%' is necessary to prevent unwanted whitespace
262                             os << "%\n";
263                             if (using_begin_end)
264                                     pushLanguageName(par_lang);
265                 }
266         }
267
268         data.leftindent_open = false;
269         if (!pit->params().leftIndent().zero()) {
270                 os << "\\begin{LyXParagraphLeftIndent}{"
271                    << from_ascii(pit->params().leftIndent().asLatexString())
272                    << "}\n";
273                 data.leftindent_open = true;
274         }
275
276         if (style.isEnvironment())
277                 state->nest_level_ += 1;
278
279         if (style.isEnvironment() && !style.latexname().empty()) {
280                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
281                 if (!style.latexargs().empty()) {
282                         OutputParams rp = runparams;
283                         rp.local_font = &pit->getFirstFontSettings(bparams);
284                         latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
285                 }
286                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
287                         os << '{'
288                            << pit->params().labelWidthString()
289                            << "}\n";
290                 } else if (style.labeltype == LABEL_BIBLIO) {
291                         if (pit->params().labelWidthString().empty())
292                                 os << '{' << bibitemWidest(buf, runparams) << "}\n";
293                         else
294                                 os << '{'
295                                   << pit->params().labelWidthString()
296                                   << "}\n";
297                 } else
298                         os << from_ascii(style.latexparam()) << '\n';
299                 if (style.latextype == LATEX_BIB_ENVIRONMENT
300                     || style.latextype == LATEX_ITEM_ENVIRONMENT
301                     || style.latextype ==  LATEX_LIST_ENVIRONMENT) {
302                         OutputParams rp = runparams;
303                         rp.local_font = &pit->getFirstFontSettings(bparams);
304                         latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
305                                        "listpreamble:");
306                 }
307         }
308         data.style = &style;
309
310         // in multilingual environments, the CJK tags have to be nested properly
311         data.cjk_nested = false;
312         if (!bparams.useNonTeXFonts
313             && (bparams.inputenc == "auto-legacy"
314                         || bparams.inputenc == "auto-legacy-plain")
315             && data.par_language->encoding()->package() == Encoding::CJK
316             && state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
317                 if (prev_par_language->encoding()->package() == Encoding::CJK) {
318                         os << "\\begin{CJK}{"
319                            << from_ascii(data.par_language->encoding()->latexName())
320                            << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
321                 }
322                 state->open_encoding_ = CJK;
323                 data.cjk_nested = true;
324         }
325         return data;
326 }
327
328
329 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
330                               TeXEnvironmentData const & data, bool const maintext,
331                               bool const lastpar)
332 {
333         OutputState * state = getOutputState();
334         // BufferParams const & bparams = buf.params();
335         // FIXME: for speedup shortcut below, would require passing of "buf" as argument
336         if (state->open_encoding_ == CJK && data.cjk_nested) {
337                 // We need to close the encoding even if it does not change
338                 // to do correct environment nesting
339                 os << "\\end{CJK}\n";
340                 state->open_encoding_ = none;
341         }
342
343         if (data.style->isEnvironment()) {
344                 os << breakln;
345                 bool const using_begin_end =
346                         runparams.use_polyglossia ||
347                                 !lyxrc.language_command_end.empty();
348                 // Close any language opened at this nest level
349                 if (using_begin_end) {
350                         while (langOpenedAtThisLevel(state)) {
351                                 if (isLocalSwitch(state)) {
352                                         os << "}";
353                                 } else {
354                                         os << "\\end{"
355                                            << openLanguageName(state)
356                                            << "}%\n";
357                                 }
358                                 popLanguageName();
359                         }
360                 }
361                 if (data.style->latextype == LATEX_BIB_ENVIRONMENT)
362                         // bibliography needs a blank line after
363                         // each item for backref to function properly
364                         // (see #12041)
365                         os << '\n';
366                 state->nest_level_ -= 1;
367                 string const & name = data.style->latexname();
368                 if (!name.empty())
369                         os << "\\end{" << from_ascii(name) << "}\n";
370                 state->prev_env_language_ = data.par_language;
371                 if (runparams.encoding != data.prev_encoding) {
372                         runparams.encoding = data.prev_encoding;
373                         os << setEncoding(data.prev_encoding->iconvName());
374                 }
375                 // If this is the last par of an inset, the language needs
376                 // to be closed after the environment
377                 if (lastpar && !maintext) {
378                         if (using_begin_end && langOpenedAtThisLevel(state)) {
379                                 if (isLocalSwitch(state)) {
380                                         os << "}";
381                                 } else {
382                                         os << "\\end{"
383                                            << openLanguageName(state)
384                                            << "}%\n";
385                                 }
386                                 popLanguageName();
387                         }
388                 }
389         }
390
391         if (data.leftindent_open) {
392                 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
393                 state->prev_env_language_ = data.par_language;
394                 if (runparams.encoding != data.prev_encoding) {
395                         runparams.encoding = data.prev_encoding;
396                         os << setEncoding(data.prev_encoding->iconvName());
397                 }
398         }
399
400         // Check whether we should output a blank line after the environment
401         if (!data.style->nextnoindent)
402                 os << '\n';
403 }
404
405
406 void TeXEnvironment(Buffer const & buf, Text const & text,
407                     OutputParams const & runparams,
408                     pit_type & pit, otexstream & os)
409 {
410         ParagraphList const & paragraphs = text.paragraphs();
411         ParagraphList::const_iterator ipar = paragraphs.iterator_at(pit);
412         LYXERR(Debug::OUTFILE, "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.find_effective())
466                         output_changes = buf.params().output_changes;
467                 else
468                         output_changes = runparams.find_with_deleted();
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::OUTFILE, "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.find_effective() && 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.find_effective()) {
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.find_effective()) {
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.find_with_deleted() && style.latextype != LATEX_ENVIRONMENT
800             && !par.empty() && par.isDeleted(0, par.size()) && !bparams.output_changes)
801                 return;
802
803         LYXERR(Debug::OUTFILE, "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         bool const have_prior_nptpar =
937                         prior_nontitle_par && !prior_nontitle_par->isPassThru();
938         Language const * const prev_language =
939                 runparams_in.find_effective()
940                         ? languages.getLanguage("ignore")
941                         : (have_prior_nptpar)
942                                 ? (use_prev_env_language 
943                                         ? state->prev_env_language_
944                                         : prior_nontitle_par->getParLanguage(bparams))
945                                 : outer_language;
946
947         bool const use_polyglossia = runparams.use_polyglossia;
948         string const par_lang = use_polyglossia ?
949                 getPolyglossiaEnvName(par_language): par_language->babel();
950         string const prev_lang = use_polyglossia ?
951                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
952         string const outer_lang = use_polyglossia ?
953                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
954         string const nextpar_lang = nextpar_language ? (use_polyglossia ?
955                 getPolyglossiaEnvName(nextpar_language) :
956                 nextpar_language->babel()) : string();
957         string lang_begin_command = use_polyglossia ?
958                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
959         string lang_end_command = use_polyglossia ?
960                 "\\end{$$lang}" : lyxrc.language_command_end;
961         // the '%' is necessary to prevent unwanted whitespace
962         string lang_command_termination = "%\n";
963         bool const using_begin_end = use_polyglossia ||
964                                         !lang_end_command.empty();
965
966         // For InTitle commands, we need to switch the language inside the command
967         // (see #10849); thus open the command here.
968         if (intitle_command) {
969                 parStartCommand(par, os, runparams, style);
970                 if (style.isCommand() && style.needprotect)
971                         // Due to the moving argument, some fragile
972                         // commands (labels, index entries)
973                         // are output after this command (#2154)
974                         runparams.postpone_fragile_stuff =
975                                 bparams.postpone_fragile_content;
976                 os << '{';
977         }
978
979         // In some insets (such as Arguments), we cannot use \selectlanguage.
980         // Also, if an RTL language is set via environment in polyglossia,
981         // only a nested \\text<lang> command will reset the direction for LTR
982         // languages (see # 10111).
983         bool const in_polyglossia_rtl_env =
984                 use_polyglossia
985                 && runparams.local_font != nullptr
986                 && outer_language->rightToLeft()
987                 && !par_language->rightToLeft()
988                 && !(have_prior_nptpar
989                      && (prev_language->rightToLeft() != par_language->rightToLeft()));
990         bool const localswitch =
991                         (runparams_in.find_effective()
992                         || text.inset().forceLocalFontSwitch()
993                         || (using_begin_end && text.inset().forcePlainLayout())
994                         || in_polyglossia_rtl_env)
995                         && !text.inset().forceParDirectionSwitch();
996         if (localswitch) {
997                 lang_begin_command = use_polyglossia ?
998                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
999                 lang_end_command = "}";
1000                 lang_command_termination.clear();
1001         }
1002
1003         bool const localswitch_needed = localswitch && par_lang != outer_lang;
1004
1005         // localswitches need to be closed and reopened at each par
1006         if (runparams_in.find_effective() || ((par_lang != prev_lang || localswitch_needed)
1007              // check if we already put language command in TeXEnvironment()
1008              && !(style.isEnvironment()
1009                   && (pit == 0 || (priorpar->layout() != par.layout()
1010                                    && priorpar->getDepth() <= par.getDepth())
1011                       || priorpar->getDepth() < par.getDepth())))) {
1012                 if (!localswitch
1013                     && (!using_begin_end || langOpenedAtThisLevel(state))
1014                     && !lang_end_command.empty()
1015                     && prev_lang != outer_lang
1016                     && !prev_lang.empty()
1017                     && (!using_begin_end || !style.isEnvironment())) {
1018                         os << from_ascii(subst(lang_end_command,
1019                                                "$$lang",
1020                                                prev_lang))
1021                            << lang_command_termination;
1022                         if (using_begin_end)
1023                                 popLanguageName();
1024                 }
1025
1026                 // We need to open a new language if we couldn't close the previous
1027                 // one (because there's no language_command_end); and even if we closed
1028                 // the previous one, if the current language is different than the
1029                 // outer_language (which is currently in effect once the previous one
1030                 // is closed).
1031                 if ((lang_end_command.empty() || par_lang != outer_lang
1032                      || (!using_begin_end
1033                          || (style.isEnvironment() && par_lang != prev_lang)))
1034                         && !par_lang.empty()) {
1035                         // If we're inside an inset, and that inset is within an \L or \R
1036                         // (or equivalents), then within the inset, too, any opposite
1037                         // language paragraph should appear within an \L or \R (in addition
1038                         // to, outside of, the normal language switch commands).
1039                         // This behavior is not correct for ArabTeX, though.
1040                         if (!using_begin_end
1041                             // not for ArabTeX
1042                             && par_language->lang() != "arabic_arabtex"
1043                             && outer_language->lang() != "arabic_arabtex"
1044                             // are we in an inset?
1045                             && runparams.local_font != nullptr
1046                             // is the inset within an \L or \R?
1047                             //
1048                             // FIXME: currently, we don't check this; this means that
1049                             // we'll have unnnecessary \L and \R commands, but that
1050                             // doesn't seem to hurt (though latex will complain)
1051                             //
1052                             // is this paragraph in the opposite direction?
1053                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
1054                                 // FIXME: I don't have a working copy of the Arabi package, so
1055                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
1056                                 // or not...
1057                                 if (par_language->lang() == "farsi")
1058                                         os << "\\textFR{";
1059                                 else if (outer_language->lang() == "farsi")
1060                                         os << "\\textLR{";
1061                                 else if (par_language->lang() == "arabic_arabi")
1062                                         os << "\\textAR{";
1063                                 else if (outer_language->lang() == "arabic_arabi")
1064                                         os << "\\textLR{";
1065                                 // remaining RTL languages currently is hebrew
1066                                 else if (par_language->rightToLeft())
1067                                         os << "\\R{";
1068                                 else
1069                                         os << "\\L{";
1070                         }
1071                         // With CJK, the CJK tag has to be closed first (see below)
1072                         if ((runparams.encoding->package() != Encoding::CJK
1073                                  || bparams.useNonTeXFonts
1074                                  || runparams.find_effective())
1075                             && (par_lang != openLanguageName(state) || localswitch || intitle_command)
1076                             && !par_lang.empty()) {
1077                                 string bc = use_polyglossia ?
1078                                           getPolyglossiaBegin(lang_begin_command, par_lang,
1079                                                               par_language->polyglossiaOpts(),
1080                                                               localswitch)
1081                                           : subst(lang_begin_command, "$$lang", par_lang);
1082                                 os << bc;
1083                                 os << lang_command_termination;
1084                                 if (using_begin_end)
1085                                         pushLanguageName(par_lang, localswitch);
1086                         }
1087                 }
1088         }
1089
1090         // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
1091         // encoding, since this only affects the position of the outputted
1092         // \inputencoding command; the encoding switch will occur when necessary
1093         if (bparams.inputenc == "auto-legacy"
1094                 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding  (see also switchEncoding())
1095                 && runparams.encoding->package() != Encoding::japanese
1096                 && runparams.encoding->package() != Encoding::none) {
1097                 // Look ahead for future encoding changes.
1098                 // We try to output them at the beginning of the paragraph,
1099                 // since the \inputencoding command is not allowed e.g. in
1100                 // sections. For this reason we only set runparams.moving_arg
1101                 // after checking for the encoding change, otherwise the
1102                 // change would be always avoided by switchEncoding().
1103                 for (pos_type i = 0; i < par.size(); ++i) {
1104                         char_type const c = par.getChar(i);
1105                         Encoding const * const encoding =
1106                                 par.getFontSettings(bparams, i).language()->encoding();
1107                         if (encoding->package() != Encoding::CJK
1108                                 && runparams.encoding->package() == Encoding::inputenc
1109                                 && isASCII(c))
1110                                 continue;
1111                         if (par.isInset(i))
1112                                 break;
1113                         // All characters before c are in the ASCII range, and
1114                         // c is non-ASCII (but no inset), so change the
1115                         // encoding to that required by the language of c.
1116                         // With CJK, only add switch if we have CJK content at the beginning
1117                         // of the paragraph
1118                         if (i != 0 && encoding->package() == Encoding::CJK)
1119                                 continue;
1120
1121                         pair<bool, int> enc_switch = switchEncoding(os.os(),
1122                                                 bparams, runparams, *encoding);
1123                         // the following is necessary after a CJK environment in a multilingual
1124                         // context (nesting issue).
1125                         if (par_language->encoding()->package() == Encoding::CJK
1126                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1127                                 os << "\\begin{CJK}{"
1128                                    << from_ascii(par_language->encoding()->latexName())
1129                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1130                                 state->open_encoding_ = CJK;
1131                         }
1132                         if (encoding->package() != Encoding::none && enc_switch.first) {
1133                                 if (enc_switch.second > 0) {
1134                                         // the '%' is necessary to prevent unwanted whitespace
1135                                         os << "%\n";
1136                                 }
1137                                 // With CJK, the CJK tag had to be closed first (see above)
1138                                 if (runparams.encoding->package() == Encoding::CJK
1139                                     && par_lang != openLanguageName(state)
1140                                     && !par_lang.empty()) {
1141                                         os << subst(lang_begin_command, "$$lang", par_lang)
1142                                            << lang_command_termination;
1143                                         if (using_begin_end)
1144                                                 pushLanguageName(par_lang, localswitch);
1145                                 }
1146                                 runparams.encoding = encoding;
1147                         }
1148                         break;
1149                 }
1150         }
1151
1152         runparams.moving_arg |= style.needprotect;
1153         if (style.needmboxprotect)
1154                 ++runparams.inulemcmd;
1155         Encoding const * const prev_encoding = runparams.encoding;
1156
1157         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1158         if (par.allowParagraphCustomization()) {
1159                 if (par.params().startOfAppendix()) {
1160                         os << "\n\\appendix\n";
1161                 }
1162
1163                 // InTitle commands must use switches (not environments)
1164                 // inside the commands (see #9332)
1165                 if (style.intitle) {
1166                         if (!par.params().spacing().isDefault())
1167                         {
1168                                 if (runparams.moving_arg)
1169                                         os << "\\protect";
1170                                 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1171                         }
1172                 } else {
1173                         if (!par.params().spacing().isDefault()
1174                                 && (pit == 0 || !priorpar->hasSameLayout(par)))
1175                         {
1176                                 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1177                                     << '\n';
1178                         }
1179
1180                         if (style.isCommand()) {
1181                                 os << '\n';
1182                         }
1183                 }
1184         }
1185
1186         // For InTitle commands, we already started the command before
1187         // the language switch
1188         if (!intitle_command) {
1189                 parStartCommand(par, os, runparams, style);
1190                 if (style.isCommand() && style.needprotect)
1191                         // Due to the moving argument, some fragile
1192                         // commands (labels, index entries)
1193                         // are output after this command (#2154)
1194                         runparams.postpone_fragile_stuff =
1195                                 bparams.postpone_fragile_content;
1196         }
1197
1198         Font const outerfont = text.outerFont(pit);
1199
1200         // FIXME UNICODE
1201         os << from_utf8(everypar);
1202         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1203
1204         Font const font = par.empty()
1205                  ? par.getLayoutFont(bparams, outerfont)
1206                  : par.getFont(bparams, par.size() - 1, outerfont);
1207
1208         bool const is_command = style.isCommand();
1209
1210         // InTitle commands need to be closed after the language has been closed.
1211         if (!intitle_command) {
1212                 if (is_command) {
1213                         os << '}';
1214                         if (!style.postcommandargs().empty())
1215                                 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1216                         if (!runparams.post_macro.empty()) {
1217                                 // Output the stored fragile commands (labels, indices etc.)
1218                                 // that need to be output after the command with moving argument.
1219                                 os << runparams.post_macro;
1220                                 runparams.post_macro.clear();
1221                         }
1222                         if (par.needsCProtection(runparams.moving_arg)
1223                             && contains(runparams.active_chars, '^'))
1224                                 os << "\\endgroup";
1225                         if (runparams.encoding != prev_encoding) {
1226                                 runparams.encoding = prev_encoding;
1227                                 os << setEncoding(prev_encoding->iconvName());
1228                         }
1229                 }
1230         }
1231
1232         bool pending_newline = false;
1233         bool unskip_newline = false;
1234         bool close_lang_switch = false;
1235         switch (style.latextype) {
1236         case LATEX_ITEM_ENVIRONMENT:
1237         case LATEX_LIST_ENVIRONMENT:
1238                 if ((nextpar && par_lang != nextpar_lang
1239                              && nextpar->getDepth() == par.getDepth())
1240                     || (atSameLastLangSwitchDepth(state) && nextpar
1241                             && nextpar->getDepth() < par.getDepth()))
1242                         close_lang_switch = using_begin_end;
1243                 if (nextpar && par.params().depth() < nextpar->params().depth())
1244                         pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1245                 break;
1246         case LATEX_ENVIRONMENT: {
1247                 // if it's the last paragraph of the current environment
1248                 // skip it otherwise fall through
1249                 if (nextpar
1250                     && ((nextpar->layout() != par.layout()
1251                            || nextpar->params().depth() != par.params().depth())
1252                         || (!using_begin_end || par_lang != nextpar_lang)))
1253                 {
1254                         close_lang_switch = using_begin_end;
1255                         break;
1256                 }
1257         }
1258         // possible
1259         // fall through
1260         default:
1261                 // we don't need it for the last paragraph and in InTitle commands!!!
1262                 if (nextpar && !intitle_command)
1263                         pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1264         }
1265
1266         // InTitle commands use switches (not environments) for space settings
1267         if (par.allowParagraphCustomization() && !style.intitle) {
1268                 if (!par.params().spacing().isDefault()
1269                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1270                         if (pending_newline)
1271                                 os << '\n';
1272
1273                         string const endtag =
1274                                 par.params().spacing().writeEnvirEnd(useSetSpace);
1275                         if (prefixIs(endtag, "\\end{"))
1276                                 os << breakln;
1277
1278                         os << from_ascii(endtag);
1279                         pending_newline = true;
1280                 }
1281         }
1282
1283         // Closing the language is needed for the last paragraph in a given language
1284         // as well as for any InTitleCommand (since these set the language locally);
1285         // it is also needed if we're within an \L or \R that we may have opened above
1286         // (not necessarily in this paragraph) and are about to close.
1287         bool closing_rtl_ltr_environment = !using_begin_end
1288                 // not for ArabTeX
1289                 && (par_language->lang() != "arabic_arabtex"
1290                     && outer_language->lang() != "arabic_arabtex")
1291                 // have we opened an \L or \R environment?
1292                 && runparams.local_font != nullptr
1293                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1294                 // are we about to close the language?
1295                 &&((nextpar && par_lang != nextpar_lang)
1296                    || (runparams.isLastPar && par_lang != outer_lang));
1297
1298         if (localswitch_needed
1299             || (intitle_command && using_begin_end)
1300             || closing_rtl_ltr_environment
1301             || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1302                 && (par_lang != outer_lang || (using_begin_end
1303                                                 && style.isEnvironment()
1304                                                 && par_lang != nextpar_lang)))) {
1305                 // Since \selectlanguage write the language to the aux file,
1306                 // we need to reset the language at the end of footnote or
1307                 // float.
1308
1309                 if (!localswitch && (pending_newline || close_lang_switch))
1310                         os << '\n';
1311
1312                 // when the paragraph uses CJK, the language has to be closed earlier
1313                 if ((font.language()->encoding()->package() != Encoding::CJK)
1314                         || bparams.useNonTeXFonts
1315                         || runparams_in.find_effective()) {
1316                         if (lang_end_command.empty()) {
1317                                 // If this is a child, we should restore the
1318                                 // master language after the last paragraph.
1319                                 Language const * const current_language =
1320                                         (runparams.isLastPar && runparams.master_language)
1321                                                 ? runparams.master_language
1322                                                 : outer_language;
1323                                 string const current_lang = use_polyglossia
1324                                         ? getPolyglossiaEnvName(current_language)
1325                                         : current_language->babel();
1326                                 if (!current_lang.empty()
1327                                     && current_lang != openLanguageName(state)) {
1328                                         string bc = use_polyglossia ?
1329                                                     getPolyglossiaBegin(lang_begin_command, current_lang,
1330                                                                         current_language->polyglossiaOpts(),
1331                                                                         localswitch)
1332                                                   : subst(lang_begin_command, "$$lang", current_lang);
1333                                         os << bc;
1334                                         pending_newline = !localswitch
1335                                                         && !text.inset().getLayout().parbreakIgnored();
1336                                         unskip_newline = !localswitch;
1337                                         if (using_begin_end)
1338                                                 pushLanguageName(current_lang, localswitch);
1339                                 }
1340                         } else if ((!using_begin_end ||
1341                                     langOpenedAtThisLevel(state)) &&
1342                                    !par_lang.empty()) {
1343                                 // If we are in an environment, we have to
1344                                 // close the "outer" language afterwards
1345                                 string const & cur_lang = openLanguageName(state);
1346                                 if (!style.isEnvironment()
1347                                     || (close_lang_switch
1348                                         && atSameLastLangSwitchDepth(state)
1349                                         && par_lang != outer_lang
1350                                         && (par_lang != cur_lang
1351                                             || (cur_lang != outer_lang
1352                                                 && nextpar
1353                                                 && style != nextpar->layout())))
1354                                     || (atSameLastLangSwitchDepth(state)
1355                                         && !state->lang_switch_depth_.empty()
1356                                         && cur_lang != par_lang)
1357                                     || in_polyglossia_rtl_env)
1358                                 {
1359                                         if (using_begin_end && !localswitch)
1360                                                 os << breakln;
1361                                         os << from_ascii(subst(
1362                                                 lang_end_command,
1363                                                 "$$lang",
1364                                                 par_lang));
1365                                         pending_newline = !localswitch
1366                                                         && !text.inset().getLayout().parbreakIgnored();
1367                                         unskip_newline = !localswitch;
1368                                         if (using_begin_end)
1369                                                 popLanguageName();
1370                                 }
1371                         }
1372                 }
1373         }
1374         if (closing_rtl_ltr_environment)
1375                 os << "}";
1376
1377         // InTitle commands need to be closed after the language has been closed.
1378         if (intitle_command) {
1379                 os << '}';
1380                 if (!style.postcommandargs().empty())
1381                         latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1382                 if (!runparams.post_macro.empty()) {
1383                         // Output the stored fragile commands (labels, indices etc.)
1384                         // that need to be output after the command with moving argument.
1385                         os << runparams.post_macro;
1386                         runparams.post_macro.clear();
1387                 }
1388                 if (par.needsCProtection(runparams.moving_arg)
1389                     && contains(runparams.active_chars, '^'))
1390                         os << "\\endgroup";
1391                 if (runparams.encoding != prev_encoding) {
1392                         runparams.encoding = prev_encoding;
1393                         os << setEncoding(prev_encoding->iconvName());
1394                 }
1395         }
1396
1397         bool const last_was_separator =
1398                 !par.empty() && par.isEnvSeparator(par.size() - 1);
1399
1400         // Signify added/deleted par break in output if show changes in output
1401         if (nextpar && !os.afterParbreak() && !last_was_separator
1402             && bparams.output_changes && par.parEndChange().changed()) {
1403                 Changes::latexMarkChange(os, bparams, Change(Change::UNCHANGED),
1404                                          par.parEndChange(), runparams);
1405                 os << bparams.encoding().latexString(docstring(1, 0x00b6)).first << "}";
1406         }
1407
1408         if (pending_newline) {
1409                 if (unskip_newline)
1410                         // prevent unwanted whitespace
1411                         os << '%';
1412                 if (!os.afterParbreak() && !last_was_separator)
1413                         os << '\n';
1414         }
1415
1416         // if this is a CJK-paragraph and the next isn't, close CJK
1417         // also if the next paragraph is a multilingual environment (because of nesting)
1418         if (nextpar && state->open_encoding_ == CJK
1419                 && bparams.encoding().iconvName() != "UTF-8"
1420                 && bparams.encoding().package() != Encoding::CJK
1421                 && ((nextpar_language &&
1422                         nextpar_language->encoding()->package() != Encoding::CJK)
1423                         || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1424                 // inbetween environments, CJK has to be closed later (nesting!)
1425                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1426                 os << "\\end{CJK}\n";
1427                 state->open_encoding_ = none;
1428         }
1429
1430         // If this is the last paragraph, close the CJK environment
1431         // if necessary. If it's an environment or nested in an environment,
1432         // we'll have to \end that first.
1433         if (runparams.isLastPar && !style.isEnvironment()
1434                 && par.params().depth() < 1) {
1435                 switch (state->open_encoding_) {
1436                         case CJK: {
1437                                 // do nothing at the end of child documents
1438                                 if (maintext && buf.masterBuffer() != &buf)
1439                                         break;
1440                                 // end of main text: also insert a \clearpage (see #5386)
1441                                 if (maintext) {
1442                                         os << "\n\\clearpage\n\\end{CJK}\n";
1443                                 // end of an inset
1444                                 } else
1445                                         os << "\\end{CJK}";
1446                                 state->open_encoding_ = none;
1447                                 break;
1448                         }
1449                         case inputenc: {
1450                                 // FIXME: If we are in an inset and the switch happened outside this inset,
1451                                 // do not switch back at the end of the inset (bug #8479)
1452                                 // The following attempt does not help with listings-caption in a CJK document:
1453                                 // if (runparams_in.local_font != 0
1454                                 //    && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1455                                 //      break;
1456                                 os << "\\egroup";
1457                                 state->open_encoding_ = none;
1458                                 break;
1459                         }
1460                         case none:
1461                         default:
1462                                 // do nothing
1463                                 break;
1464                 }
1465         }
1466
1467         // Information about local language is stored as a font feature.
1468         // If this is the last paragraph of the inset and a local_font was set upon entering
1469         // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1470         // ensure the encoding is set back to the default encoding of the local language.
1471         if (runparams.isLastPar && runparams_in.local_font != nullptr
1472             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1473             && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1474                 && !runparams.isFullUnicode()
1475            ) {
1476                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1477                 os << setEncoding(runparams_in.encoding->iconvName());
1478         }
1479         // Otherwise, the current encoding should be set for the next paragraph.
1480         else
1481                 runparams_in.encoding = runparams.encoding;
1482
1483         // Also pass the post_macros upstream
1484         runparams_in.post_macro = runparams.post_macro;
1485         // These need to be passed upstream as well
1486         runparams_in.need_maketitle = runparams.need_maketitle;
1487         runparams_in.have_maketitle = runparams.have_maketitle;
1488
1489
1490         // we don't need a newline for the last paragraph!!!
1491         // Note from JMarc: we will re-add a \n explicitly in
1492         // TeXEnvironment, because it is needed in this case
1493         if (nextpar && !os.afterParbreak() && !last_was_separator) {
1494                 if (!text.inset().getLayout().parbreakIgnored() && !merged_par)
1495                         // Make sure to start a new line
1496                         os << breakln;
1497                 // A newline '\n' is always output before a command,
1498                 // so avoid doubling it.
1499                 Layout const & next_layout = nextpar->layout();
1500                 if (!next_layout.isCommand()) {
1501                         // Here we now try to avoid spurious empty lines by
1502                         // outputting a paragraph break only if: (case 1) the
1503                         // paragraph style allows parbreaks and no \begin, \end
1504                         // or \item tags are going to follow (i.e., if the next
1505                         // isn't the first or the current isn't the last
1506                         // paragraph of an environment or itemize) and the
1507                         // depth and alignment of the following paragraph is
1508                         // unchanged, or (case 2) the following is a
1509                         // non-environment paragraph whose depth is increased
1510                         // but whose alignment is unchanged, or (case 3) the
1511                         // paragraph is not an environment and the next one is a
1512                         // non-itemize-like env at lower depth, or (case 4) the
1513                         // paragraph is a command not followed by an environment
1514                         // and the alignment of the current and next paragraph
1515                         // is unchanged, or (case 5) the current alignment is
1516                         // changed and a standard paragraph follows.
1517                         DocumentClass const & tclass = bparams.documentClass();
1518                         if ((style == next_layout
1519                              && !style.parbreak_is_newline
1520                              && !text.inset().getLayout().parbreakIsNewline()
1521                              && !text.inset().getLayout().parbreakIgnored()
1522                              && style.latextype != LATEX_ITEM_ENVIRONMENT
1523                              && style.latextype != LATEX_LIST_ENVIRONMENT
1524                              && style.align == par.getAlign(bparams)
1525                              && nextpar->getDepth() == par.getDepth()
1526                              && nextpar->getAlign(bparams) == par.getAlign(bparams))
1527                             || (!next_layout.isEnvironment()
1528                                 && nextpar->getDepth() > par.getDepth()
1529                                 && nextpar->getAlign(bparams) == next_layout.align)
1530                             || (!style.isEnvironment()
1531                                 && next_layout.latextype == LATEX_ENVIRONMENT
1532                                 && nextpar->getDepth() < par.getDepth())
1533                             || (style.isCommand()
1534                                 && !next_layout.isEnvironment()
1535                                 && style.align == par.getAlign(bparams)
1536                                 && next_layout.align == nextpar->getAlign(bparams))
1537                             || (style.align != par.getAlign(bparams)
1538                                 && tclass.isDefaultLayout(next_layout))) {
1539                                 // and omit paragraph break if it has been deleted with ct
1540                                 // and changes are not shown in output
1541                                 if (!merged_par) {
1542                                         if (runparams.isNonLong)
1543                                                 // This is to allow parbreak in multirow
1544                                                 // It could also be used for other non-long
1545                                                 // contexts
1546                                                 os << "\\endgraf\n";
1547                                         else
1548                                                 os << '\n';
1549                                 }
1550                         }
1551                 }
1552         }
1553
1554         // Reset language nesting level after intitle command
1555         if (intitle_command)
1556                 state->nest_level_ -= 1;
1557
1558         LYXERR(Debug::OUTFILE, "TeXOnePar for paragraph " << pit << " done; ptr "
1559                                                           << &par << " next " << nextpar);
1560
1561         return;
1562 }
1563
1564
1565 // LaTeX all paragraphs
1566 void latexParagraphs(Buffer const & buf,
1567                      Text const & text,
1568                      otexstream & os,
1569                      OutputParams const & runparams,
1570                      string const & everypar)
1571 {
1572         LASSERT(runparams.par_begin <= runparams.par_end,
1573                 { os << "% LaTeX Output Error\n"; return; } );
1574
1575         BufferParams const & bparams = buf.params();
1576         BufferParams const & mparams = buf.masterParams();
1577
1578         bool const maintext = text.isMainText();
1579         bool const is_child = buf.masterBuffer() != &buf;
1580         bool const multibib_child = maintext && is_child
1581                         && mparams.multibib == "child";
1582
1583         if (multibib_child && mparams.useBiblatex())
1584                 os << "\\newrefsection";
1585         else if (multibib_child && mparams.useBibtopic()
1586                  && !buf.masterBibInfo().empty()) {
1587                 os << "\\begin{btUnit}\n";
1588                 runparams.openbtUnit = true;
1589         }
1590
1591         // Open a CJK environment at the beginning of the main buffer
1592         // if the document's main encoding requires the CJK package
1593         // or the document encoding is utf8 and the CJK package is required
1594         // (but not in child documents or documents using system fonts):
1595         OutputState * state = getOutputState();
1596         if (maintext && !is_child && !bparams.useNonTeXFonts
1597             && (bparams.encoding().package() == Encoding::CJK
1598                         || (bparams.encoding().name() == "utf8"
1599                                 && runparams.use_CJK))
1600            ) {
1601                 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1602                                                                  ? from_ascii("UTF8")
1603                                                                  : from_ascii(bparams.encoding().latexName());
1604                 os << "\\begin{CJK}{" << cjkenc
1605                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1606                 state->open_encoding_ = CJK;
1607         }
1608         // if "auto begin" is switched off, explicitly switch the
1609         // language on at start
1610         string const mainlang = runparams.use_polyglossia
1611                 ? getPolyglossiaEnvName(bparams.language)
1612                 : bparams.language->babel();
1613         string const lang_begin_command = runparams.use_polyglossia ?
1614                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1615         string const lang_end_command = runparams.use_polyglossia ?
1616                 "\\end{$$lang}" : lyxrc.language_command_end;
1617         bool const using_begin_end = runparams.use_polyglossia ||
1618                                         !lang_end_command.empty();
1619
1620         if (maintext && !lyxrc.language_auto_begin &&
1621             !mainlang.empty()) {
1622                 // FIXME UNICODE
1623                 string bc = runparams.use_polyglossia ?
1624                             getPolyglossiaBegin(lang_begin_command, mainlang,
1625                                                 bparams.language->polyglossiaOpts())
1626                           : subst(lang_begin_command, "$$lang", mainlang);
1627                 os << bc;
1628                 os << '\n';
1629                 if (using_begin_end)
1630                         pushLanguageName(mainlang);
1631         }
1632
1633         ParagraphList const & paragraphs = text.paragraphs();
1634
1635         if (runparams.par_begin == runparams.par_end) {
1636                 // The full doc will be exported but it is easier to just rely on
1637                 // runparams range parameters that will be passed TeXEnvironment.
1638                 runparams.par_begin = 0;
1639                 runparams.par_end = static_cast<int>(paragraphs.size());
1640         }
1641
1642         pit_type pit = runparams.par_begin;
1643         // lastpit is for the language check after the loop.
1644         pit_type lastpit = pit;
1645         DocumentClass const & tclass = bparams.documentClass();
1646
1647         // Did we already warn about inTitle layout mixing? (we only warn once)
1648         bool gave_layout_warning = false;
1649         for (; pit < runparams.par_end; ++pit) {
1650                 lastpit = pit;
1651                 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
1652
1653                 // FIXME This check should not be needed. We should
1654                 // perhaps issue an error if it is.
1655                 Layout const & layout = text.inset().forcePlainLayout() ?
1656                                 tclass.plainLayout() : par->layout();
1657
1658                 if (layout.intitle) {
1659                         if (runparams.have_maketitle) {
1660                                 if (!gave_layout_warning && !runparams.dryrun) {
1661                                         gave_layout_warning = true;
1662                                         frontend::Alert::warning(_("Error in latexParagraphs"),
1663                                                         bformat(_("You are using at least one "
1664                                                           "layout (%1$s) intended for the title, "
1665                                                           "after using non-title layouts. This "
1666                                                           "could lead to missing or incorrect output."
1667                                                           ), layout.name()));
1668                                 }
1669                         } else if (!runparams.need_maketitle) {
1670                                 runparams.need_maketitle = true;
1671                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1672                                         os << "\\begin{"
1673                                                         << from_ascii(tclass.titlename())
1674                                                         << "}\n";
1675                                 }
1676                         }
1677                 } else if (runparams.need_maketitle && !runparams.have_maketitle
1678                            && !layout.inpreamble && !text.inset().isInTitle()) {
1679                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1680                                 os << "\\end{" << from_ascii(tclass.titlename())
1681                                                 << "}\n";
1682                         }
1683                         else {
1684                                 os << "\\" << from_ascii(tclass.titlename())
1685                                                 << "\n";
1686                         }
1687                         runparams.have_maketitle = true;
1688                         runparams.need_maketitle = false;
1689                 }
1690
1691                 if (layout.isCommand() && !layout.latexname().empty()
1692                     && layout.latexname() == bparams.multibib) {
1693                         if (runparams.openbtUnit)
1694                                 os << "\\end{btUnit}\n";
1695                         if (!bparams.useBiblatex()
1696                             && !buf.masterBibInfo().empty()) {
1697                                 os << '\n' << "\\begin{btUnit}\n";
1698                                 runparams.openbtUnit = true;
1699                         }
1700                 }
1701
1702                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1703                         // This is a standard top level paragraph, TeX it and continue.
1704                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1705                         continue;
1706                 }
1707
1708                 // Do not output empty environments if the whole paragraph has
1709                 // been deleted with ct and changes are not output.
1710                 bool output_changes;
1711                 if (!runparams.find_effective())
1712                         output_changes = bparams.output_changes;
1713                 else
1714                         output_changes = runparams.find_with_deleted();
1715                 bool const lastpar = size_t(pit + 1) >= paragraphs.size();
1716                 if (!lastpar) {
1717                         ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
1718                         Paragraph const & cpar = paragraphs.at(pit);
1719                         if ((par->layout() != nextpar->layout()
1720                              || par->params().depth() == nextpar->params().depth()
1721                              || par->params().leftIndent() == nextpar->params().leftIndent())
1722                             && !cpar.empty()
1723                             && cpar.isDeleted(0, cpar.size()) && !output_changes) {
1724                                 if (!cpar.parEndChange().deleted())
1725                                         os << '\n' << '\n';
1726                                 continue;
1727                         }
1728                 } else {
1729                         // This is the last par
1730                         Paragraph const & cpar = paragraphs.at(pit);
1731                         if ( !cpar.empty()
1732                             && cpar.isDeleted(0, cpar.size()) && !output_changes) {
1733                                 if (!cpar.parEndChange().deleted())
1734                                         os << '\n' << '\n';
1735                                 continue;
1736                         }
1737                 }
1738
1739                 TeXEnvironmentData const data =
1740                         prepareEnvironment(buf, text, par, os, runparams);
1741                 // pit can be changed in TeXEnvironment.
1742                 TeXEnvironment(buf, text, runparams, pit, os);
1743                 finishEnvironment(os, runparams, data, maintext, lastpar);
1744         }
1745
1746         // FIXME: uncomment the content or remove this block
1747         if (pit == runparams.par_end) {
1748                         // Make sure that the last paragraph is
1749                         // correctly terminated (because TeXOnePar does
1750                         // not add a \n in this case)
1751                         //os << '\n';
1752         }
1753
1754         // It might be that we only have a title in this document.
1755         // But if we're in an inset, this is not the end of
1756         // the document. (There may be some other checks of this
1757         // kind that are needed.)
1758         if (runparams.need_maketitle && !runparams.have_maketitle && maintext) {
1759                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1760                         os << "\\end{" << from_ascii(tclass.titlename())
1761                            << "}\n";
1762                 } else {
1763                         os << "\\" << from_ascii(tclass.titlename())
1764                            << "\n";
1765                 }
1766         }
1767
1768         if (maintext && !is_child && runparams.openbtUnit)
1769                 os << "\\end{btUnit}\n";
1770
1771         // if "auto end" is switched off, explicitly close the language at the end
1772         // but only if the last par is in a babel or polyglossia language
1773         Language const * const lastpar_language =
1774                         paragraphs.at(lastpit).getParLanguage(bparams);
1775         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1776                 lastpar_language->encoding()->package() != Encoding::CJK) {
1777                 os << from_utf8(subst(lang_end_command,
1778                                         "$$lang",
1779                                         mainlang))
1780                         << '\n';
1781                 // If we have language_auto_begin, the stack will
1782                 // already be empty, nothing to pop()
1783                 if (using_begin_end && langOpenedAtThisLevel(state))
1784                         popLanguageName();
1785         }
1786
1787         // If the last paragraph is an environment, we'll have to close
1788         // CJK at the very end to do proper nesting.
1789         if (maintext && !is_child && state->open_encoding_ == CJK) {
1790                 os << "\\clearpage\n\\end{CJK}\n";
1791                 state->open_encoding_ = none;
1792         }
1793         // Likewise for polyglossia or when using begin/end commands
1794         // or at the very end of an active branch inset with a language switch
1795         Language const * const outer_language = (runparams.local_font != nullptr)
1796                         ? runparams.local_font->language() : bparams.language;
1797         string const & prev_lang = runparams.use_polyglossia
1798                         ? getPolyglossiaEnvName(outer_language)
1799                         : outer_language->babel();
1800         string const lastpar_lang = runparams.use_polyglossia ?
1801                 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1802         string const & cur_lang = openLanguageName(state);
1803         if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1804              || (maintext && !is_child)) && !cur_lang.empty()) {
1805                 os << from_utf8(subst(lang_end_command,
1806                                         "$$lang",
1807                                         cur_lang))
1808                    << '\n';
1809                 if (using_begin_end)
1810                         popLanguageName();
1811         } else if (runparams.inbranch && !using_begin_end
1812                    && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1813                 // with !using_begin_end, cur_lang is empty, so we need to
1814                 // compare against the paragraph language (and we are in the
1815                 // last paragraph at this point)
1816                 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1817         }
1818
1819         // reset inherited encoding
1820         if (state->cjk_inherited_ > 0) {
1821                 state->cjk_inherited_ -= 1;
1822                 if (state->cjk_inherited_ == 0)
1823                         state->open_encoding_ = CJK;
1824         }
1825
1826         if (multibib_child && mparams.useBibtopic()) {
1827                 os << "\\end{btUnit}\n";
1828                 runparams.openbtUnit = false;
1829         }
1830 }
1831
1832 // Switch the input encoding for some part(s) of the document.
1833 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1834                    OutputParams const & runparams, Encoding const & newEnc,
1835                    bool force, bool noswitchmacro)
1836 {
1837         // Never switch encoding with XeTeX/LuaTeX
1838         // or if we're in a moving argument or inherit the outer encoding.
1839         if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1840                 return make_pair(false, 0);     
1841
1842         // Only switch for auto-selected legacy encodings (inputenc setting
1843         // "auto-legacy" or "auto-legacy-plain").
1844         // The "listings" environment can force a switch also with other
1845         // encoding settings (it does not support variable width encodings
1846         // (utf8, jis, ...) under 8-bit latex engines).
1847         if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1848                                    || runparams.moving_arg))
1849                 return make_pair(false, 0);
1850
1851         Encoding const & oldEnc = *runparams.encoding;
1852         // Do not switch, if the encoding is unchanged or switching is not supported.
1853         if (oldEnc.name() == newEnc.name()
1854                 || oldEnc.package() == Encoding::japanese
1855                 || oldEnc.package() == Encoding::none
1856                 || newEnc.package() == Encoding::none
1857                 || runparams.find_effective())
1858                 return make_pair(false, 0);
1859         // FIXME We ignore encoding switches from/to encodings that do
1860         // neither support the inputenc package nor the CJK package here.
1861         // This may fail for characters not supported by "unicodesymbols"
1862         // or for non-ASCII characters in "listings"
1863         // but it is the best we can do.
1864
1865         // change encoding
1866         LYXERR(Debug::OUTFILE, "Changing LaTeX encoding from "
1867                    << oldEnc.name() << " to " << newEnc.name());
1868         os << setEncoding(newEnc.iconvName());
1869         if (bparams.inputenc == "auto-legacy-plain")
1870           return make_pair(true, 0);
1871
1872         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1873         OutputState * state = getOutputState();
1874         switch (newEnc.package()) {
1875                 case Encoding::none:
1876                 case Encoding::japanese:
1877                         // shouldn't ever reach here (see above) but avoids warning.
1878                         return make_pair(true, 0);
1879                 case Encoding::inputenc: {
1880                         size_t count = inputenc_arg.length();
1881                         if (oldEnc.package() == Encoding::CJK &&
1882                             state->open_encoding_ == CJK) {
1883                                 os << "\\end{CJK}";
1884                                 state->open_encoding_ = none;
1885                                 count += 9;
1886                         }
1887                         else if (oldEnc.package() == Encoding::inputenc &&
1888                                  state->open_encoding_ == inputenc) {
1889                                 os << "\\egroup";
1890                                 state->open_encoding_ = none;
1891                                 count += 7;
1892                         }
1893                         if (runparams.local_font != nullptr
1894                             &&  oldEnc.package() == Encoding::CJK) {
1895                                 // within insets, \inputenc switches need
1896                                 // to be embraced within \bgroup...\egroup;
1897                                 // else CJK fails.
1898                                 os << "\\bgroup";
1899                                 count += 7;
1900                                 state->open_encoding_ = inputenc;
1901                         }
1902                         if (noswitchmacro)
1903                                 return make_pair(true, count);
1904                         os << "\\inputencoding{" << inputenc_arg << '}';
1905                         return make_pair(true, count + 16);
1906                 }
1907                 case Encoding::CJK: {
1908                         size_t count = inputenc_arg.length();
1909                         if (oldEnc.package() == Encoding::CJK &&
1910                             state->open_encoding_ == CJK) {
1911                                 os << "\\end{CJK}";
1912                                 count += 9;
1913                         }
1914                         if (oldEnc.package() == Encoding::inputenc &&
1915                             state->open_encoding_ == inputenc) {
1916                                 os << "\\egroup";
1917                                 count += 7;
1918                         }
1919                         os << "\\begin{CJK}{"
1920                            << from_ascii(newEnc.latexName()) << "}{"
1921                            << from_ascii(bparams.fonts_cjk) << "}";
1922                         state->open_encoding_ = CJK;
1923                         return make_pair(true, count + 15);
1924                 }
1925         }
1926         // Dead code to avoid a warning:
1927         return make_pair(true, 0);
1928 }
1929
1930 } // namespace lyx