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