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