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