]> git.lyx.org Git - features.git/blob - src/output_latex.cpp
Partial fix for #9740 "XeTeX/LuaTeX with TeX fonts problems".
[features.git] / src / output_latex.cpp
1 /**
2  * \file output_latex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "Encoding.h"
18 #include "Font.h"
19 #include "InsetList.h"
20 #include "Language.h"
21 #include "Layout.h"
22 #include "LyXRC.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "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         if (state->open_encoding_ == CJK && data.cjk_nested) {
239                 // We need to close the encoding even if it does not change
240                 // to do correct environment nesting
241                 os << "\\end{CJK}\n";
242                 state->open_encoding_ = none;
243         }
244
245         if (data.style->isEnvironment()) {
246                 os << breakln
247                    << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
248                 state->prev_env_language_ = data.par_language;
249                 if (runparams.encoding != data.prev_encoding) {
250                         runparams.encoding = data.prev_encoding;
251                         if (!runparams.isFullUnicode()) // FIXME: test for UseTeXFonts
252                                 os << setEncoding(data.prev_encoding->iconvName());
253                 }
254         }
255
256         if (data.leftindent_open) {
257                 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
258                 state->prev_env_language_ = data.par_language;
259                 if (runparams.encoding != data.prev_encoding) {
260                         runparams.encoding = data.prev_encoding;
261                         if (!runparams.isFullUnicode()) // FIXME: test for UseTeXFonts
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 (prev(pit, offset) == pars.begin())
475                         break;
476                 ParagraphList::const_iterator priorpit = 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 = 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         // The document's language
641         Language const * const doc_language = bparams.language;
642         // The language that was in effect when the environment this paragraph is
643         // inside of was opened
644         Language const * const outer_language =
645                 (runparams.local_font != 0) ?
646                         runparams.local_font->language() : doc_language;
647
648         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
649
650         // The previous language that was in effect is the language of the
651         // previous paragraph, unless the previous paragraph is inside an
652         // environment with nesting depth greater than (or equal to, but with
653         // a different layout) the current one. If there is no previous
654         // paragraph, the previous language is the outer language.
655         bool const use_prev_env_language = state->prev_env_language_ != 0
656                         && priorpar
657                         && priorpar->layout().isEnvironment()
658                         && (priorpar->getDepth() > par.getDepth()
659                             || (priorpar->getDepth() == par.getDepth()
660                                     && priorpar->layout() != par.layout()));
661         Language const * const prev_language =
662                 (pit != 0)
663                 ? (use_prev_env_language ? state->prev_env_language_
664                                          : priorpar->getParLanguage(bparams))
665                 : outer_language;
666
667
668         bool const use_polyglossia = runparams.use_polyglossia;
669         string const par_lang = use_polyglossia ?
670                 getPolyglossiaEnvName(par_language): par_language->babel();
671         string const prev_lang = use_polyglossia ?
672                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
673         string const outer_lang = use_polyglossia ?
674                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
675         string lang_begin_command = use_polyglossia ?
676                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
677         string lang_end_command = use_polyglossia ?
678                 "\\end{$$lang}" : lyxrc.language_command_end;
679         // the '%' is necessary to prevent unwanted whitespace
680         string lang_command_termination = "%\n";
681
682         // In some insets (such as Arguments), we cannot use \selectlanguage
683         bool const localswitch = text.inset().forceLocalFontSwitch();
684         if (localswitch) {
685                 lang_begin_command = use_polyglossia ?
686                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
687                 lang_end_command = "}";
688                 lang_command_termination.clear();
689         }
690
691         if (par_lang != prev_lang
692                 // check if we already put language command in TeXEnvironment()
693                 && !(style.isEnvironment()
694                      && (pit == 0 || (priorpar->layout() != par.layout()
695                                           && priorpar->getDepth() <= par.getDepth())
696                                   || priorpar->getDepth() < par.getDepth())))
697         {
698                 if (!lang_end_command.empty() &&
699                     prev_lang != outer_lang &&
700                     !prev_lang.empty())
701                 {
702                         os << from_ascii(subst(lang_end_command,
703                                 "$$lang",
704                                 prev_lang))
705                            << lang_command_termination;
706                         if (prev_lang == state->open_polyglossia_lang_)
707                                 state->open_polyglossia_lang_ = "";
708                 }
709
710                 // We need to open a new language if we couldn't close the previous
711                 // one (because there's no language_command_end); and even if we closed
712                 // the previous one, if the current language is different than the
713                 // outer_language (which is currently in effect once the previous one
714                 // is closed).
715                 if ((lang_end_command.empty() || par_lang != outer_lang)
716                         && !par_lang.empty()) {
717                         // If we're inside an inset, and that inset is within an \L or \R
718                         // (or equivalents), then within the inset, too, any opposite
719                         // language paragraph should appear within an \L or \R (in addition
720                         // to, outside of, the normal language switch commands).
721                         // This behavior is not correct for ArabTeX, though.
722                         if (!use_polyglossia
723                             // not for ArabTeX
724                                 && par_language->lang() != "arabic_arabtex"
725                                 && outer_language->lang() != "arabic_arabtex"
726                             // are we in an inset?
727                             && runparams.local_font != 0
728                             // is the inset within an \L or \R?
729                             //
730                             // FIXME: currently, we don't check this; this means that
731                             // we'll have unnnecessary \L and \R commands, but that
732                             // doesn't seem to hurt (though latex will complain)
733                             //
734                             // is this paragraph in the opposite direction?
735                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
736                                 // FIXME: I don't have a working copy of the Arabi package, so
737                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
738                                 // or not...
739                                 if (par_language->lang() == "farsi")
740                                         os << "\\textFR{";
741                                 else if (outer_language->lang() == "farsi")
742                                         os << "\\textLR{";
743                                 else if (par_language->lang() == "arabic_arabi")
744                                         os << "\\textAR{";
745                                 else if (outer_language->lang() == "arabic_arabi")
746                                         os << "\\textLR{";
747                                 // remaining RTL languages currently is hebrew
748                                 else if (par_language->rightToLeft())
749                                         os << "\\R{";
750                                 else
751                                         os << "\\L{";
752                         }
753                         // With CJK, the CJK tag has to be closed first (see below)
754                         if (runparams.encoding->package() != Encoding::CJK
755                             && !par_lang.empty()) {
756                                 string bc = use_polyglossia ?
757                                           getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
758                                           : subst(lang_begin_command, "$$lang", par_lang);
759                                 os << bc;
760                                 os << lang_command_termination;
761                         }
762                 }
763         }
764
765         // Switch file encoding if necessary; no need to do this for "default"
766         // encoding, since this only affects the position of the outputted
767         // \inputencoding command; the encoding switch will occur when necessary
768         if (bparams.inputenc == "auto"
769                 && runparams.encoding->package() != Encoding::none) {
770                 // Look ahead for future encoding changes.
771                 // We try to output them at the beginning of the paragraph,
772                 // since the \inputencoding command is not allowed e.g. in
773                 // sections. For this reason we only set runparams.moving_arg
774                 // after checking for the encoding change, otherwise the
775                 // change would be always avoided by switchEncoding().
776                 for (pos_type i = 0; i < par.size(); ++i) {
777                         char_type const c = par.getChar(i);
778                         Encoding const * const encoding =
779                                 par.getFontSettings(bparams, i).language()->encoding();
780                         if (encoding->package() != Encoding::CJK
781                                 && runparams.encoding->package() == Encoding::inputenc
782                                 && isASCII(c))
783                                 continue;
784                         if (par.isInset(i))
785                                 break;
786                         // All characters before c are in the ASCII range, and
787                         // c is non-ASCII (but no inset), so change the
788                         // encoding to that required by the language of c.
789                         // With CJK, only add switch if we have CJK content at the beginning
790                         // of the paragraph
791                         if (i != 0 && encoding->package() == Encoding::CJK)
792                                 continue;
793
794                         pair<bool, int> enc_switch = switchEncoding(os.os(),
795                                                 bparams, runparams, *encoding);
796                         // the following is necessary after a CJK environment in a multilingual
797                         // context (nesting issue).
798                         if (par_language->encoding()->package() == Encoding::CJK
799                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
800                                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
801                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
802                                 state->open_encoding_ = CJK;
803                         }
804                         if (encoding->package() != Encoding::none && enc_switch.first) {
805                                 if (enc_switch.second > 0) {
806                                         // the '%' is necessary to prevent unwanted whitespace
807                                         os << "%\n";
808                                 }
809                                 // With CJK, the CJK tag had to be closed first (see above)
810                                 if (runparams.encoding->package() == Encoding::CJK
811                                     && !par_lang.empty()) {
812                                         os << from_ascii(subst(
813                                                 lang_begin_command,
814                                                 "$$lang",
815                                                 par_lang))
816                                         << lang_command_termination;
817                                 }
818                                 runparams.encoding = encoding;
819                         }
820                         break;
821                 }
822         }
823
824         runparams.moving_arg |= style.needprotect;
825         Encoding const * const prev_encoding = runparams.encoding;
826
827         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
828         if (par.allowParagraphCustomization()) {
829                 if (par.params().startOfAppendix()) {
830                         os << "\n\\appendix\n";
831                 }
832
833                 if (!par.params().spacing().isDefault()
834                         && (pit == 0 || !priorpar->hasSameLayout(par)))
835                 {
836                         os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
837                             << '\n';
838                 }
839
840                 if (style.isCommand()) {
841                         os << '\n';
842                 }
843         }
844
845         parStartCommand(par, os, runparams, style);
846         Font const outerfont = text.outerFont(pit);
847
848         // FIXME UNICODE
849         os << from_utf8(everypar);
850         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
851
852         // Make sure that \\par is done with the font of the last
853         // character if this has another size as the default.
854         // This is necessary because LaTeX (and LyX on the screen)
855         // calculates the space between the baselines according
856         // to this font. (Matthias)
857         //
858         // We must not change the font for the last paragraph
859         // of non-multipar insets, tabular cells or commands,
860         // since this produces unwanted whitespace.
861
862         Font const font = par.empty()
863                  ? par.getLayoutFont(bparams, outerfont)
864                  : par.getFont(bparams, par.size() - 1, outerfont);
865
866         bool const is_command = style.isCommand();
867
868         if (style.resfont.size() != font.fontInfo().size()
869             && (nextpar || maintext
870                 || (text.inset().paragraphs().size() > 1
871                     && text.inset().lyxCode() != CELL_CODE))
872             && !is_command) {
873                 os << '{';
874                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
875         } else if (is_command) {
876                 os << '}';
877                 if (!style.postcommandargs().empty())
878                         latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
879                 if (runparams.encoding != prev_encoding) {
880                         runparams.encoding = prev_encoding;
881                         if (!runparams.isFullUnicode()) // FIXME: test for UseTeXFonts
882                                 os << setEncoding(prev_encoding->iconvName());
883                 }
884         }
885
886         bool pending_newline = false;
887         bool unskip_newline = false;
888         switch (style.latextype) {
889         case LATEX_ITEM_ENVIRONMENT:
890         case LATEX_LIST_ENVIRONMENT:
891                 if (nextpar && par.params().depth() < nextpar->params().depth())
892                         pending_newline = true;
893                 break;
894         case LATEX_ENVIRONMENT: {
895                 // if its the last paragraph of the current environment
896                 // skip it otherwise fall through
897                 if (nextpar
898                         && (nextpar->layout() != par.layout()
899                         || nextpar->params().depth() != par.params().depth()))
900                         break;
901         }
902
903         // fall through possible
904         default:
905                 // we don't need it for the last paragraph!!!
906                 if (nextpar)
907                         pending_newline = true;
908         }
909
910         if (par.allowParagraphCustomization()) {
911                 if (!par.params().spacing().isDefault()
912                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
913                         if (pending_newline)
914                                 os << '\n';
915
916                         string const endtag =
917                                 par.params().spacing().writeEnvirEnd(useSetSpace);
918                         if (prefixIs(endtag, "\\end{"))
919                                 os << breakln;
920
921                         os << from_ascii(endtag);
922                         pending_newline = true;
923                 }
924         }
925
926         // Closing the language is needed for the last paragraph; it is also
927         // needed if we're within an \L or \R that we may have opened above (not
928         // necessarily in this paragraph) and are about to close.
929         bool closing_rtl_ltr_environment = !use_polyglossia
930                 // not for ArabTeX
931                 && (par_language->lang() != "arabic_arabtex"
932                     && outer_language->lang() != "arabic_arabtex")
933                 // have we opened an \L or \R environment?
934                 && runparams.local_font != 0
935                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
936                 // are we about to close the language?
937                 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
938                    || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
939
940         if (closing_rtl_ltr_environment
941             || (runparams.isLastPar
942                 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
943                     || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
944                 // Since \selectlanguage write the language to the aux file,
945                 // we need to reset the language at the end of footnote or
946                 // float.
947
948                 if (pending_newline)
949                         os << '\n';
950
951                 // when the paragraph uses CJK, the language has to be closed earlier
952                 if (font.language()->encoding()->package() != Encoding::CJK) {
953                         if (lang_end_command.empty()) {
954                                 // If this is a child, we should restore the
955                                 // master language after the last paragraph.
956                                 Language const * const current_language =
957                                         (runparams.isLastPar && runparams.master_language)
958                                                 ? runparams.master_language
959                                                 : outer_language;
960                                 string const current_lang = use_polyglossia
961                                         ? getPolyglossiaEnvName(current_language)
962                                         : current_language->babel();
963                                 if (!current_lang.empty()) {
964                                         string bc = use_polyglossia ?
965                                                     getPolyglossiaBegin(lang_begin_command, current_lang,
966                                                                         current_language->polyglossiaOpts())
967                                                   : subst(lang_begin_command, "$$lang", current_lang);
968                                         os << bc;
969                                         pending_newline = !localswitch;
970                                         unskip_newline = !localswitch;
971                                 }
972                         } else if (!par_lang.empty()) {
973                                 // If we are in an environment, we have to close the "outer" language afterwards
974                                 if (!style.isEnvironment() || state->open_polyglossia_lang_ != par_lang) {
975                                         os << from_ascii(subst(
976                                                 lang_end_command,
977                                                 "$$lang",
978                                                 par_lang));
979                                         pending_newline = !localswitch;
980                                         unskip_newline = !localswitch;
981                                 }
982                         }
983                 }
984         }
985         if (closing_rtl_ltr_environment)
986                 os << "}";
987
988         bool const last_was_separator =
989                 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
990
991         if (pending_newline) {
992                 if (unskip_newline)
993                         // prevent unwanted whitespace
994                         os << '%';
995                 if (!os.afterParbreak() && !last_was_separator)
996                         os << '\n';
997         }
998
999         // if this is a CJK-paragraph and the next isn't, close CJK
1000         // also if the next paragraph is a multilingual environment (because of nesting)
1001         if (nextpar
1002                 && state->open_encoding_ == CJK
1003                 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
1004                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1005                 // inbetween environments, CJK has to be closed later (nesting!)
1006                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1007                 os << "\\end{CJK}\n";
1008                 state->open_encoding_ = none;
1009         }
1010
1011         // If this is the last paragraph, close the CJK environment
1012         // if necessary. If it's an environment, we'll have to \end that first.
1013         if (runparams.isLastPar && !style.isEnvironment()) {
1014                 switch (state->open_encoding_) {
1015                         case CJK: {
1016                                 // do nothing at the end of child documents
1017                                 if (maintext && buf.masterBuffer() != &buf)
1018                                         break;
1019                                 // end of main text
1020                                 if (maintext) {
1021                                         os << "\n\\end{CJK}\n";
1022                                 // end of an inset
1023                                 } else
1024                                         os << "\\end{CJK}";
1025                                 state->open_encoding_ = none;
1026                                 break;
1027                         }
1028                         case inputenc: {
1029                                 os << "\\egroup";
1030                                 state->open_encoding_ = none;
1031                                 break;
1032                         }
1033                         case none:
1034                         default:
1035                                 // do nothing
1036                                 break;
1037                 }
1038         }
1039
1040         // If this is the last paragraph, and a local_font was set upon entering
1041         // the inset, and we're using "auto" or "default" encoding, the encoding
1042         // should be set back to that local_font's encoding.
1043         // However, do not change the encoding when non-TeX fonts are used.
1044         if (runparams.isLastPar && runparams_in.local_font != 0
1045             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1046             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1047             && (!runparams.isFullUnicode())) { // FIXME: test for UseTeXFonts
1048                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1049                 os << setEncoding(runparams_in.encoding->iconvName());
1050         }
1051         // Otherwise, the current encoding should be set for the next paragraph.
1052         else
1053                 runparams_in.encoding = runparams.encoding;
1054
1055
1056         // we don't need a newline for the last paragraph!!!
1057         // Note from JMarc: we will re-add a \n explicitly in
1058         // TeXEnvironment, because it is needed in this case
1059         if (nextpar && !os.afterParbreak() && !last_was_separator) {
1060                 // Make sure to start a new line
1061                 os << breakln;
1062                 Layout const & next_layout = nextpar->layout();
1063                 // A newline '\n' is always output before a command,
1064                 // so avoid doubling it.
1065                 if (!next_layout.isCommand()) {
1066                         // Here we now try to avoid spurious empty lines by
1067                         // outputting a paragraph break only if: (case 1) the
1068                         // paragraph style allows parbreaks and no \begin, \end
1069                         // or \item tags are going to follow (i.e., if the next
1070                         // isn't the first or the current isn't the last
1071                         // paragraph of an environment or itemize) and the
1072                         // depth and alignment of the following paragraph is
1073                         // unchanged, or (case 2) the following is a
1074                         // non-environment paragraph whose depth is increased
1075                         // but whose alignment is unchanged, or (case 3) the
1076                         // paragraph is not an environment and the next one is a
1077                         // non-itemize-like env at lower depth, or (case 4) the
1078                         // paragraph is a command not followed by an environment
1079                         // and the alignment of the current and next paragraph
1080                         // is unchanged, or (case 5) the current alignment is
1081                         // changed and a standard paragraph follows.
1082                         DocumentClass const & tclass = bparams.documentClass();
1083                         if ((style == next_layout
1084                              && !style.parbreak_is_newline
1085                              && !text.inset().getLayout().parbreakIsNewline()
1086                              && style.latextype != LATEX_ITEM_ENVIRONMENT
1087                              && style.latextype != LATEX_LIST_ENVIRONMENT
1088                              && style.align == par.getAlign()
1089                              && nextpar->getDepth() == par.getDepth()
1090                              && nextpar->getAlign() == par.getAlign())
1091                             || (!next_layout.isEnvironment()
1092                                 && nextpar->getDepth() > par.getDepth()
1093                                 && nextpar->getAlign() == par.getAlign())
1094                             || (!style.isEnvironment()
1095                                 && next_layout.latextype == LATEX_ENVIRONMENT
1096                                 && nextpar->getDepth() < par.getDepth())
1097                             || (style.isCommand()
1098                                 && !next_layout.isEnvironment()
1099                                 && style.align == par.getAlign()
1100                                 && next_layout.align == nextpar->getAlign())
1101                             || (style.align != par.getAlign()
1102                                 && tclass.isDefaultLayout(next_layout))) {
1103                                 os << '\n';
1104                         }
1105                 }
1106         }
1107
1108         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1109                 << &par << " next " << nextpar);
1110
1111         return;
1112 }
1113
1114
1115 // LaTeX all paragraphs
1116 void latexParagraphs(Buffer const & buf,
1117                      Text const & text,
1118                      otexstream & os,
1119                      OutputParams const & runparams,
1120                      string const & everypar)
1121 {
1122         LASSERT(runparams.par_begin <= runparams.par_end,
1123                 { os << "% LaTeX Output Error\n"; return; } );
1124
1125         BufferParams const & bparams = buf.params();
1126
1127         bool const maintext = text.isMainText();
1128         bool const is_child = buf.masterBuffer() != &buf;
1129
1130         // Open a CJK environment at the beginning of the main buffer
1131         // if the document's language is a CJK language
1132         // (but not in child documents)
1133         OutputState * state = getOutputState();
1134         if (maintext && !is_child
1135             && bparams.encoding().package() == Encoding::CJK) {
1136                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1137                 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1138                 state->open_encoding_ = CJK;
1139         }
1140         // if "auto begin" is switched off, explicitly switch the
1141         // language on at start
1142         string const mainlang = runparams.use_polyglossia
1143                 ? getPolyglossiaEnvName(bparams.language)
1144                 : bparams.language->babel();
1145         string const lang_begin_command = runparams.use_polyglossia ?
1146                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1147
1148         if (maintext && !lyxrc.language_auto_begin &&
1149             !mainlang.empty()) {
1150                 // FIXME UNICODE
1151                 string bc = runparams.use_polyglossia ?
1152                             getPolyglossiaBegin(lang_begin_command, mainlang,
1153                                                 bparams.language->polyglossiaOpts())
1154                           : subst(lang_begin_command, "$$lang", mainlang);
1155                 os << bc;
1156                 os << '\n';
1157         }
1158
1159         ParagraphList const & paragraphs = text.paragraphs();
1160
1161         if (runparams.par_begin == runparams.par_end) {
1162                 // The full doc will be exported but it is easier to just rely on
1163                 // runparams range parameters that will be passed TeXEnvironment.
1164                 runparams.par_begin = 0;
1165                 runparams.par_end = paragraphs.size();
1166         }
1167
1168         pit_type pit = runparams.par_begin;
1169         // lastpit is for the language check after the loop.
1170         pit_type lastpit = pit;
1171         // variables used in the loop:
1172         bool was_title = false;
1173         bool already_title = false;
1174         DocumentClass const & tclass = bparams.documentClass();
1175
1176         for (; pit < runparams.par_end; ++pit) {
1177                 lastpit = pit;
1178                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1179
1180                 // FIXME This check should not be needed. We should
1181                 // perhaps issue an error if it is.
1182                 Layout const & layout = text.inset().forcePlainLayout() ?
1183                                 tclass.plainLayout() : par->layout();
1184
1185                 if (layout.intitle) {
1186                         if (already_title) {
1187                                 LYXERR0("Error in latexParagraphs: You"
1188                                         " should not mix title layouts"
1189                                         " with normal ones.");
1190                         } else if (!was_title) {
1191                                 was_title = true;
1192                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1193                                         os << "\\begin{"
1194                                                         << from_ascii(tclass.titlename())
1195                                                         << "}\n";
1196                                 }
1197                         }
1198                 } else if (was_title && !already_title) {
1199                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1200                                 os << "\\end{" << from_ascii(tclass.titlename())
1201                                                 << "}\n";
1202                         }
1203                         else {
1204                                 os << "\\" << from_ascii(tclass.titlename())
1205                                                 << "\n";
1206                         }
1207                         already_title = true;
1208                         was_title = false;
1209                 }
1210
1211
1212                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1213                         // This is a standard top level paragraph, TeX it and continue.
1214                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1215                         continue;
1216                 }
1217                 
1218                 TeXEnvironmentData const data =
1219                         prepareEnvironment(buf, text, par, os, runparams);
1220                 // pit can be changed in TeXEnvironment.
1221                 TeXEnvironment(buf, text, runparams, pit, os);
1222                 finishEnvironment(os, runparams, data);
1223         }
1224
1225         if (pit == runparams.par_end) {
1226                         // Make sure that the last paragraph is
1227                         // correctly terminated (because TeXOnePar does
1228                         // not add a \n in this case)
1229                         //os << '\n';
1230         }
1231
1232         // It might be that we only have a title in this document
1233         if (was_title && !already_title) {
1234                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1235                         os << "\\end{" << from_ascii(tclass.titlename())
1236                            << "}\n";
1237                 } else {
1238                         os << "\\" << from_ascii(tclass.titlename())
1239                            << "\n";
1240                 }
1241         }
1242
1243         // if "auto end" is switched off, explicitly close the language at the end
1244         // but only if the last par is in a babel or polyglossia language
1245         string const lang_end_command = runparams.use_polyglossia ?
1246                 "\\end{$$lang}" : lyxrc.language_command_end;
1247         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1248                 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1249                 os << from_utf8(subst(lang_end_command,
1250                                         "$$lang",
1251                                         mainlang))
1252                         << '\n';
1253                 if (state->open_polyglossia_lang_ == mainlang)
1254                         state->open_polyglossia_lang_ = "";
1255         }
1256
1257         // If the last paragraph is an environment, we'll have to close
1258         // CJK at the very end to do proper nesting.
1259         if (maintext && !is_child && state->open_encoding_ == CJK) {
1260                 os << "\\end{CJK}\n";
1261                 state->open_encoding_ = none;
1262         }
1263         // Likewise for polyglossia
1264         if (maintext && !is_child && state->open_polyglossia_lang_ != "") {
1265                 os << from_utf8(subst(lang_end_command,
1266                                         "$$lang",
1267                                         state->open_polyglossia_lang_))
1268                    << '\n';
1269                 state->open_polyglossia_lang_ = "";
1270         }
1271
1272         // reset inherited encoding
1273         if (state->cjk_inherited_ > 0) {
1274                 state->cjk_inherited_ -= 1;
1275                 if (state->cjk_inherited_ == 0)
1276                         state->open_encoding_ = CJK;
1277         }
1278 }
1279
1280
1281 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1282                    OutputParams const & runparams, Encoding const & newEnc,
1283                    bool force)
1284 {
1285         Encoding const & oldEnc = *runparams.encoding;
1286         bool moving_arg = runparams.moving_arg;
1287         // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1288         bool const from_to_cjk = 
1289                 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1290                 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1291         if (!force && !from_to_cjk
1292             && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1293                 return make_pair(false, 0);
1294
1295         // Do nothing if the encoding is unchanged.
1296         if (oldEnc.name() == newEnc.name())
1297                 return make_pair(false, 0);
1298
1299         // FIXME We ignore encoding switches from/to encodings that do
1300         // neither support the inputenc package nor the CJK package here.
1301         // This does of course only work in special cases (e.g. switch from
1302         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1303         // but it is the best we can do
1304         if (oldEnc.package() == Encoding::none
1305                 || newEnc.package() == Encoding::none)
1306                 return make_pair(false, 0);
1307
1308         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1309                 << oldEnc.name() << " to " << newEnc.name());
1310         os << setEncoding(newEnc.iconvName());
1311         if (bparams.inputenc == "default")
1312                 return make_pair(true, 0);
1313
1314         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1315         OutputState * state = getOutputState();
1316         switch (newEnc.package()) {
1317                 case Encoding::none:
1318                 case Encoding::japanese:
1319                         // shouldn't ever reach here, see above
1320                         return make_pair(true, 0);
1321                 case Encoding::inputenc: {
1322                         int count = inputenc_arg.length();
1323                         if (oldEnc.package() == Encoding::CJK &&
1324                             state->open_encoding_ == CJK) {
1325                                 os << "\\end{CJK}";
1326                                 state->open_encoding_ = none;
1327                                 count += 9;
1328                         }
1329                         else if (oldEnc.package() == Encoding::inputenc &&
1330                                  state->open_encoding_ == inputenc) {
1331                                 os << "\\egroup";
1332                                 state->open_encoding_ = none;
1333                                 count += 7;
1334                         }
1335                         if (runparams.local_font != 0
1336                             &&  oldEnc.package() == Encoding::CJK) {
1337                                 // within insets, \inputenc switches need
1338                                 // to be embraced within \bgroup...\egroup;
1339                                 // else CJK fails.
1340                                 os << "\\bgroup";
1341                                 count += 7;
1342                                 state->open_encoding_ = inputenc;
1343                         }
1344                         // with the japanese option, inputenc is omitted.
1345                         if (runparams.use_japanese)
1346                                 return make_pair(true, count);
1347                         os << "\\inputencoding{" << inputenc_arg << '}';
1348                         return make_pair(true, count + 16);
1349                 }
1350                 case Encoding::CJK: {
1351                         int count = inputenc_arg.length();
1352                         if (oldEnc.package() == Encoding::CJK &&
1353                             state->open_encoding_ == CJK) {
1354                                 os << "\\end{CJK}";
1355                                 count += 9;
1356                         }
1357                         if (oldEnc.package() == Encoding::inputenc &&
1358                             state->open_encoding_ == inputenc) {
1359                                 os << "\\egroup";
1360                                 count += 7;
1361                         }
1362                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1363                            << from_ascii(bparams.fonts_cjk) << "}";
1364                         state->open_encoding_ = CJK;
1365                         return make_pair(true, count + 15);
1366                 }
1367         }
1368         // Dead code to avoid a warning:
1369         return make_pair(true, 0);
1370
1371 }
1372
1373 } // namespace lyx