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