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