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