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