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