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