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