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