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