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