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