]> git.lyx.org Git - features.git/blob - src/output_latex.cpp
Remove unused variables found by cppcheck
[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 #include "TexRow.h"
28
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetArgument.h"
31
32 #include "support/lassert.h"
33 #include "support/convert.h"
34 #include "support/debug.h"
35 #include "support/lstrings.h"
36 #include "support/lyxalgo.h"
37 #include "support/textutils.h"
38
39 #include <QThreadStorage>
40
41 #include <list>
42
43 using namespace std;
44 using namespace lyx::support;
45
46
47 namespace lyx {
48
49 namespace {
50
51 enum OpenEncoding {
52         none,
53         inputenc,
54         CJK
55 };
56
57
58 struct OutputState
59 {
60         OutputState() : open_encoding_(none), cjk_inherited_(0),
61                         prev_env_language_(0), open_polyglossia_lang_("")
62         {
63         }
64         int open_encoding_;
65         int cjk_inherited_;
66         Language const * prev_env_language_;
67         string open_polyglossia_lang_;
68 };
69
70
71 OutputState * getOutputState()
72 {
73         // FIXME An instance of OutputState should be kept around for each export
74         //       instead of using local thread storage
75         static QThreadStorage<OutputState *> outputstate;
76         if (!outputstate.hasLocalData())
77                 outputstate.setLocalData(new OutputState);
78         return outputstate.localData();
79 }
80
81
82 string const getPolyglossiaEnvName(Language const * lang)
83 {
84         string result = lang->polyglossia();
85         if (result == "arabic")
86                 // exceptional spelling; see polyglossia docs.
87                 result = "Arabic";
88         return result;
89 }
90
91
92 string const getPolyglossiaBegin(string const & lang_begin_command,
93                                  string const & lang, string const & opts)
94 {
95         string result;
96         if (!lang.empty())
97                 result = subst(lang_begin_command, "$$lang", lang);
98         string options = opts.empty() ?
99                     string() : "[" + opts + "]";
100         result = subst(result, "$$opts", options);
101
102         return result;
103 }
104
105
106 struct TeXEnvironmentData
107 {
108         bool cjk_nested;
109         Layout const * style;
110         Language const * par_language;
111         Encoding const * prev_encoding;
112         bool leftindent_open;
113 };
114
115
116 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
117                                         Text const & text,
118                                         ParagraphList::const_iterator pit,
119                                         otexstream & os,
120                                         OutputParams const & runparams)
121 {
122         TeXEnvironmentData data;
123
124         BufferParams const & bparams = buf.params();
125
126         // FIXME This test should not be necessary.
127         // We should perhaps issue an error if it is.
128         Layout const & style = text.inset().forcePlainLayout() ?
129                 bparams.documentClass().plainLayout() : pit->layout();
130
131         ParagraphList const & paragraphs = text.paragraphs();
132         ParagraphList::const_iterator const priorpit =
133                 pit == paragraphs.begin() ? pit : prev(pit, 1);
134
135         OutputState * state = getOutputState();
136         bool const use_prev_env_language = state->prev_env_language_ != 0
137                         && priorpit->layout().isEnvironment()
138                         && (priorpit->getDepth() > pit->getDepth()
139                             || (priorpit->getDepth() == pit->getDepth()
140                                 && priorpit->layout() != pit->layout()));
141
142         data.prev_encoding = runparams.encoding;
143         data.par_language = pit->getParLanguage(bparams);
144         Language const * const doc_language = bparams.language;
145         Language const * const prev_par_language =
146                 (pit != paragraphs.begin())
147                 ? (use_prev_env_language ? state->prev_env_language_
148                                          : priorpit->getParLanguage(bparams))
149                 : doc_language;
150
151         bool const use_polyglossia = runparams.use_polyglossia;
152         string const par_lang = use_polyglossia ?
153                 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
154         string const prev_par_lang = use_polyglossia ?
155                 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
156         string const doc_lang = use_polyglossia ?
157                 getPolyglossiaEnvName(doc_language) : doc_language->babel();
158         string const lang_begin_command = use_polyglossia ?
159                 "\\begin{$$lang}" : lyxrc.language_command_begin;
160         string const lang_end_command = use_polyglossia ?
161                 "\\end{$$lang}" : lyxrc.language_command_end;
162
163         if (par_lang != prev_par_lang) {
164                 if (!lang_end_command.empty() &&
165                     prev_par_lang != doc_lang &&
166                     !prev_par_lang.empty()) {
167                         os << from_ascii(subst(
168                                 lang_end_command,
169                                 "$$lang",
170                                 prev_par_lang))
171                           // the '%' is necessary to prevent unwanted whitespace
172                           << "%\n";
173                 }
174
175                 if ((lang_end_command.empty() ||
176                     par_lang != doc_lang) &&
177                     !par_lang.empty()) {
178                             string bc = use_polyglossia ?
179                                         getPolyglossiaBegin(lang_begin_command, par_lang,
180                                                             data.par_language->polyglossiaOpts())
181                                       : subst(lang_begin_command, "$$lang", par_lang);
182                             os << bc;
183                             // the '%' is necessary to prevent unwanted whitespace
184                             os << "%\n";
185                 }
186         }
187
188         data.leftindent_open = false;
189         if (!pit->params().leftIndent().zero()) {
190                 os << "\\begin{LyXParagraphLeftIndent}{"
191                    << from_ascii(pit->params().leftIndent().asLatexString())
192                    << "}\n";
193                 data.leftindent_open = true;
194         }
195
196         if (style.isEnvironment()) {
197                 if (par_lang != doc_lang)
198                         state->open_polyglossia_lang_ = par_lang;
199                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
200                 if (!style.latexargs().empty()) {
201                         OutputParams rp = runparams;
202                         rp.local_font = &pit->getFirstFontSettings(bparams);
203                         latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
204                 }
205                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
206                         os << '{'
207                            << pit->params().labelWidthString()
208                            << "}\n";
209                 } else if (style.labeltype == LABEL_BIBLIO) {
210                         if (pit->params().labelWidthString().empty())
211                                 os << '{' << bibitemWidest(buf, runparams) << "}\n";
212                         else
213                                 os << '{'
214                                   << pit->params().labelWidthString()
215                                   << "}\n";
216                 } else
217                         os << from_ascii(style.latexparam()) << '\n';
218         }
219         data.style = &style;
220
221         // in multilingual environments, the CJK tags have to be nested properly
222         data.cjk_nested = false;
223         if (data.par_language->encoding()->package() == Encoding::CJK &&
224             state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
225                 if (prev_par_language->encoding()->package() == Encoding::CJK)
226                         os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
227                            << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
228                 state->open_encoding_ = CJK;
229                 data.cjk_nested = true;
230         }
231         return data;
232 }
233
234
235 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
236                               TeXEnvironmentData const & data)
237 {
238         OutputState * state = getOutputState();
239         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.isFullUnicode())
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.isFullUnicode())
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         // The document's language
642         Language const * const doc_language = bparams.language;
643         // The language that was in effect when the environment this paragraph is
644         // inside of was opened
645         Language const * const outer_language =
646                 (runparams.local_font != 0) ?
647                         runparams.local_font->language() : doc_language;
648
649         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
650
651         // The previous language that was in effect is the language of the
652         // previous paragraph, unless the previous paragraph is inside an
653         // environment with nesting depth greater than (or equal to, but with
654         // a different layout) the current one. If there is no previous
655         // paragraph, the previous language is the outer language.
656         bool const use_prev_env_language = state->prev_env_language_ != 0
657                         && priorpar
658                         && priorpar->layout().isEnvironment()
659                         && (priorpar->getDepth() > par.getDepth()
660                             || (priorpar->getDepth() == par.getDepth()
661                                     && priorpar->layout() != par.layout()));
662         Language const * const prev_language =
663                 (pit != 0)
664                 ? (use_prev_env_language ? state->prev_env_language_
665                                          : priorpar->getParLanguage(bparams))
666                 : outer_language;
667
668
669         bool const use_polyglossia = runparams.use_polyglossia;
670         string const par_lang = use_polyglossia ?
671                 getPolyglossiaEnvName(par_language): par_language->babel();
672         string const prev_lang = use_polyglossia ?
673                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
674         string const outer_lang = use_polyglossia ?
675                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
676         string lang_begin_command = use_polyglossia ?
677                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
678         string lang_end_command = use_polyglossia ?
679                 "\\end{$$lang}" : lyxrc.language_command_end;
680         // the '%' is necessary to prevent unwanted whitespace
681         string lang_command_termination = "%\n";
682
683         // In some insets (such as Arguments), we cannot use \selectlanguage
684         bool const localswitch = text.inset().forceLocalFontSwitch();
685         if (localswitch) {
686                 lang_begin_command = use_polyglossia ?
687                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
688                 lang_end_command = "}";
689                 lang_command_termination.clear();
690         }
691
692         if (par_lang != prev_lang
693                 // check if we already put language command in TeXEnvironment()
694                 && !(style.isEnvironment()
695                      && (pit == 0 || (priorpar->layout() != par.layout()
696                                           && priorpar->getDepth() <= par.getDepth())
697                                   || priorpar->getDepth() < par.getDepth())))
698         {
699                 if (!lang_end_command.empty() &&
700                     prev_lang != outer_lang &&
701                     !prev_lang.empty())
702                 {
703                         os << from_ascii(subst(lang_end_command,
704                                 "$$lang",
705                                 prev_lang))
706                            << lang_command_termination;
707                 }
708
709                 // We need to open a new language if we couldn't close the previous
710                 // one (because there's no language_command_end); and even if we closed
711                 // the previous one, if the current language is different than the
712                 // outer_language (which is currently in effect once the previous one
713                 // is closed).
714                 if ((lang_end_command.empty() || par_lang != outer_lang)
715                         && !par_lang.empty()) {
716                         // If we're inside an inset, and that inset is within an \L or \R
717                         // (or equivalents), then within the inset, too, any opposite
718                         // language paragraph should appear within an \L or \R (in addition
719                         // to, outside of, the normal language switch commands).
720                         // This behavior is not correct for ArabTeX, though.
721                         if (!use_polyglossia
722                             // not for ArabTeX
723                                 && par_language->lang() != "arabic_arabtex"
724                                 && outer_language->lang() != "arabic_arabtex"
725                             // are we in an inset?
726                             && runparams.local_font != 0
727                             // is the inset within an \L or \R?
728                             //
729                             // FIXME: currently, we don't check this; this means that
730                             // we'll have unnnecessary \L and \R commands, but that
731                             // doesn't seem to hurt (though latex will complain)
732                             //
733                             // is this paragraph in the opposite direction?
734                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
735                                 // FIXME: I don't have a working copy of the Arabi package, so
736                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
737                                 // or not...
738                                 if (par_language->lang() == "farsi")
739                                         os << "\\textFR{";
740                                 else if (outer_language->lang() == "farsi")
741                                         os << "\\textLR{";
742                                 else if (par_language->lang() == "arabic_arabi")
743                                         os << "\\textAR{";
744                                 else if (outer_language->lang() == "arabic_arabi")
745                                         os << "\\textLR{";
746                                 // remaining RTL languages currently is hebrew
747                                 else if (par_language->rightToLeft())
748                                         os << "\\R{";
749                                 else
750                                         os << "\\L{";
751                         }
752                         // With CJK, the CJK tag has to be closed first (see below)
753                         if (runparams.encoding->package() != Encoding::CJK
754                             && !par_lang.empty()) {
755                                 string bc = use_polyglossia ?
756                                           getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
757                                           : subst(lang_begin_command, "$$lang", par_lang);
758                                 os << bc;
759                                 os << lang_command_termination;
760                         }
761                 }
762         }
763
764         // Switch file encoding if necessary; no need to do this for "default"
765         // encoding, since this only affects the position of the outputted
766         // \inputencoding command; the encoding switch will occur when necessary
767         if (bparams.inputenc == "auto"
768                 && runparams.encoding->package() != Encoding::none) {
769                 // Look ahead for future encoding changes.
770                 // We try to output them at the beginning of the paragraph,
771                 // since the \inputencoding command is not allowed e.g. in
772                 // sections. For this reason we only set runparams.moving_arg
773                 // after checking for the encoding change, otherwise the
774                 // change would be always avoided by switchEncoding().
775                 for (pos_type i = 0; i < par.size(); ++i) {
776                         char_type const c = par.getChar(i);
777                         Encoding const * const encoding =
778                                 par.getFontSettings(bparams, i).language()->encoding();
779                         if (encoding->package() != Encoding::CJK
780                                 && runparams.encoding->package() == Encoding::inputenc
781                                 && isASCII(c))
782                                 continue;
783                         if (par.isInset(i))
784                                 break;
785                         // All characters before c are in the ASCII range, and
786                         // c is non-ASCII (but no inset), so change the
787                         // encoding to that required by the language of c.
788                         // With CJK, only add switch if we have CJK content at the beginning
789                         // of the paragraph
790                         if (i != 0 && encoding->package() == Encoding::CJK)
791                                 continue;
792
793                         pair<bool, int> enc_switch = switchEncoding(os.os(),
794                                                 bparams, runparams, *encoding);
795                         // the following is necessary after a CJK environment in a multilingual
796                         // context (nesting issue).
797                         if (par_language->encoding()->package() == Encoding::CJK
798                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
799                                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
800                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
801                                 state->open_encoding_ = CJK;
802                         }
803                         if (encoding->package() != Encoding::none && enc_switch.first) {
804                                 if (enc_switch.second > 0) {
805                                         // the '%' is necessary to prevent unwanted whitespace
806                                         os << "%\n";
807                                 }
808                                 // With CJK, the CJK tag had to be closed first (see above)
809                                 if (runparams.encoding->package() == Encoding::CJK
810                                     && !par_lang.empty()) {
811                                         os << from_ascii(subst(
812                                                 lang_begin_command,
813                                                 "$$lang",
814                                                 par_lang))
815                                         << lang_command_termination;
816                                 }
817                                 runparams.encoding = encoding;
818                         }
819                         break;
820                 }
821         }
822
823         runparams.moving_arg |= style.needprotect;
824         Encoding const * const prev_encoding = runparams.encoding;
825
826         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
827         if (par.allowParagraphCustomization()) {
828                 if (par.params().startOfAppendix()) {
829                         os << "\n\\appendix\n";
830                 }
831
832                 if (!par.params().spacing().isDefault()
833                         && (pit == 0 || !priorpar->hasSameLayout(par)))
834                 {
835                         os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
836                             << '\n';
837                 }
838
839                 if (style.isCommand()) {
840                         os << '\n';
841                 }
842         }
843
844         parStartCommand(par, os, runparams, style);
845         Font const outerfont = text.outerFont(pit);
846
847         // FIXME UNICODE
848         os << from_utf8(everypar);
849         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
850
851         // Make sure that \\par is done with the font of the last
852         // character if this has another size as the default.
853         // This is necessary because LaTeX (and LyX on the screen)
854         // calculates the space between the baselines according
855         // to this font. (Matthias)
856         //
857         // We must not change the font for the last paragraph
858         // of non-multipar insets, tabular cells or commands,
859         // since this produces unwanted whitespace.
860
861         Font const font = par.empty()
862                  ? par.getLayoutFont(bparams, outerfont)
863                  : par.getFont(bparams, par.size() - 1, outerfont);
864
865         bool const is_command = style.isCommand();
866
867         if (style.resfont.size() != font.fontInfo().size()
868             && (nextpar || maintext
869                 || (text.inset().paragraphs().size() > 1
870                     && text.inset().lyxCode() != CELL_CODE))
871             && !is_command) {
872                 os << '{';
873                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
874         } else if (is_command) {
875                 os << '}';
876                 if (!style.postcommandargs().empty())
877                         latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
878                 if (runparams.encoding != prev_encoding) {
879                         runparams.encoding = prev_encoding;
880                         if (!runparams.isFullUnicode())
881                                 os << setEncoding(prev_encoding->iconvName());
882                 }
883         }
884
885         bool pending_newline = false;
886         bool unskip_newline = false;
887         switch (style.latextype) {
888         case LATEX_ITEM_ENVIRONMENT:
889         case LATEX_LIST_ENVIRONMENT:
890                 if (nextpar && par.params().depth() < nextpar->params().depth())
891                         pending_newline = true;
892                 break;
893         case LATEX_ENVIRONMENT: {
894                 // if its the last paragraph of the current environment
895                 // skip it otherwise fall through
896                 if (nextpar
897                         && (nextpar->layout() != par.layout()
898                         || nextpar->params().depth() != par.params().depth()))
899                         break;
900         }
901
902         // fall through possible
903         default:
904                 // we don't need it for the last paragraph!!!
905                 if (nextpar)
906                         pending_newline = true;
907         }
908
909         if (par.allowParagraphCustomization()) {
910                 if (!par.params().spacing().isDefault()
911                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
912                         if (pending_newline)
913                                 os << '\n';
914
915                         string const endtag =
916                                 par.params().spacing().writeEnvirEnd(useSetSpace);
917                         if (prefixIs(endtag, "\\end{"))
918                                 os << breakln;
919
920                         os << from_ascii(endtag);
921                         pending_newline = true;
922                 }
923         }
924
925         // Closing the language is needed for the last paragraph; it is also
926         // needed if we're within an \L or \R that we may have opened above (not
927         // necessarily in this paragraph) and are about to close.
928         bool closing_rtl_ltr_environment = !use_polyglossia
929                 // not for ArabTeX
930                 && (par_language->lang() != "arabic_arabtex"
931                     && outer_language->lang() != "arabic_arabtex")
932                 // have we opened an \L or \R environment?
933                 && runparams.local_font != 0
934                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
935                 // are we about to close the language?
936                 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
937                    || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
938
939         if (closing_rtl_ltr_environment
940             || (runparams.isLastPar
941                 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
942                     || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
943                 // Since \selectlanguage write the language to the aux file,
944                 // we need to reset the language at the end of footnote or
945                 // float.
946
947                 if (pending_newline)
948                         os << '\n';
949
950                 // when the paragraph uses CJK, the language has to be closed earlier
951                 if (font.language()->encoding()->package() != Encoding::CJK) {
952                         if (lang_end_command.empty()) {
953                                 // If this is a child, we should restore the
954                                 // master language after the last paragraph.
955                                 Language const * const current_language =
956                                         (runparams.isLastPar && runparams.master_language)
957                                                 ? runparams.master_language
958                                                 : outer_language;
959                                 string const current_lang = use_polyglossia
960                                         ? getPolyglossiaEnvName(current_language)
961                                         : current_language->babel();
962                                 if (!current_lang.empty()) {
963                                         string bc = use_polyglossia ?
964                                                     getPolyglossiaBegin(lang_begin_command, current_lang,
965                                                                         current_language->polyglossiaOpts())
966                                                   : subst(lang_begin_command, "$$lang", current_lang);
967                                         os << bc;
968                                         pending_newline = !localswitch;
969                                         unskip_newline = !localswitch;
970                                 }
971                         } else if (!par_lang.empty()) {
972                                 // If we are in an environment, we have to close the "outer" language afterwards
973                                 if (!style.isEnvironment() || state->open_polyglossia_lang_ != par_lang) {
974                                         os << from_ascii(subst(
975                                                 lang_end_command,
976                                                 "$$lang",
977                                                 par_lang));
978                                         pending_newline = !localswitch;
979                                         unskip_newline = !localswitch;
980                                 }
981                         }
982                 }
983         }
984         if (closing_rtl_ltr_environment)
985                 os << "}";
986
987         bool const last_was_separator =
988                 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
989
990         if (pending_newline) {
991                 if (unskip_newline)
992                         // prevent unwanted whitespace
993                         os << '%';
994                 if (!os.afterParbreak() && !last_was_separator)
995                         os << '\n';
996         }
997
998         // if this is a CJK-paragraph and the next isn't, close CJK
999         // also if the next paragraph is a multilingual environment (because of nesting)
1000         if (nextpar
1001                 && state->open_encoding_ == CJK
1002                 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
1003                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1004                 // inbetween environments, CJK has to be closed later (nesting!)
1005                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1006                 os << "\\end{CJK}\n";
1007                 state->open_encoding_ = none;
1008         }
1009
1010         // If this is the last paragraph, close the CJK environment
1011         // if necessary. If it's an environment, we'll have to \end that first.
1012         if (runparams.isLastPar && !style.isEnvironment()) {
1013                 switch (state->open_encoding_) {
1014                         case CJK: {
1015                                 // do nothing at the end of child documents
1016                                 if (maintext && buf.masterBuffer() != &buf)
1017                                         break;
1018                                 // end of main text
1019                                 if (maintext) {
1020                                         os << "\n\\end{CJK}\n";
1021                                 // end of an inset
1022                                 } else
1023                                         os << "\\end{CJK}";
1024                                 state->open_encoding_ = none;
1025                                 break;
1026                         }
1027                         case inputenc: {
1028                                 os << "\\egroup";
1029                                 state->open_encoding_ = none;
1030                                 break;
1031                         }
1032                         case none:
1033                         default:
1034                                 // do nothing
1035                                 break;
1036                 }
1037         }
1038
1039         // If this is the last paragraph, and a local_font was set upon entering
1040         // the inset, and we're using "auto" or "default" encoding, the encoding
1041         // should be set back to that local_font's encoding.
1042         // However, do not change the encoding when a fully unicode aware backend
1043         // such as XeTeX is 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())) {
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 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         }
1254
1255         // If the last paragraph is an environment, we'll have to close
1256         // CJK at the very end to do proper nesting.
1257         if (maintext && !is_child && state->open_encoding_ == CJK) {
1258                 os << "\\end{CJK}\n";
1259                 state->open_encoding_ = none;
1260         }
1261         // Likewise for polyglossia
1262         if (maintext && !is_child && state->open_polyglossia_lang_ != "") {
1263                 os << "\\end{" << state->open_polyglossia_lang_ << "}\n";
1264                 state->open_polyglossia_lang_ = "";
1265         }
1266
1267         // reset inherited encoding
1268         if (state->cjk_inherited_ > 0) {
1269                 state->cjk_inherited_ -= 1;
1270                 if (state->cjk_inherited_ == 0)
1271                         state->open_encoding_ = CJK;
1272         }
1273 }
1274
1275
1276 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1277                    OutputParams const & runparams, Encoding const & newEnc,
1278                    bool force)
1279 {
1280         Encoding const & oldEnc = *runparams.encoding;
1281         bool moving_arg = runparams.moving_arg;
1282         // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1283         bool const from_to_cjk = 
1284                 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1285                 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1286         if (!force && !from_to_cjk
1287             && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1288                 return make_pair(false, 0);
1289
1290         // Do nothing if the encoding is unchanged.
1291         if (oldEnc.name() == newEnc.name())
1292                 return make_pair(false, 0);
1293
1294         // FIXME We ignore encoding switches from/to encodings that do
1295         // neither support the inputenc package nor the CJK package here.
1296         // This does of course only work in special cases (e.g. switch from
1297         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1298         // but it is the best we can do
1299         if (oldEnc.package() == Encoding::none
1300                 || newEnc.package() == Encoding::none)
1301                 return make_pair(false, 0);
1302
1303         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1304                 << oldEnc.name() << " to " << newEnc.name());
1305         os << setEncoding(newEnc.iconvName());
1306         if (bparams.inputenc == "default")
1307                 return make_pair(true, 0);
1308
1309         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1310         OutputState * state = getOutputState();
1311         switch (newEnc.package()) {
1312                 case Encoding::none:
1313                 case Encoding::japanese:
1314                         // shouldn't ever reach here, see above
1315                         return make_pair(true, 0);
1316                 case Encoding::inputenc: {
1317                         int count = inputenc_arg.length();
1318                         if (oldEnc.package() == Encoding::CJK &&
1319                             state->open_encoding_ == CJK) {
1320                                 os << "\\end{CJK}";
1321                                 state->open_encoding_ = none;
1322                                 count += 9;
1323                         }
1324                         else if (oldEnc.package() == Encoding::inputenc &&
1325                                  state->open_encoding_ == inputenc) {
1326                                 os << "\\egroup";
1327                                 state->open_encoding_ = none;
1328                                 count += 7;
1329                         }
1330                         if (runparams.local_font != 0
1331                             &&  oldEnc.package() == Encoding::CJK) {
1332                                 // within insets, \inputenc switches need
1333                                 // to be embraced within \bgroup...\egroup;
1334                                 // else CJK fails.
1335                                 os << "\\bgroup";
1336                                 count += 7;
1337                                 state->open_encoding_ = inputenc;
1338                         }
1339                         // with the japanese option, inputenc is omitted.
1340                         if (runparams.use_japanese)
1341                                 return make_pair(true, count);
1342                         os << "\\inputencoding{" << inputenc_arg << '}';
1343                         return make_pair(true, count + 16);
1344                 }
1345                 case Encoding::CJK: {
1346                         int count = inputenc_arg.length();
1347                         if (oldEnc.package() == Encoding::CJK &&
1348                             state->open_encoding_ == CJK) {
1349                                 os << "\\end{CJK}";
1350                                 count += 9;
1351                         }
1352                         if (oldEnc.package() == Encoding::inputenc &&
1353                             state->open_encoding_ == inputenc) {
1354                                 os << "\\egroup";
1355                                 count += 7;
1356                         }
1357                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1358                            << from_ascii(bparams.fonts_cjk) << "}";
1359                         state->open_encoding_ = CJK;
1360                         return make_pair(true, count + 15);
1361                 }
1362         }
1363         // Dead code to avoid a warning:
1364         return make_pair(true, 0);
1365
1366 }
1367
1368 } // namespace lyx