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