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