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