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