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