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