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