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