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