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