]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
fa64895ef376ef40c67e3215d521842500af1d5e
[lyx.git] / src / output_latex.cpp
1 /**
2  * \file output_latex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "BiblioInfo.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "Encoding.h"
19 #include "Font.h"
20 #include "InsetList.h"
21 #include "Language.h"
22 #include "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_(0), 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_ != 0
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                         os << "\\cprotect";
684                 os << '\\' << from_ascii(style.latexname());
685
686                 // Command arguments
687                 if (!style.latexargs().empty())
688                         latexArgInsets(par, os, runparams, style.latexargs());
689                 os << from_ascii(style.latexparam());
690                 break;
691         case LATEX_ITEM_ENVIRONMENT:
692         case LATEX_LIST_ENVIRONMENT:
693                 if (runparams.for_search) {
694                         os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
695                 }
696                 else {
697                         os << "\\" + style.itemcommand();
698                         // Item arguments
699                         if (!style.itemargs().empty())
700                                 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
701                         os << " ";
702                 }
703                 break;
704         case LATEX_ENVIRONMENT:
705                 if (runparams.for_search) {
706                         os << "\\latexenvironment{" << style.latexname() << "}{";
707                 }
708                 break;
709         case LATEX_BIB_ENVIRONMENT:
710                 // ignore this, the inset will write itself
711                 break;
712         default:
713                 break;
714         }
715 }
716
717 } // namespace
718
719 // FIXME: this should be anonymous
720 void TeXOnePar(Buffer const & buf,
721                Text const & text,
722                pit_type pit,
723                otexstream & os,
724                OutputParams const & runparams_in,
725                string const & everypar,
726                int start_pos, int end_pos,
727                bool const force)
728 {
729         BufferParams const & bparams = runparams_in.is_child
730                 ? buf.masterParams() : buf.params();
731         ParagraphList const & paragraphs = text.paragraphs();
732         Paragraph const & par = paragraphs.at(pit);
733         // FIXME This check should not really be needed.
734         // Perhaps we should issue an error if it is.
735         Layout const & style = text.inset().forcePlainLayout() ?
736                 bparams.documentClass().plainLayout() : par.layout();
737
738         if (style.inpreamble && !force)
739                 return;
740
741         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
742                 << everypar << "'");
743
744         OutputParams runparams = runparams_in;
745         runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
746         // We reinitialize par begin and end to be on the safe side
747         // with embedded inset as we don't know if they set those
748         // value correctly.
749         runparams.par_begin = 0;
750         runparams.par_end = 0;
751
752         bool const maintext = text.isMainText();
753         // we are at the beginning of an inset and CJK is already open;
754         // we count inheritation levels to get the inset nesting right.
755         OutputState * state = getOutputState();
756         if (pit == 0 && !maintext
757             && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
758                 state->cjk_inherited_ += 1;
759                 state->open_encoding_ = none;
760         }
761
762         if (text.inset().isPassThru()) {
763                 Font const outerfont = text.outerFont(pit);
764
765                 // No newline before first paragraph in this lyxtext
766                 if (pit > 0) {
767                         os << '\n';
768                         if (!text.inset().getLayout().parbreakIsNewline())
769                                 os << '\n';
770                 }
771
772                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
773                 return;
774         }
775
776         Paragraph const * nextpar = runparams.isLastPar
777                 ? 0 : &paragraphs.at(pit + 1);
778
779         bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
780
781         if (style.pass_thru) {
782                 Font const outerfont = text.outerFont(pit);
783                 parStartCommand(par, os, runparams, style);
784                 if (style.isCommand() && style.needprotect)
785                         // Due to the moving argument, some fragile
786                         // commands (labels, index entries)
787                         // are output after this command (#2154)
788                         runparams.postpone_fragile_stuff = true;
789                 if (intitle_command)
790                         os << '{';
791
792                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
793
794                 // I did not create a parEndCommand for this minuscule
795                 // task because in the other user of parStartCommand
796                 // the code is different (JMarc)
797                 if (style.isCommand())
798                         os << "}\n";
799                 else
800                         os << '\n';
801                 if (!style.parbreak_is_newline) {
802                         os << '\n';
803                 } else if (nextpar && !style.isEnvironment()) {
804                         Layout const nextstyle = text.inset().forcePlainLayout()
805                                 ? bparams.documentClass().plainLayout()
806                                 : nextpar->layout();
807                         if (nextstyle.name() != style.name())
808                                 os << '\n';
809                 }
810
811                 return;
812         }
813
814         // This paragraph's language
815         Language const * const par_language = par.getParLanguage(bparams);
816         Language const * const nextpar_language = nextpar ?
817                 nextpar->getParLanguage(bparams) : 0;
818         // The document's language
819         Language const * const doc_language = bparams.language;
820         // The language that was in effect when the environment this paragraph is
821         // inside of was opened
822         Language const * const outer_language =
823                 (runparams.local_font != 0) ?
824                         runparams.local_font->language() : doc_language;
825
826         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
827
828         // The previous language that was in effect is the language of the
829         // previous paragraph, unless the previous paragraph is inside an
830         // environment with nesting depth greater than (or equal to, but with
831         // a different layout) the current one. If there is no previous
832         // paragraph, the previous language is the outer language.
833         // Note further that we take the outer language also if the prior par
834         // is PassThru, since in that case it has latex_language, and all secondary
835         // languages have been closed (#10793).
836         bool const use_prev_env_language = state->prev_env_language_ != 0
837                         && priorpar
838                         && priorpar->layout().isEnvironment()
839                         && (priorpar->getDepth() > par.getDepth()
840                             || (priorpar->getDepth() == par.getDepth()
841                                     && priorpar->layout() != par.layout()));
842         Language const * const prev_language =
843                 runparams_in.for_search ?
844                         languages.getLanguage("ignore")
845                 :(priorpar && !priorpar->isPassThru())
846                         ? (use_prev_env_language ? state->prev_env_language_
847                                                 : priorpar->getParLanguage(bparams))
848                         : outer_language;
849
850         bool const use_polyglossia = runparams.use_polyglossia;
851         string const par_lang = use_polyglossia ?
852                 getPolyglossiaEnvName(par_language): par_language->babel();
853         string const prev_lang = use_polyglossia ?
854                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
855         string const outer_lang = use_polyglossia ?
856                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
857         string const nextpar_lang = nextpar_language ? (use_polyglossia ?
858                 getPolyglossiaEnvName(nextpar_language) :
859                 nextpar_language->babel()) : string();
860         string lang_begin_command = use_polyglossia ?
861                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
862         string lang_end_command = use_polyglossia ?
863                 "\\end{$$lang}" : lyxrc.language_command_end;
864         // the '%' is necessary to prevent unwanted whitespace
865         string lang_command_termination = "%\n";
866         bool const using_begin_end = use_polyglossia ||
867                                         !lang_end_command.empty();
868
869         // For InTitle commands, we need to switch the language inside the command
870         // (see #10849); thus open the command here.
871         if (intitle_command) {
872                 parStartCommand(par, os, runparams, style);
873                 if (style.isCommand() && style.needprotect)
874                         // Due to the moving argument, some fragile
875                         // commands (labels, index entries)
876                         // are output after this command (#2154)
877                         runparams.postpone_fragile_stuff = true;
878                 os << '{';
879         }
880
881         // In some insets (such as Arguments), we cannot use \selectlanguage.
882         // Also, if an RTL language is set via environment in polyglossia,
883         // only a nested \\text<lang> command will reset the direction for LTR
884         // languages (see # 10111).
885         bool const in_polyglossia_rtl_env =
886                 use_polyglossia
887                 && runparams.local_font != 0
888                 && outer_language->rightToLeft()
889                 && !par_language->rightToLeft();
890         bool const localswitch = runparams_in.for_search
891                         || text.inset().forceLocalFontSwitch()
892                         || (using_begin_end && text.inset().forcePlainLayout())
893                         || in_polyglossia_rtl_env;
894         if (localswitch) {
895                 lang_begin_command = use_polyglossia ?
896                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
897                 lang_end_command = "}";
898                 lang_command_termination.clear();
899         }
900
901         bool const localswitch_needed = localswitch && par_lang != outer_lang;
902
903         // localswitches need to be closed and reopened at each par
904         if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
905              // check if we already put language command in TeXEnvironment()
906              && !(style.isEnvironment()
907                   && (pit == 0 || (priorpar->layout() != par.layout()
908                                    && priorpar->getDepth() <= par.getDepth())
909                       || priorpar->getDepth() < par.getDepth())))) {
910                 if (!localswitch
911                     && (!using_begin_end || langOpenedAtThisLevel(state))
912                     && !lang_end_command.empty()
913                     && prev_lang != outer_lang
914                     && !prev_lang.empty()
915                     && (!using_begin_end || !style.isEnvironment())) {
916                         os << from_ascii(subst(lang_end_command,
917                                                "$$lang",
918                                                prev_lang))
919                            << lang_command_termination;
920                         if (using_begin_end)
921                                 popLanguageName();
922                 }
923
924                 // We need to open a new language if we couldn't close the previous
925                 // one (because there's no language_command_end); and even if we closed
926                 // the previous one, if the current language is different than the
927                 // outer_language (which is currently in effect once the previous one
928                 // is closed).
929                 if ((lang_end_command.empty() || par_lang != outer_lang
930                      || (!using_begin_end
931                          || (style.isEnvironment() && par_lang != prev_lang)))
932                         && !par_lang.empty()) {
933                         // If we're inside an inset, and that inset is within an \L or \R
934                         // (or equivalents), then within the inset, too, any opposite
935                         // language paragraph should appear within an \L or \R (in addition
936                         // to, outside of, the normal language switch commands).
937                         // This behavior is not correct for ArabTeX, though.
938                         if (!using_begin_end
939                             // not for ArabTeX
940                             && par_language->lang() != "arabic_arabtex"
941                             && outer_language->lang() != "arabic_arabtex"
942                             // are we in an inset?
943                             && runparams.local_font != 0
944                             // is the inset within an \L or \R?
945                             //
946                             // FIXME: currently, we don't check this; this means that
947                             // we'll have unnnecessary \L and \R commands, but that
948                             // doesn't seem to hurt (though latex will complain)
949                             //
950                             // is this paragraph in the opposite direction?
951                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
952                                 // FIXME: I don't have a working copy of the Arabi package, so
953                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
954                                 // or not...
955                                 if (par_language->lang() == "farsi")
956                                         os << "\\textFR{";
957                                 else if (outer_language->lang() == "farsi")
958                                         os << "\\textLR{";
959                                 else if (par_language->lang() == "arabic_arabi")
960                                         os << "\\textAR{";
961                                 else if (outer_language->lang() == "arabic_arabi")
962                                         os << "\\textLR{";
963                                 // remaining RTL languages currently is hebrew
964                                 else if (par_language->rightToLeft())
965                                         os << "\\R{";
966                                 else
967                                         os << "\\L{";
968                         }
969                         // With CJK, the CJK tag has to be closed first (see below)
970                         if ((runparams.encoding->package() != Encoding::CJK || runparams.for_search)
971                             && (par_lang != openLanguageName(state) || localswitch)
972                             && !par_lang.empty()) {
973                                 string bc = use_polyglossia ?
974                                           getPolyglossiaBegin(lang_begin_command, par_lang,
975                                                               par_language->polyglossiaOpts(),
976                                                               localswitch)
977                                           : subst(lang_begin_command, "$$lang", par_lang);
978                                 os << bc;
979                                 os << lang_command_termination;
980                                 if (using_begin_end)
981                                         pushLanguageName(par_lang, localswitch);
982                         }
983                 }
984         }
985
986         // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
987         // encoding, since this only affects the position of the outputted
988         // \inputencoding command; the encoding switch will occur when necessary
989         if (bparams.inputenc == "auto-legacy"
990                 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding  (see also switchEncoding())
991                 && runparams.encoding->package() != Encoding::japanese
992                 && runparams.encoding->package() != Encoding::none) {
993                 // Look ahead for future encoding changes.
994                 // We try to output them at the beginning of the paragraph,
995                 // since the \inputencoding command is not allowed e.g. in
996                 // sections. For this reason we only set runparams.moving_arg
997                 // after checking for the encoding change, otherwise the
998                 // change would be always avoided by switchEncoding().
999                 for (pos_type i = 0; i < par.size(); ++i) {
1000                         char_type const c = par.getChar(i);
1001                         Encoding const * const encoding =
1002                                 par.getFontSettings(bparams, i).language()->encoding();
1003                         if (encoding->package() != Encoding::CJK
1004                                 && runparams.encoding->package() == Encoding::inputenc
1005                                 && isASCII(c))
1006                                 continue;
1007                         if (par.isInset(i))
1008                                 break;
1009                         // All characters before c are in the ASCII range, and
1010                         // c is non-ASCII (but no inset), so change the
1011                         // encoding to that required by the language of c.
1012                         // With CJK, only add switch if we have CJK content at the beginning
1013                         // of the paragraph
1014                         if (i != 0 && encoding->package() == Encoding::CJK)
1015                                 continue;
1016
1017                         pair<bool, int> enc_switch = switchEncoding(os.os(),
1018                                                 bparams, runparams, *encoding);
1019                         // the following is necessary after a CJK environment in a multilingual
1020                         // context (nesting issue).
1021                         if (par_language->encoding()->package() == Encoding::CJK
1022                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1023                                 os << "\\begin{CJK}{"
1024                                    << from_ascii(par_language->encoding()->latexName())
1025                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1026                                 state->open_encoding_ = CJK;
1027                         }
1028                         if (encoding->package() != Encoding::none && enc_switch.first) {
1029                                 if (enc_switch.second > 0) {
1030                                         // the '%' is necessary to prevent unwanted whitespace
1031                                         os << "%\n";
1032                                 }
1033                                 // With CJK, the CJK tag had to be closed first (see above)
1034                                 if (runparams.encoding->package() == Encoding::CJK
1035                                     && par_lang != openLanguageName(state)
1036                                     && !par_lang.empty()) {
1037                                         os << subst(lang_begin_command, "$$lang", par_lang)
1038                                            << lang_command_termination;
1039                                         if (using_begin_end)
1040                                                 pushLanguageName(par_lang, localswitch);
1041                                 }
1042                                 runparams.encoding = encoding;
1043                         }
1044                         break;
1045                 }
1046         }
1047
1048         runparams.moving_arg |= style.needprotect;
1049         if (style.needmboxprotect)
1050                 ++runparams.inulemcmd;
1051         Encoding const * const prev_encoding = runparams.encoding;
1052
1053         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1054         if (par.allowParagraphCustomization()) {
1055                 if (par.params().startOfAppendix()) {
1056                         os << "\n\\appendix\n";
1057                 }
1058
1059                 // InTitle commands must use switches (not environments)
1060                 // inside the commands (see #9332)
1061                 if (style.intitle) {
1062                         if (!par.params().spacing().isDefault())
1063                         {
1064                                 if (runparams.moving_arg)
1065                                         os << "\\protect";
1066                                 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1067                         }
1068                 } else {
1069                         if (!par.params().spacing().isDefault()
1070                                 && (pit == 0 || !priorpar->hasSameLayout(par)))
1071                         {
1072                                 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1073                                     << '\n';
1074                         }
1075
1076                         if (style.isCommand()) {
1077                                 os << '\n';
1078                         }
1079                 }
1080         }
1081
1082         // For InTitle commands, we already started the command before
1083         // the language switch
1084         if (!intitle_command) {
1085                 parStartCommand(par, os, runparams, style);
1086                 if (style.isCommand() && style.needprotect)
1087                         // Due to the moving argument, some fragile
1088                         // commands (labels, index entries)
1089                         // are output after this command (#2154)
1090                         runparams.postpone_fragile_stuff = true;
1091         }
1092
1093         Font const outerfont = text.outerFont(pit);
1094
1095         // FIXME UNICODE
1096         os << from_utf8(everypar);
1097         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1098
1099         Font const font = par.empty()
1100                  ? par.getLayoutFont(bparams, outerfont)
1101                  : par.getFont(bparams, par.size() - 1, outerfont);
1102
1103         bool const is_command = style.isCommand();
1104
1105         // InTitle commands need to be closed after the language has been closed.
1106         if (!intitle_command) {
1107                 if (is_command) {
1108                         os << '}';
1109                         if (!style.postcommandargs().empty())
1110                                 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1111                         if (!runparams.post_macro.empty()) {
1112                                 // Output the stored fragile commands (labels, indices etc.)
1113                                 // that need to be output after the command with moving argument.
1114                                 os << runparams.post_macro;
1115                                 runparams.post_macro.clear();
1116                         }
1117                         if (runparams.encoding != prev_encoding) {
1118                                 runparams.encoding = prev_encoding;
1119                                 os << setEncoding(prev_encoding->iconvName());
1120                         }
1121                 }
1122         }
1123
1124         bool pending_newline = false;
1125         bool unskip_newline = false;
1126         bool close_lang_switch = false;
1127         switch (style.latextype) {
1128         case LATEX_ITEM_ENVIRONMENT:
1129         case LATEX_LIST_ENVIRONMENT:
1130                 if ((nextpar && par_lang != nextpar_lang
1131                              && nextpar->getDepth() == par.getDepth())
1132                     || (atSameLastLangSwitchDepth(state) && nextpar
1133                             && nextpar->getDepth() < par.getDepth()))
1134                         close_lang_switch = using_begin_end;
1135                 if (nextpar && par.params().depth() < nextpar->params().depth())
1136                         pending_newline = true;
1137                 break;
1138         case LATEX_ENVIRONMENT: {
1139                 // if it's the last paragraph of the current environment
1140                 // skip it otherwise fall through
1141                 if (nextpar
1142                     && ((nextpar->layout() != par.layout()
1143                            || nextpar->params().depth() != par.params().depth())
1144                         || (!using_begin_end || par_lang != nextpar_lang)))
1145                 {
1146                         close_lang_switch = using_begin_end;
1147                         break;
1148                 }
1149         }
1150         // possible
1151         // fall through
1152         default:
1153                 // we don't need it for the last paragraph and in InTitle commands!!!
1154                 if (nextpar && !intitle_command)
1155                         pending_newline = true;
1156         }
1157
1158         // InTitle commands use switches (not environments) for space settings
1159         if (par.allowParagraphCustomization() && !style.intitle) {
1160                 if (!par.params().spacing().isDefault()
1161                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1162                         if (pending_newline)
1163                                 os << '\n';
1164
1165                         string const endtag =
1166                                 par.params().spacing().writeEnvirEnd(useSetSpace);
1167                         if (prefixIs(endtag, "\\end{"))
1168                                 os << breakln;
1169
1170                         os << from_ascii(endtag);
1171                         pending_newline = true;
1172                 }
1173         }
1174
1175         // Closing the language is needed for the last paragraph in a given language
1176         // as well as for any InTitleCommand (since these set the language locally);
1177         // it is also needed if we're within an \L or \R that we may have opened above
1178         // (not necessarily in this paragraph) and are about to close.
1179         bool closing_rtl_ltr_environment = !using_begin_end
1180                 // not for ArabTeX
1181                 && (par_language->lang() != "arabic_arabtex"
1182                     && outer_language->lang() != "arabic_arabtex")
1183                 // have we opened an \L or \R environment?
1184                 && runparams.local_font != 0
1185                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1186                 // are we about to close the language?
1187                 &&((nextpar && par_lang != nextpar_lang)
1188                    || (runparams.isLastPar && par_lang != outer_lang));
1189
1190         if (localswitch_needed
1191             || (intitle_command && using_begin_end)
1192             || closing_rtl_ltr_environment
1193             || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1194                 && (par_lang != outer_lang || (using_begin_end
1195                                                 && style.isEnvironment()
1196                                                 && par_lang != nextpar_lang)))) {
1197                 // Since \selectlanguage write the language to the aux file,
1198                 // we need to reset the language at the end of footnote or
1199                 // float.
1200
1201                 if (!localswitch && (pending_newline || close_lang_switch))
1202                         os << '\n';
1203
1204                 // when the paragraph uses CJK, the language has to be closed earlier
1205                 if ((font.language()->encoding()->package() != Encoding::CJK) || runparams_in.for_search) {
1206                         if (lang_end_command.empty()) {
1207                                 // If this is a child, we should restore the
1208                                 // master language after the last paragraph.
1209                                 Language const * const current_language =
1210                                         (runparams.isLastPar && runparams.master_language)
1211                                                 ? runparams.master_language
1212                                                 : outer_language;
1213                                 string const current_lang = use_polyglossia
1214                                         ? getPolyglossiaEnvName(current_language)
1215                                         : current_language->babel();
1216                                 if (!current_lang.empty()
1217                                     && current_lang != openLanguageName(state)) {
1218                                         string bc = use_polyglossia ?
1219                                                     getPolyglossiaBegin(lang_begin_command, current_lang,
1220                                                                         current_language->polyglossiaOpts(),
1221                                                                         localswitch)
1222                                                   : subst(lang_begin_command, "$$lang", current_lang);
1223                                         os << bc;
1224                                         pending_newline = !localswitch;
1225                                         unskip_newline = !localswitch;
1226                                         if (using_begin_end)
1227                                                 pushLanguageName(current_lang, localswitch);
1228                                 }
1229                         } else if ((!using_begin_end ||
1230                                     langOpenedAtThisLevel(state)) &&
1231                                    !par_lang.empty()) {
1232                                 // If we are in an environment, we have to
1233                                 // close the "outer" language afterwards
1234                                 string const & cur_lang = openLanguageName(state);
1235                                 if (!style.isEnvironment()
1236                                     || (close_lang_switch
1237                                         && atSameLastLangSwitchDepth(state)
1238                                         && par_lang != outer_lang
1239                                         && (par_lang != cur_lang
1240                                             || (cur_lang != outer_lang
1241                                                 && nextpar
1242                                                 && style != nextpar->layout())))
1243                                     || (atSameLastLangSwitchDepth(state)
1244                                         && state->lang_switch_depth_.size()
1245                                         && cur_lang != par_lang)
1246                                     || in_polyglossia_rtl_env)
1247                                 {
1248                                         if (using_begin_end && !localswitch)
1249                                                 os << breakln;
1250                                         os << from_ascii(subst(
1251                                                 lang_end_command,
1252                                                 "$$lang",
1253                                                 par_lang));
1254                                         pending_newline = !localswitch;
1255                                         unskip_newline = !localswitch;
1256                                         if (using_begin_end)
1257                                                 popLanguageName();
1258                                 }
1259                         }
1260                 }
1261         }
1262         if (closing_rtl_ltr_environment)
1263                 os << "}";
1264
1265         // InTitle commands need to be closed after the language has been closed.
1266         if (intitle_command) {
1267                 if (is_command) {
1268                         os << '}';
1269                         if (!style.postcommandargs().empty())
1270                                 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1271                         if (!runparams.post_macro.empty()) {
1272                                 // Output the stored fragile commands (labels, indices etc.)
1273                                 // that need to be output after the command with moving argument.
1274                                 os << runparams.post_macro;
1275                                 runparams.post_macro.clear();
1276                         }
1277                         if (runparams.encoding != prev_encoding) {
1278                                 runparams.encoding = prev_encoding;
1279                                 os << setEncoding(prev_encoding->iconvName());
1280                         }
1281                 }
1282         }
1283
1284         bool const last_was_separator =
1285                 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1286
1287         if (pending_newline) {
1288                 if (unskip_newline)
1289                         // prevent unwanted whitespace
1290                         os << '%';
1291                 if (!os.afterParbreak() && !last_was_separator)
1292                         os << '\n';
1293         }
1294
1295         // if this is a CJK-paragraph and the next isn't, close CJK
1296         // also if the next paragraph is a multilingual environment (because of nesting)
1297         if (nextpar
1298                 && (state->open_encoding_ == CJK && bparams.encoding().iconvName() != "UTF-8"
1299                         && bparams.encoding().package() != Encoding::CJK )
1300                 && (nextpar_language->encoding()->package() != Encoding::CJK
1301                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1302                 // inbetween environments, CJK has to be closed later (nesting!)
1303                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1304                 os << "\\end{CJK}\n";
1305                 state->open_encoding_ = none;
1306         }
1307
1308         // If this is the last paragraph, close the CJK environment
1309         // if necessary. If it's an environment or nested in an environment,
1310         // we'll have to \end that first.
1311         if (runparams.isLastPar && !style.isEnvironment()
1312                 && par.params().depth() < 1) {
1313                 switch (state->open_encoding_) {
1314                         case CJK: {
1315                                 // do nothing at the end of child documents
1316                                 if (maintext && buf.masterBuffer() != &buf)
1317                                         break;
1318                                 // end of main text: also insert a \clearpage (see #5386)
1319                                 if (maintext) {
1320                                         os << "\n\\clearpage\n\\end{CJK}\n";
1321                                 // end of an inset
1322                                 } else
1323                                         os << "\\end{CJK}";
1324                                 state->open_encoding_ = none;
1325                                 break;
1326                         }
1327                         case inputenc: {
1328                                 // FIXME: If we are in an inset and the switch happened outside this inset,
1329                                 // do not switch back at the end of the inset (bug #8479)
1330                                 // The following attempt does not help with listings-caption in a CJK document:
1331                                 // if (runparams_in.local_font != 0
1332                                 //    && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1333                                 //      break;
1334                                 os << "\\egroup";
1335                                 state->open_encoding_ = none;
1336                                 break;
1337                         }
1338                         case none:
1339                         default:
1340                                 // do nothing
1341                                 break;
1342                 }
1343         }
1344
1345         // Information about local language is stored as a font feature.
1346         // If this is the last paragraph of the inset and a local_font was set upon entering
1347         // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1348         // ensure the encoding is set back to the default encoding of the local language.
1349         if (runparams.isLastPar && runparams_in.local_font != 0
1350             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1351             && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1352                 && !runparams.isFullUnicode()
1353            ) {
1354                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1355                 os << setEncoding(runparams_in.encoding->iconvName());
1356         }
1357         // Otherwise, the current encoding should be set for the next paragraph.
1358         else
1359                 runparams_in.encoding = runparams.encoding;
1360
1361         // Also pass the post_macros upstream
1362         runparams_in.post_macro = runparams.post_macro;
1363
1364
1365         // we don't need a newline for the last paragraph!!!
1366         // Note from JMarc: we will re-add a \n explicitly in
1367         // TeXEnvironment, because it is needed in this case
1368         if (nextpar && !os.afterParbreak() && !last_was_separator) {
1369                 // Make sure to start a new line
1370                 os << breakln;
1371                 Layout const & next_layout = nextpar->layout();
1372                 // A newline '\n' is always output before a command,
1373                 // so avoid doubling it.
1374                 if (!next_layout.isCommand()) {
1375                         // Here we now try to avoid spurious empty lines by
1376                         // outputting a paragraph break only if: (case 1) the
1377                         // paragraph style allows parbreaks and no \begin, \end
1378                         // or \item tags are going to follow (i.e., if the next
1379                         // isn't the first or the current isn't the last
1380                         // paragraph of an environment or itemize) and the
1381                         // depth and alignment of the following paragraph is
1382                         // unchanged, or (case 2) the following is a
1383                         // non-environment paragraph whose depth is increased
1384                         // but whose alignment is unchanged, or (case 3) the
1385                         // paragraph is not an environment and the next one is a
1386                         // non-itemize-like env at lower depth, or (case 4) the
1387                         // paragraph is a command not followed by an environment
1388                         // and the alignment of the current and next paragraph
1389                         // is unchanged, or (case 5) the current alignment is
1390                         // changed and a standard paragraph follows.
1391                         DocumentClass const & tclass = bparams.documentClass();
1392                         if ((style == next_layout
1393                              && !style.parbreak_is_newline
1394                              && !text.inset().getLayout().parbreakIsNewline()
1395                              && style.latextype != LATEX_ITEM_ENVIRONMENT
1396                              && style.latextype != LATEX_LIST_ENVIRONMENT
1397                              && style.align == par.getAlign()
1398                              && nextpar->getDepth() == par.getDepth()
1399                              && nextpar->getAlign() == par.getAlign())
1400                             || (!next_layout.isEnvironment()
1401                                 && nextpar->getDepth() > par.getDepth()
1402                                 && nextpar->getAlign() == next_layout.align)
1403                             || (!style.isEnvironment()
1404                                 && next_layout.latextype == LATEX_ENVIRONMENT
1405                                 && nextpar->getDepth() < par.getDepth())
1406                             || (style.isCommand()
1407                                 && !next_layout.isEnvironment()
1408                                 && style.align == par.getAlign()
1409                                 && next_layout.align == nextpar->getAlign())
1410                             || (style.align != par.getAlign()
1411                                 && tclass.isDefaultLayout(next_layout))) {
1412                                 os << '\n';
1413                         }
1414                 }
1415         }
1416
1417         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1418                 << &par << " next " << nextpar);
1419
1420         return;
1421 }
1422
1423
1424 // LaTeX all paragraphs
1425 void latexParagraphs(Buffer const & buf,
1426                      Text const & text,
1427                      otexstream & os,
1428                      OutputParams const & runparams,
1429                      string const & everypar)
1430 {
1431         LASSERT(runparams.par_begin <= runparams.par_end,
1432                 { os << "% LaTeX Output Error\n"; return; } );
1433
1434         BufferParams const & bparams = buf.params();
1435         BufferParams const & mparams = buf.masterParams();
1436
1437         bool const maintext = text.isMainText();
1438         bool const is_child = buf.masterBuffer() != &buf;
1439         bool const multibib_child = maintext && is_child
1440                         && mparams.multibib == "child";
1441
1442         if (multibib_child && mparams.useBiblatex())
1443                 os << "\\newrefsection";
1444         else if (multibib_child && mparams.useBibtopic()
1445                  && !buf.masterBibInfo().empty()) {
1446                 os << "\\begin{btUnit}\n";
1447                 runparams.openbtUnit = true;
1448         }
1449
1450         // Open a CJK environment at the beginning of the main buffer
1451         // if the document's main encoding requires the CJK package
1452         // or the document encoding is utf8 and the CJK package is required
1453         // (but not in child documents or documents using system fonts):
1454         OutputState * state = getOutputState();
1455         if (maintext && !is_child && !bparams.useNonTeXFonts
1456             && (bparams.encoding().package() == Encoding::CJK
1457                         || (bparams.encoding().name() == "utf8"
1458                                 && runparams.use_CJK))
1459            ) {
1460                 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1461                                                                  ? from_ascii("UTF8") : from_ascii(bparams.encoding().latexName());
1462                 os << "\\begin{CJK}{" << cjkenc
1463                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1464                 state->open_encoding_ = CJK;
1465         }
1466         // if "auto begin" is switched off, explicitly switch the
1467         // language on at start
1468         string const mainlang = runparams.use_polyglossia
1469                 ? getPolyglossiaEnvName(bparams.language)
1470                 : bparams.language->babel();
1471         string const lang_begin_command = runparams.use_polyglossia ?
1472                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1473         string const lang_end_command = runparams.use_polyglossia ?
1474                 "\\end{$$lang}" : lyxrc.language_command_end;
1475         bool const using_begin_end = runparams.use_polyglossia ||
1476                                         !lang_end_command.empty();
1477
1478         if (maintext && !lyxrc.language_auto_begin &&
1479             !mainlang.empty()) {
1480                 // FIXME UNICODE
1481                 string bc = runparams.use_polyglossia ?
1482                             getPolyglossiaBegin(lang_begin_command, mainlang,
1483                                                 bparams.language->polyglossiaOpts())
1484                           : subst(lang_begin_command, "$$lang", mainlang);
1485                 os << bc;
1486                 os << '\n';
1487                 if (using_begin_end)
1488                         pushLanguageName(mainlang);
1489         }
1490
1491         ParagraphList const & paragraphs = text.paragraphs();
1492
1493         if (runparams.par_begin == runparams.par_end) {
1494                 // The full doc will be exported but it is easier to just rely on
1495                 // runparams range parameters that will be passed TeXEnvironment.
1496                 runparams.par_begin = 0;
1497                 runparams.par_end = paragraphs.size();
1498         }
1499
1500         pit_type pit = runparams.par_begin;
1501         // lastpit is for the language check after the loop.
1502         pit_type lastpit = pit;
1503         // variables used in the loop:
1504         bool was_title = false;
1505         bool already_title = false;
1506         DocumentClass const & tclass = bparams.documentClass();
1507
1508         // Did we already warn about inTitle layout mixing? (we only warn once)
1509         bool gave_layout_warning = false;
1510         for (; pit < runparams.par_end; ++pit) {
1511                 lastpit = pit;
1512                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1513
1514                 // FIXME This check should not be needed. We should
1515                 // perhaps issue an error if it is.
1516                 Layout const & layout = text.inset().forcePlainLayout() ?
1517                                 tclass.plainLayout() : par->layout();
1518
1519                 if (layout.intitle) {
1520                         if (already_title) {
1521                                 if (!gave_layout_warning && !runparams.dryrun) {
1522                                         gave_layout_warning = true;
1523                                         frontend::Alert::warning(_("Error in latexParagraphs"),
1524                                                         bformat(_("You are using at least one "
1525                                                           "layout (%1$s) intended for the title, "
1526                                                           "after using non-title layouts. This "
1527                                                           "could lead to missing or incorrect output."
1528                                                           ), layout.name()));
1529                                 }
1530                         } else if (!was_title) {
1531                                 was_title = true;
1532                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1533                                         os << "\\begin{"
1534                                                         << from_ascii(tclass.titlename())
1535                                                         << "}\n";
1536                                 }
1537                         }
1538                 } else if (was_title && !already_title && !layout.inpreamble) {
1539                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1540                                 os << "\\end{" << from_ascii(tclass.titlename())
1541                                                 << "}\n";
1542                         }
1543                         else {
1544                                 os << "\\" << from_ascii(tclass.titlename())
1545                                                 << "\n";
1546                         }
1547                         already_title = true;
1548                         was_title = false;
1549                 }
1550
1551                 if (layout.isCommand() && !layout.latexname().empty()
1552                     && layout.latexname() == bparams.multibib) {
1553                         if (runparams.openbtUnit)
1554                                 os << "\\end{btUnit}\n";
1555                         if (!bparams.useBiblatex()
1556                             && !buf.masterBibInfo().empty()) {
1557                                 os << '\n' << "\\begin{btUnit}\n";
1558                                 runparams.openbtUnit = true;
1559                         }
1560                 }
1561
1562                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1563                         // This is a standard top level paragraph, TeX it and continue.
1564                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1565                         continue;
1566                 }
1567
1568                 TeXEnvironmentData const data =
1569                         prepareEnvironment(buf, text, par, os, runparams);
1570                 // pit can be changed in TeXEnvironment.
1571                 TeXEnvironment(buf, text, runparams, pit, os);
1572                 finishEnvironment(os, runparams, data);
1573         }
1574
1575         if (pit == runparams.par_end) {
1576                         // Make sure that the last paragraph is
1577                         // correctly terminated (because TeXOnePar does
1578                         // not add a \n in this case)
1579                         //os << '\n';
1580         }
1581
1582         // It might be that we only have a title in this document
1583         if (was_title && !already_title) {
1584                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1585                         os << "\\end{" << from_ascii(tclass.titlename())
1586                            << "}\n";
1587                 } else {
1588                         os << "\\" << from_ascii(tclass.titlename())
1589                            << "\n";
1590                 }
1591         }
1592
1593         if (maintext && !is_child && runparams.openbtUnit)
1594                 os << "\\end{btUnit}\n";
1595
1596         // if "auto end" is switched off, explicitly close the language at the end
1597         // but only if the last par is in a babel or polyglossia language
1598         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1599                 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1600                 os << from_utf8(subst(lang_end_command,
1601                                         "$$lang",
1602                                         mainlang))
1603                         << '\n';
1604                 if (using_begin_end)
1605                         popLanguageName();
1606         }
1607
1608         // If the last paragraph is an environment, we'll have to close
1609         // CJK at the very end to do proper nesting.
1610         if (maintext && !is_child && state->open_encoding_ == CJK) {
1611                 os << "\\clearpage\n\\end{CJK}\n";
1612                 state->open_encoding_ = none;
1613         }
1614         // Likewise for polyglossia or when using begin/end commands
1615         // or after an active branch inset with a language switch
1616         Language const * const outer_language = (runparams.local_font != 0)
1617                         ? runparams.local_font->language() : bparams.language;
1618         string const & prev_lang = runparams.use_polyglossia
1619                         ? getPolyglossiaEnvName(outer_language)
1620                         : outer_language->babel();
1621         string const & cur_lang = openLanguageName(state);
1622         if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1623              || (maintext && !is_child)) && !cur_lang.empty()) {
1624                 os << from_utf8(subst(lang_end_command,
1625                                         "$$lang",
1626                                         cur_lang))
1627                    << '\n';
1628                 if (using_begin_end)
1629                         popLanguageName();
1630         } else if (runparams.inbranch && !using_begin_end && prev_lang != cur_lang) {
1631                 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1632         }
1633
1634         // reset inherited encoding
1635         if (state->cjk_inherited_ > 0) {
1636                 state->cjk_inherited_ -= 1;
1637                 if (state->cjk_inherited_ == 0)
1638                         state->open_encoding_ = CJK;
1639         }
1640
1641         if (multibib_child && mparams.useBibtopic()) {
1642                 os << "\\end{btUnit}\n";
1643                 runparams.openbtUnit = false;
1644         }
1645 }
1646
1647 // Switch the input encoding for some part(s) of the document.
1648 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1649                    OutputParams const & runparams, Encoding const & newEnc,
1650                    bool force, bool noswitchmacro)
1651 {
1652         // Never switch encoding with non-TeX fonts (always "utf8plain"),
1653         // with LuaTeX and TeX fonts (only one encoding accepted by luainputenc),
1654         // or if we're in a moving argument or inherit the outer encoding.
1655         if (bparams.useNonTeXFonts
1656                 || runparams.flavor == OutputParams::LUATEX
1657                 || runparams.flavor == OutputParams::DVILUATEX
1658                 || newEnc.name() == "inherit")
1659           return make_pair(false, 0);
1660
1661         // Only switch for auto-selected legacy encodings (inputenc setting
1662         // "auto-legacy" or "auto-legacy-plain").
1663         // The "listings" environment can force a switch also with other
1664         // encoding settings (it does not support variable width encodings
1665         // (utf8, jis, ...) under 8-bit latex engines).
1666         if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1667                                    || runparams.moving_arg))
1668                 return make_pair(false, 0);
1669
1670         Encoding const & oldEnc = *runparams.encoding;
1671         // Do not switch, if the encoding is unchanged or switching is not supported.
1672         if (oldEnc.name() == newEnc.name()
1673                 || oldEnc.package() == Encoding::japanese
1674                 || oldEnc.package() == Encoding::none
1675                 || newEnc.package() == Encoding::none
1676                 || runparams.for_search)
1677                 return make_pair(false, 0);
1678         // FIXME We ignore encoding switches from/to encodings that do
1679         // neither support the inputenc package nor the CJK package here.
1680         // This may fail for characters not supported by "unicodesymbols"
1681         // or for non-ASCII characters in "listings"
1682         // but it is the best we can do.
1683
1684         // change encoding
1685         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1686                    << oldEnc.name() << " to " << newEnc.name());
1687         os << setEncoding(newEnc.iconvName());
1688         if (bparams.inputenc == "auto-legacy-plain")
1689           return make_pair(true, 0);
1690
1691         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1692         OutputState * state = getOutputState();
1693         switch (newEnc.package()) {
1694                 case Encoding::none:
1695                 case Encoding::japanese:
1696                         // shouldn't ever reach here (see above) but avoids warning.
1697                         return make_pair(true, 0);
1698                 case Encoding::inputenc: {
1699                         int count = inputenc_arg.length();
1700                         if (oldEnc.package() == Encoding::CJK &&
1701                             state->open_encoding_ == CJK) {
1702                                 os << "\\end{CJK}";
1703                                 state->open_encoding_ = none;
1704                                 count += 9;
1705                         }
1706                         else if (oldEnc.package() == Encoding::inputenc &&
1707                                  state->open_encoding_ == inputenc) {
1708                                 os << "\\egroup";
1709                                 state->open_encoding_ = none;
1710                                 count += 7;
1711                         }
1712                         if (runparams.local_font != 0
1713                             &&  oldEnc.package() == Encoding::CJK) {
1714                                 // within insets, \inputenc switches need
1715                                 // to be embraced within \bgroup...\egroup;
1716                                 // else CJK fails.
1717                                 os << "\\bgroup";
1718                                 count += 7;
1719                                 state->open_encoding_ = inputenc;
1720                         }
1721                         if (noswitchmacro)
1722                                 return make_pair(true, count);
1723                         os << "\\inputencoding{" << inputenc_arg << '}';
1724                         return make_pair(true, count + 16);
1725                 }
1726                 case Encoding::CJK: {
1727                         int count = inputenc_arg.length();
1728                         if (oldEnc.package() == Encoding::CJK &&
1729                             state->open_encoding_ == CJK) {
1730                                 os << "\\end{CJK}";
1731                                 count += 9;
1732                         }
1733                         if (oldEnc.package() == Encoding::inputenc &&
1734                             state->open_encoding_ == inputenc) {
1735                                 os << "\\egroup";
1736                                 count += 7;
1737                         }
1738                         os << "\\begin{CJK}{"
1739                            << from_ascii(newEnc.latexName()) << "}{"
1740                            << from_ascii(bparams.fonts_cjk) << "}";
1741                         state->open_encoding_ = CJK;
1742                         return make_pair(true, count + 15);
1743                 }
1744         }
1745         // Dead code to avoid a warning:
1746         return make_pair(true, 0);
1747 }
1748
1749 } // namespace lyx