]> git.lyx.org Git - features.git/blob - src/output_latex.cpp
Clean-up before following bugfix
[features.git] / src / output_latex.cpp
1 /**
2  * \file output_latex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "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 namespace {
614
615 // output the proper paragraph start according to latextype.
616 void parStartCommand(Paragraph const & par, otexstream & os,
617                      OutputParams const & runparams, Layout const & style) 
618 {
619         switch (style.latextype) {
620         case LATEX_COMMAND:
621                 os << '\\' << from_ascii(style.latexname());
622
623                 // Command arguments
624                 if (!style.latexargs().empty())
625                         latexArgInsets(par, os, runparams, style.latexargs());
626                 os << from_ascii(style.latexparam());
627                 break;
628         case LATEX_ITEM_ENVIRONMENT:
629         case LATEX_LIST_ENVIRONMENT:
630                 os << "\\" + style.itemcommand();
631                 // Item arguments
632                 if (!style.itemargs().empty())
633                         latexArgInsets(par, os, runparams, style.itemargs(), "item:");
634                 os << " ";
635                 break;
636         case LATEX_BIB_ENVIRONMENT:
637                 // ignore this, the inset will write itself
638                 break;
639         default:
640                 break;
641         }
642 }
643
644 } // namespace anon
645
646 // FIXME: this should be anonymous
647 void TeXOnePar(Buffer const & buf,
648                Text const & text,
649                pit_type pit,
650                otexstream & os,
651                OutputParams const & runparams_in,
652                string const & everypar,
653                int start_pos, int end_pos)
654 {
655         BufferParams const & bparams = runparams_in.is_child
656                 ? buf.masterParams() : buf.params();
657         ParagraphList const & paragraphs = text.paragraphs();
658         Paragraph const & par = paragraphs.at(pit);
659         // FIXME This check should not really be needed.
660         // Perhaps we should issue an error if it is.
661         Layout const & style = text.inset().forcePlainLayout() ?
662                 bparams.documentClass().plainLayout() : par.layout();
663
664         if (style.inpreamble)
665                 return;
666
667         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
668                 << everypar << "'");
669
670         OutputParams runparams = runparams_in;
671         runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
672         // We reinitialze par begin and end to be on the safe side
673         // with embedded inset as we don't know if they set those
674         // value correctly.
675         runparams.par_begin = 0;
676         runparams.par_end = 0;
677
678         bool const maintext = text.isMainText();
679         // we are at the beginning of an inset and CJK is already open;
680         // we count inheritation levels to get the inset nesting right.
681         OutputState * state = getOutputState();
682         if (pit == 0 && !maintext
683             && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
684                 state->cjk_inherited_ += 1;
685                 state->open_encoding_ = none;
686         }
687
688         if (text.inset().isPassThru()) {
689                 Font const outerfont = text.outerFont(pit);
690
691                 // No newline before first paragraph in this lyxtext
692                 if (pit > 0) {
693                         os << '\n';
694                         if (!text.inset().getLayout().parbreakIsNewline())
695                                 os << '\n';
696                 }
697
698                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
699                 return;
700         }
701
702         Paragraph const * nextpar = runparams.isLastPar
703                 ? 0 : &paragraphs.at(pit + 1);
704
705         if (style.pass_thru) {
706                 Font const outerfont = text.outerFont(pit);
707                 parStartCommand(par, os, runparams, style);
708
709                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
710
711                 // I did not create a parEndCommand for this minuscule
712                 // task because in the other user of parStartCommand
713                 // the code is different (JMarc)
714                 if (style.isCommand())
715                         os << "}\n";
716                 else
717                         os << '\n';
718                 if (!style.parbreak_is_newline) {
719                         os << '\n';
720                 } else if (nextpar && !style.isEnvironment()) {
721                         Layout const nextstyle = text.inset().forcePlainLayout()
722                                 ? bparams.documentClass().plainLayout()
723                                 : nextpar->layout();
724                         if (nextstyle.name() != style.name())
725                                 os << '\n';
726                 }
727
728                 return;
729         }
730
731         // This paragraph's language
732         Language const * const par_language = par.getParLanguage(bparams);
733         Language const * const nextpar_language = nextpar ?
734                 nextpar->getParLanguage(bparams) : 0;
735         // The document's language
736         Language const * const doc_language = bparams.language;
737         // The language that was in effect when the environment this paragraph is
738         // inside of was opened
739         Language const * const outer_language =
740                 (runparams.local_font != 0) ?
741                         runparams.local_font->language() : doc_language;
742
743         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
744
745         // The previous language that was in effect is the language of the
746         // previous paragraph, unless the previous paragraph is inside an
747         // environment with nesting depth greater than (or equal to, but with
748         // a different layout) the current one. If there is no previous
749         // paragraph, the previous language is the outer language.
750         bool const use_prev_env_language = state->prev_env_language_ != 0
751                         && priorpar
752                         && priorpar->layout().isEnvironment()
753                         && (priorpar->getDepth() > par.getDepth()
754                             || (priorpar->getDepth() == par.getDepth()
755                                     && priorpar->layout() != par.layout()));
756         Language const * const prev_language =
757                 (pit != 0)
758                 ? (use_prev_env_language ? state->prev_env_language_
759                                          : priorpar->getParLanguage(bparams))
760                 : outer_language;
761
762
763         bool const use_polyglossia = runparams.use_polyglossia;
764         string const par_lang = use_polyglossia ?
765                 getPolyglossiaEnvName(par_language): par_language->babel();
766         string const prev_lang = use_polyglossia ?
767                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
768         string const outer_lang = use_polyglossia ?
769                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
770         string const nextpar_lang = nextpar_language ? (use_polyglossia ?
771                 getPolyglossiaEnvName(nextpar_language) :
772                 nextpar_language->babel()) : string();
773         string lang_begin_command = use_polyglossia ?
774                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
775         string lang_end_command = use_polyglossia ?
776                 "\\end{$$lang}" : lyxrc.language_command_end;
777         // the '%' is necessary to prevent unwanted whitespace
778         string lang_command_termination = "%\n";
779
780         // In some insets (such as Arguments), we cannot use \selectlanguage
781         bool const localswitch = text.inset().forceLocalFontSwitch()
782                         || (use_polyglossia && text.inset().forcePlainLayout());
783         if (localswitch) {
784                 lang_begin_command = use_polyglossia ?
785                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
786                 lang_end_command = "}";
787                 lang_command_termination.clear();
788         }
789
790         if (par_lang != prev_lang
791                 // check if we already put language command in TeXEnvironment()
792                 && !(style.isEnvironment()
793                      && (pit == 0 || (priorpar->layout() != par.layout()
794                                           && priorpar->getDepth() <= par.getDepth())
795                                   || priorpar->getDepth() < par.getDepth())))
796         {
797                 if (!lang_end_command.empty() &&
798                     prev_lang != outer_lang &&
799                     !prev_lang.empty() &&
800                     (!use_polyglossia || !style.isEnvironment()))
801                 {
802                         os << from_ascii(subst(lang_end_command,
803                                 "$$lang",
804                                 prev_lang))
805                            << lang_command_termination;
806                         if (use_polyglossia)
807                                 popPolyglossiaLang();
808                 }
809
810                 // We need to open a new language if we couldn't close the previous
811                 // one (because there's no language_command_end); and even if we closed
812                 // the previous one, if the current language is different than the
813                 // outer_language (which is currently in effect once the previous one
814                 // is closed).
815                 if ((lang_end_command.empty() || par_lang != outer_lang
816                      || (!use_polyglossia
817                          || (style.isEnvironment() && par_lang != prev_lang)))
818                         && !par_lang.empty()) {
819                         // If we're inside an inset, and that inset is within an \L or \R
820                         // (or equivalents), then within the inset, too, any opposite
821                         // language paragraph should appear within an \L or \R (in addition
822                         // to, outside of, the normal language switch commands).
823                         // This behavior is not correct for ArabTeX, though.
824                         if (!use_polyglossia
825                             // not for ArabTeX
826                                 && par_language->lang() != "arabic_arabtex"
827                                 && outer_language->lang() != "arabic_arabtex"
828                             // are we in an inset?
829                             && runparams.local_font != 0
830                             // is the inset within an \L or \R?
831                             //
832                             // FIXME: currently, we don't check this; this means that
833                             // we'll have unnnecessary \L and \R commands, but that
834                             // doesn't seem to hurt (though latex will complain)
835                             //
836                             // is this paragraph in the opposite direction?
837                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
838                                 // FIXME: I don't have a working copy of the Arabi package, so
839                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
840                                 // or not...
841                                 if (par_language->lang() == "farsi")
842                                         os << "\\textFR{";
843                                 else if (outer_language->lang() == "farsi")
844                                         os << "\\textLR{";
845                                 else if (par_language->lang() == "arabic_arabi")
846                                         os << "\\textAR{";
847                                 else if (outer_language->lang() == "arabic_arabi")
848                                         os << "\\textLR{";
849                                 // remaining RTL languages currently is hebrew
850                                 else if (par_language->rightToLeft())
851                                         os << "\\R{";
852                                 else
853                                         os << "\\L{";
854                         }
855                         // With CJK, the CJK tag has to be closed first (see below)
856                         if (runparams.encoding->package() != Encoding::CJK
857                             && par_lang != openPolyglossiaLang(state)
858                             && !par_lang.empty()) {
859                                 string bc = use_polyglossia ?
860                                           getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
861                                           : subst(lang_begin_command, "$$lang", par_lang);
862                                 os << bc;
863                                 os << lang_command_termination;
864                                 if (use_polyglossia)
865                                         pushPolyglossiaLang(par_lang, localswitch);
866                         }
867                 }
868         }
869
870         // Switch file encoding if necessary; no need to do this for "default"
871         // encoding, since this only affects the position of the outputted
872         // \inputencoding command; the encoding switch will occur when necessary
873         if (bparams.inputenc == "auto"
874                 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding  (see also switchEncoding())
875                 && runparams.encoding->package() != Encoding::none) {
876                 // Look ahead for future encoding changes.
877                 // We try to output them at the beginning of the paragraph,
878                 // since the \inputencoding command is not allowed e.g. in
879                 // sections. For this reason we only set runparams.moving_arg
880                 // after checking for the encoding change, otherwise the
881                 // change would be always avoided by switchEncoding().
882                 for (pos_type i = 0; i < par.size(); ++i) {
883                         char_type const c = par.getChar(i);
884                         Encoding const * const encoding =
885                                 par.getFontSettings(bparams, i).language()->encoding();
886                         if (encoding->package() != Encoding::CJK
887                                 && runparams.encoding->package() == Encoding::inputenc
888                                 && isASCII(c))
889                                 continue;
890                         if (par.isInset(i))
891                                 break;
892                         // All characters before c are in the ASCII range, and
893                         // c is non-ASCII (but no inset), so change the
894                         // encoding to that required by the language of c.
895                         // With CJK, only add switch if we have CJK content at the beginning
896                         // of the paragraph
897                         if (i != 0 && encoding->package() == Encoding::CJK)
898                                 continue;
899
900                         pair<bool, int> enc_switch = switchEncoding(os.os(),
901                                                 bparams, runparams, *encoding);
902                         // the following is necessary after a CJK environment in a multilingual
903                         // context (nesting issue).
904                         if (par_language->encoding()->package() == Encoding::CJK
905                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
906                                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
907                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
908                                 state->open_encoding_ = CJK;
909                         }
910                         if (encoding->package() != Encoding::none && enc_switch.first) {
911                                 if (enc_switch.second > 0) {
912                                         // the '%' is necessary to prevent unwanted whitespace
913                                         os << "%\n";
914                                 }
915                                 // With CJK, the CJK tag had to be closed first (see above)
916                                 if (runparams.encoding->package() == Encoding::CJK
917                                     && par_lang != openPolyglossiaLang(state)
918                                     && !par_lang.empty()) {
919                                         os << from_ascii(subst(
920                                                 lang_begin_command,
921                                                 "$$lang",
922                                                 par_lang))
923                                         << lang_command_termination;
924                                         if (use_polyglossia)
925                                                 pushPolyglossiaLang(par_lang, localswitch);
926                                 }
927                                 runparams.encoding = encoding;
928                         }
929                         break;
930                 }
931         }
932
933         runparams.moving_arg |= style.needprotect;
934         Encoding const * const prev_encoding = runparams.encoding;
935
936         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
937         if (par.allowParagraphCustomization()) {
938                 if (par.params().startOfAppendix()) {
939                         os << "\n\\appendix\n";
940                 }
941
942                 if (!par.params().spacing().isDefault()
943                         && (pit == 0 || !priorpar->hasSameLayout(par)))
944                 {
945                         os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
946                             << '\n';
947                 }
948
949                 if (style.isCommand()) {
950                         os << '\n';
951                 }
952         }
953
954         parStartCommand(par, os, runparams, style);
955         Font const outerfont = text.outerFont(pit);
956
957         // FIXME UNICODE
958         os << from_utf8(everypar);
959         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
960
961         // Make sure that \\par is done with the font of the last
962         // character if this has another size as the default.
963         // This is necessary because LaTeX (and LyX on the screen)
964         // calculates the space between the baselines according
965         // to this font. (Matthias)
966         //
967         // We must not change the font for the last paragraph
968         // of non-multipar insets, tabular cells or commands,
969         // since this produces unwanted whitespace.
970
971         Font const font = par.empty()
972                  ? par.getLayoutFont(bparams, outerfont)
973                  : par.getFont(bparams, par.size() - 1, outerfont);
974
975         bool const is_command = style.isCommand();
976
977         if (style.resfont.size() != font.fontInfo().size()
978             && (nextpar || maintext
979                 || (text.inset().paragraphs().size() > 1
980                     && text.inset().lyxCode() != CELL_CODE))
981             && !is_command) {
982                 os << '{';
983                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
984         } else if (is_command) {
985                 os << '}';
986                 if (!style.postcommandargs().empty())
987                         latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
988                 if (runparams.encoding != prev_encoding) {
989                         runparams.encoding = prev_encoding;
990                         os << setEncoding(prev_encoding->iconvName());
991                 }
992         }
993
994         bool pending_newline = false;
995         bool unskip_newline = false;
996         bool close_lang_switch = false;
997         switch (style.latextype) {
998         case LATEX_ITEM_ENVIRONMENT:
999         case LATEX_LIST_ENVIRONMENT:
1000                 if ((nextpar && par_lang != nextpar_lang
1001                              && nextpar->getDepth() == par.getDepth())
1002                     || (atSameLastLangSwitchDepth(state) && nextpar
1003                             && nextpar->getDepth() < par.getDepth()))
1004                         close_lang_switch = use_polyglossia;
1005                 if (nextpar && par.params().depth() < nextpar->params().depth())
1006                         pending_newline = true;
1007                 break;
1008         case LATEX_ENVIRONMENT: {
1009                 // if its the last paragraph of the current environment
1010                 // skip it otherwise fall through
1011                 if (nextpar
1012                     && ((nextpar->layout() != par.layout()
1013                            || nextpar->params().depth() != par.params().depth())
1014                         || (!use_polyglossia || par_lang != nextpar_lang)))
1015                 {
1016                         close_lang_switch = use_polyglossia;
1017                         break;
1018                 }
1019         }
1020
1021         // fall through possible
1022         default:
1023                 // we don't need it for the last paragraph!!!
1024                 if (nextpar)
1025                         pending_newline = true;
1026         }
1027
1028         if (par.allowParagraphCustomization()) {
1029                 if (!par.params().spacing().isDefault()
1030                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1031                         if (pending_newline)
1032                                 os << '\n';
1033
1034                         string const endtag =
1035                                 par.params().spacing().writeEnvirEnd(useSetSpace);
1036                         if (prefixIs(endtag, "\\end{"))
1037                                 os << breakln;
1038
1039                         os << from_ascii(endtag);
1040                         pending_newline = true;
1041                 }
1042         }
1043
1044         // Closing the language is needed for the last paragraph; it is also
1045         // needed if we're within an \L or \R that we may have opened above (not
1046         // necessarily in this paragraph) and are about to close.
1047         bool closing_rtl_ltr_environment = !use_polyglossia
1048                 // not for ArabTeX
1049                 && (par_language->lang() != "arabic_arabtex"
1050                     && outer_language->lang() != "arabic_arabtex")
1051                 // have we opened an \L or \R environment?
1052                 && runparams.local_font != 0
1053                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1054                 // are we about to close the language?
1055                 &&((nextpar && par_lang != nextpar_lang)
1056                    || (runparams.isLastPar && par_lang != outer_lang));
1057
1058         if (closing_rtl_ltr_environment
1059             || ((runparams.isLastPar || close_lang_switch)
1060                 && (par_lang != outer_lang || (use_polyglossia
1061                                                 && style.isEnvironment()
1062                                                 && par_lang != nextpar_lang)))) {
1063                 // Since \selectlanguage write the language to the aux file,
1064                 // we need to reset the language at the end of footnote or
1065                 // float.
1066
1067                 if (pending_newline || close_lang_switch)
1068                         os << '\n';
1069
1070                 // when the paragraph uses CJK, the language has to be closed earlier
1071                 if (font.language()->encoding()->package() != Encoding::CJK) {
1072                         if (lang_end_command.empty()) {
1073                                 // If this is a child, we should restore the
1074                                 // master language after the last paragraph.
1075                                 Language const * const current_language =
1076                                         (runparams.isLastPar && runparams.master_language)
1077                                                 ? runparams.master_language
1078                                                 : outer_language;
1079                                 string const current_lang = use_polyglossia
1080                                         ? getPolyglossiaEnvName(current_language)
1081                                         : current_language->babel();
1082                                 if (!current_lang.empty()
1083                                     && current_lang != openPolyglossiaLang(state)) {
1084                                         string bc = use_polyglossia ?
1085                                                     getPolyglossiaBegin(lang_begin_command, current_lang,
1086                                                                         current_language->polyglossiaOpts())
1087                                                   : subst(lang_begin_command, "$$lang", current_lang);
1088                                         os << bc;
1089                                         pending_newline = !localswitch;
1090                                         unskip_newline = !localswitch;
1091                                         if (use_polyglossia)
1092                                                 pushPolyglossiaLang(current_lang, localswitch);
1093                                 }
1094                         } else if (!par_lang.empty()) {
1095                                 // If we are in an environment, we have to close the "outer" language afterwards
1096                                 string const & pol_lang = openPolyglossiaLang(state);
1097                                 if (!style.isEnvironment()
1098                                     || (close_lang_switch
1099                                         && atSameLastLangSwitchDepth(state)
1100                                         && par_lang != outer_lang
1101                                         && (par_lang != pol_lang
1102                                             || (pol_lang != outer_lang
1103                                                 && nextpar
1104                                                 && style != nextpar->layout())))
1105                                     || (atSameLastLangSwitchDepth(state)
1106                                         && state->lang_switch_depth_.size()
1107                                         && pol_lang != par_lang))
1108                                 {
1109                                         if (use_polyglossia && !localswitch)
1110                                                 os << breakln;
1111                                         os << from_ascii(subst(
1112                                                 lang_end_command,
1113                                                 "$$lang",
1114                                                 par_lang));
1115                                         pending_newline = !localswitch;
1116                                         unskip_newline = !localswitch;
1117                                         if (use_polyglossia)
1118                                                 popPolyglossiaLang();
1119                                 }
1120                         }
1121                 }
1122         }
1123         if (closing_rtl_ltr_environment)
1124                 os << "}";
1125
1126         bool const last_was_separator =
1127                 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1128
1129         if (pending_newline) {
1130                 if (unskip_newline)
1131                         // prevent unwanted whitespace
1132                         os << '%';
1133                 if (!os.afterParbreak() && !last_was_separator)
1134                         os << breakln;
1135         }
1136
1137         // if this is a CJK-paragraph and the next isn't, close CJK
1138         // also if the next paragraph is a multilingual environment (because of nesting)
1139         if (nextpar
1140                 && state->open_encoding_ == CJK
1141                 && (nextpar_language->encoding()->package() != Encoding::CJK
1142                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1143                 // inbetween environments, CJK has to be closed later (nesting!)
1144                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1145                 os << "\\end{CJK}\n";
1146                 state->open_encoding_ = none;
1147         }
1148
1149         // If this is the last paragraph, close the CJK environment
1150         // if necessary. If it's an environment, we'll have to \end that first.
1151         if (runparams.isLastPar && !style.isEnvironment()) {
1152                 switch (state->open_encoding_) {
1153                         case CJK: {
1154                                 // do nothing at the end of child documents
1155                                 if (maintext && buf.masterBuffer() != &buf)
1156                                         break;
1157                                 // end of main text
1158                                 if (maintext) {
1159                                         os << "\n\\end{CJK}\n";
1160                                 // end of an inset
1161                                 } else
1162                                         os << "\\end{CJK}";
1163                                 state->open_encoding_ = none;
1164                                 break;
1165                         }
1166                         case inputenc: {
1167                                 os << "\\egroup";
1168                                 state->open_encoding_ = none;
1169                                 break;
1170                         }
1171                         case none:
1172                         default:
1173                                 // do nothing
1174                                 break;
1175                 }
1176         }
1177
1178         // If this is the last paragraph, and a local_font was set upon entering
1179         // the inset, and we're using "auto" or "default" encoding, and not
1180         // compiling with XeTeX or LuaTeX, the encoding
1181         // should be set back to that local_font's encoding.
1182         if (runparams.isLastPar && runparams_in.local_font != 0
1183             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1184             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1185                 && !runparams.isFullUnicode()
1186            ) {
1187                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1188                 os << setEncoding(runparams_in.encoding->iconvName());
1189         }
1190         // Otherwise, the current encoding should be set for the next paragraph.
1191         else
1192                 runparams_in.encoding = runparams.encoding;
1193
1194
1195         // we don't need a newline for the last paragraph!!!
1196         // Note from JMarc: we will re-add a \n explicitly in
1197         // TeXEnvironment, because it is needed in this case
1198         if (nextpar && !os.afterParbreak() && !last_was_separator) {
1199                 // Make sure to start a new line
1200                 os << breakln;
1201                 Layout const & next_layout = nextpar->layout();
1202                 // A newline '\n' is always output before a command,
1203                 // so avoid doubling it.
1204                 if (!next_layout.isCommand()) {
1205                         // Here we now try to avoid spurious empty lines by
1206                         // outputting a paragraph break only if: (case 1) the
1207                         // paragraph style allows parbreaks and no \begin, \end
1208                         // or \item tags are going to follow (i.e., if the next
1209                         // isn't the first or the current isn't the last
1210                         // paragraph of an environment or itemize) and the
1211                         // depth and alignment of the following paragraph is
1212                         // unchanged, or (case 2) the following is a
1213                         // non-environment paragraph whose depth is increased
1214                         // but whose alignment is unchanged, or (case 3) the
1215                         // paragraph is not an environment and the next one is a
1216                         // non-itemize-like env at lower depth, or (case 4) the
1217                         // paragraph is a command not followed by an environment
1218                         // and the alignment of the current and next paragraph
1219                         // is unchanged, or (case 5) the current alignment is
1220                         // changed and a standard paragraph follows.
1221                         DocumentClass const & tclass = bparams.documentClass();
1222                         if ((style == next_layout
1223                              && !style.parbreak_is_newline
1224                              && !text.inset().getLayout().parbreakIsNewline()
1225                              && style.latextype != LATEX_ITEM_ENVIRONMENT
1226                              && style.latextype != LATEX_LIST_ENVIRONMENT
1227                              && style.align == par.getAlign()
1228                              && nextpar->getDepth() == par.getDepth()
1229                              && nextpar->getAlign() == par.getAlign())
1230                             || (!next_layout.isEnvironment()
1231                                 && nextpar->getDepth() > par.getDepth()
1232                                 && nextpar->getAlign() == par.getAlign())
1233                             || (!style.isEnvironment()
1234                                 && next_layout.latextype == LATEX_ENVIRONMENT
1235                                 && nextpar->getDepth() < par.getDepth())
1236                             || (style.isCommand()
1237                                 && !next_layout.isEnvironment()
1238                                 && style.align == par.getAlign()
1239                                 && next_layout.align == nextpar->getAlign())
1240                             || (style.align != par.getAlign()
1241                                 && tclass.isDefaultLayout(next_layout))) {
1242                                 os << '\n';
1243                         }
1244                 }
1245         }
1246
1247         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1248                 << &par << " next " << nextpar);
1249
1250         return;
1251 }
1252
1253
1254 // LaTeX all paragraphs
1255 void latexParagraphs(Buffer const & buf,
1256                      Text const & text,
1257                      otexstream & os,
1258                      OutputParams const & runparams,
1259                      string const & everypar)
1260 {
1261         LASSERT(runparams.par_begin <= runparams.par_end,
1262                 { os << "% LaTeX Output Error\n"; return; } );
1263
1264         BufferParams const & bparams = buf.params();
1265         BufferParams const & mparams = buf.masterParams();
1266
1267         bool const maintext = text.isMainText();
1268         bool const is_child = buf.masterBuffer() != &buf;
1269         bool const multibib_child = maintext && is_child
1270                         && mparams.multibib == "child";
1271
1272         if (multibib_child && mparams.useBiblatex())
1273                 os << "\\newrefsection";
1274         else if (multibib_child && mparams.useBibtopic()) {
1275                 os << "\\begin{btUnit}\n";
1276                 runparams.openbtUnit = true;
1277         }
1278
1279         // Open a CJK environment at the beginning of the main buffer
1280         // if the document's language is a CJK language
1281         // (but not in child documents)
1282         OutputState * state = getOutputState();
1283         if (maintext && !is_child
1284             && bparams.encoding().package() == Encoding::CJK) {
1285                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1286                 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1287                 state->open_encoding_ = CJK;
1288         }
1289         // if "auto begin" is switched off, explicitly switch the
1290         // language on at start
1291         string const mainlang = runparams.use_polyglossia
1292                 ? getPolyglossiaEnvName(bparams.language)
1293                 : bparams.language->babel();
1294         string const lang_begin_command = runparams.use_polyglossia ?
1295                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1296
1297         if (maintext && !lyxrc.language_auto_begin &&
1298             !mainlang.empty()) {
1299                 // FIXME UNICODE
1300                 string bc = runparams.use_polyglossia ?
1301                             getPolyglossiaBegin(lang_begin_command, mainlang,
1302                                                 bparams.language->polyglossiaOpts())
1303                           : subst(lang_begin_command, "$$lang", mainlang);
1304                 os << bc;
1305                 os << '\n';
1306                 if (runparams.use_polyglossia)
1307                         pushPolyglossiaLang(mainlang);
1308         }
1309
1310         ParagraphList const & paragraphs = text.paragraphs();
1311
1312         if (runparams.par_begin == runparams.par_end) {
1313                 // The full doc will be exported but it is easier to just rely on
1314                 // runparams range parameters that will be passed TeXEnvironment.
1315                 runparams.par_begin = 0;
1316                 runparams.par_end = paragraphs.size();
1317         }
1318
1319         pit_type pit = runparams.par_begin;
1320         // lastpit is for the language check after the loop.
1321         pit_type lastpit = pit;
1322         // variables used in the loop:
1323         bool was_title = false;
1324         bool already_title = false;
1325         DocumentClass const & tclass = bparams.documentClass();
1326
1327         // Did we already warn about inTitle layout mixing? (we only warn once)
1328         bool gave_layout_warning = false;
1329         for (; pit < runparams.par_end; ++pit) {
1330                 lastpit = pit;
1331                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1332
1333                 // FIXME This check should not be needed. We should
1334                 // perhaps issue an error if it is.
1335                 Layout const & layout = text.inset().forcePlainLayout() ?
1336                                 tclass.plainLayout() : par->layout();
1337
1338                 if (layout.intitle) {
1339                         if (already_title) {
1340                                 if (!gave_layout_warning && !runparams.dryrun) {
1341                                         gave_layout_warning = true;
1342                                         frontend::Alert::warning(_("Error in latexParagraphs"),
1343                                                         bformat(_("You are using at least one "
1344                                                           "layout (%1$s) intended for the title, "
1345                                                           "after using non-title layouts. This "
1346                                                           "could lead to missing or incorrect output."
1347                                                           ), layout.name()));
1348                                 }
1349                         } else if (!was_title) {
1350                                 was_title = true;
1351                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1352                                         os << "\\begin{"
1353                                                         << from_ascii(tclass.titlename())
1354                                                         << "}\n";
1355                                 }
1356                         }
1357                 } else if (was_title && !already_title && !layout.inpreamble) {
1358                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1359                                 os << "\\end{" << from_ascii(tclass.titlename())
1360                                                 << "}\n";
1361                         }
1362                         else {
1363                                 os << "\\" << from_ascii(tclass.titlename())
1364                                                 << "\n";
1365                         }
1366                         already_title = true;
1367                         was_title = false;
1368                 }
1369
1370                 if (layout.isCommand() && !layout.latexname().empty()
1371                     && layout.latexname() == bparams.multibib) {
1372                         if (runparams.openbtUnit)
1373                                 os << "\\end{btUnit}\n";
1374                         if (!bparams.useBiblatex()) {
1375                                 os << '\n' << "\\begin{btUnit}\n";
1376                                 runparams.openbtUnit = true;
1377                         }
1378                 }
1379
1380                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1381                         // This is a standard top level paragraph, TeX it and continue.
1382                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1383                         continue;
1384                 }
1385                 
1386                 TeXEnvironmentData const data =
1387                         prepareEnvironment(buf, text, par, os, runparams);
1388                 // pit can be changed in TeXEnvironment.
1389                 TeXEnvironment(buf, text, runparams, pit, os);
1390                 finishEnvironment(os, runparams, data);
1391         }
1392
1393         if (pit == runparams.par_end) {
1394                         // Make sure that the last paragraph is
1395                         // correctly terminated (because TeXOnePar does
1396                         // not add a \n in this case)
1397                         //os << '\n';
1398         }
1399
1400         // It might be that we only have a title in this document
1401         if (was_title && !already_title) {
1402                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1403                         os << "\\end{" << from_ascii(tclass.titlename())
1404                            << "}\n";
1405                 } else {
1406                         os << "\\" << from_ascii(tclass.titlename())
1407                            << "\n";
1408                 }
1409         }
1410
1411         if (maintext && !is_child && runparams.openbtUnit)
1412                 os << "\\end{btUnit}\n";
1413
1414         // if "auto end" is switched off, explicitly close the language at the end
1415         // but only if the last par is in a babel or polyglossia language
1416         string const lang_end_command = runparams.use_polyglossia ?
1417                 "\\end{$$lang}" : lyxrc.language_command_end;
1418         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1419                 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1420                 os << from_utf8(subst(lang_end_command,
1421                                         "$$lang",
1422                                         mainlang))
1423                         << '\n';
1424                 if (runparams.use_polyglossia)
1425                         popPolyglossiaLang();
1426         }
1427
1428         // If the last paragraph is an environment, we'll have to close
1429         // CJK at the very end to do proper nesting.
1430         if (maintext && !is_child && state->open_encoding_ == CJK) {
1431                 os << "\\end{CJK}\n";
1432                 state->open_encoding_ = none;
1433         }
1434         // Likewise for polyglossia
1435         string const & pol_lang = openPolyglossiaLang(state);
1436         if (maintext && !is_child && !pol_lang.empty()) {
1437                 os << from_utf8(subst(lang_end_command,
1438                                         "$$lang",
1439                                         pol_lang))
1440                    << '\n';
1441                 if (runparams.use_polyglossia)
1442                         popPolyglossiaLang();
1443         }
1444
1445         // reset inherited encoding
1446         if (state->cjk_inherited_ > 0) {
1447                 state->cjk_inherited_ -= 1;
1448                 if (state->cjk_inherited_ == 0)
1449                         state->open_encoding_ = CJK;
1450         }
1451
1452         if (multibib_child && mparams.useBibtopic()) {
1453                 os << "\\end{btUnit}\n";
1454                 runparams.openbtUnit = false;
1455         }
1456 }
1457
1458
1459 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1460                    OutputParams const & runparams, Encoding const & newEnc,
1461                    bool force)
1462 {
1463         // XeTeX/LuaTeX use only one encoding per document:
1464         // * with useNonTeXFonts: "utf8plain",
1465         // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1466         // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1467         if (runparams.isFullUnicode())
1468                 return make_pair(false, 0);
1469
1470         Encoding const & oldEnc = *runparams.encoding;
1471         bool moving_arg = runparams.moving_arg;
1472         // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1473         bool const from_to_cjk = 
1474                 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1475                 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1476         if (!force && !from_to_cjk
1477             && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1478                 return make_pair(false, 0);
1479
1480         // Do nothing if the encoding is unchanged.
1481         if (oldEnc.name() == newEnc.name())
1482                 return make_pair(false, 0);
1483
1484         // FIXME We ignore encoding switches from/to encodings that do
1485         // neither support the inputenc package nor the CJK package here.
1486         // This does of course only work in special cases (e.g. switch from
1487         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1488         // but it is the best we can do
1489         if (oldEnc.package() == Encoding::none
1490                 || newEnc.package() == Encoding::none)
1491                 return make_pair(false, 0);
1492
1493         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1494                 << oldEnc.name() << " to " << newEnc.name());
1495         os << setEncoding(newEnc.iconvName());
1496         if (bparams.inputenc == "default")
1497                 return make_pair(true, 0);
1498
1499         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1500         OutputState * state = getOutputState();
1501         switch (newEnc.package()) {
1502                 case Encoding::none:
1503                 case Encoding::japanese:
1504                         // shouldn't ever reach here, see above
1505                         return make_pair(true, 0);
1506                 case Encoding::inputenc: {
1507                         int count = inputenc_arg.length();
1508                         if (oldEnc.package() == Encoding::CJK &&
1509                             state->open_encoding_ == CJK) {
1510                                 os << "\\end{CJK}";
1511                                 state->open_encoding_ = none;
1512                                 count += 9;
1513                         }
1514                         else if (oldEnc.package() == Encoding::inputenc &&
1515                                  state->open_encoding_ == inputenc) {
1516                                 os << "\\egroup";
1517                                 state->open_encoding_ = none;
1518                                 count += 7;
1519                         }
1520                         if (runparams.local_font != 0
1521                             &&  oldEnc.package() == Encoding::CJK) {
1522                                 // within insets, \inputenc switches need
1523                                 // to be embraced within \bgroup...\egroup;
1524                                 // else CJK fails.
1525                                 os << "\\bgroup";
1526                                 count += 7;
1527                                 state->open_encoding_ = inputenc;
1528                         }
1529                         // with the japanese option, inputenc is omitted.
1530                         if (runparams.use_japanese)
1531                                 return make_pair(true, count);
1532                         os << "\\inputencoding{" << inputenc_arg << '}';
1533                         return make_pair(true, count + 16);
1534                 }
1535                 case Encoding::CJK: {
1536                         int count = inputenc_arg.length();
1537                         if (oldEnc.package() == Encoding::CJK &&
1538                             state->open_encoding_ == CJK) {
1539                                 os << "\\end{CJK}";
1540                                 count += 9;
1541                         }
1542                         if (oldEnc.package() == Encoding::inputenc &&
1543                             state->open_encoding_ == inputenc) {
1544                                 os << "\\egroup";
1545                                 count += 7;
1546                         }
1547                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1548                            << from_ascii(bparams.fonts_cjk) << "}";
1549                         state->open_encoding_ = CJK;
1550                         return make_pair(true, count + 15);
1551                 }
1552         }
1553         // Dead code to avoid a warning:
1554         return make_pair(true, 0);
1555
1556 }
1557
1558 } // namespace lyx