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