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