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