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