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