]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
d66279459a5f5b61c1b341274cd3ae2c4d604ed8
[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 ipar = paragraphs.constIterator(pit);
372         LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
373
374         Layout const & current_layout = ipar->layout();
375         depth_type const current_depth = ipar->params().depth();
376         Length const & current_left_indent = ipar->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         for (auto const & larg : latexargs) {
445                 Layout::latexarg const & arg = larg.second;
446                 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
447                                 vector<string> req = getVectorFromString(arg.requires);
448                                 required.insert(required.end(), req.begin(), req.end());
449                         }
450         }
451
452         for (unsigned int i = 1; i <= argnr; ++i) {
453                 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
454                 bool inserted = false;
455                 if (lit != ilist.end()) {
456                         InsetArgument const * ins = (*lit).second;
457                         if (ins) {
458                                 Layout::LaTeXArgMap::const_iterator const lait =
459                                                 latexargs.find(ins->name());
460                                 if (lait != latexargs.end()) {
461                                         Layout::latexarg arg = (*lait).second;
462                                         docstring ldelim = arg.mandatory ?
463                                                         from_ascii("{") : from_ascii("[");
464                                         docstring rdelim = arg.mandatory ?
465                                                         from_ascii("}") : from_ascii("]");
466                                         if (!arg.ldelim.empty())
467                                                 ldelim = arg.ldelim;
468                                         if (!arg.rdelim.empty())
469                                                 rdelim = arg.rdelim;
470                                         ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
471                                         inserted = true;
472                                 }
473                         }
474                 }
475                 if (!inserted) {
476                         Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
477                         Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
478                         for (; lait != laend; ++lait) {
479                                 string const name = prefix + convert<string>(i);
480                                 if ((*lait).first == name) {
481                                         Layout::latexarg arg = (*lait).second;
482                                         docstring preset = arg.presetarg;
483                                         if (!arg.defaultarg.empty()) {
484                                                 if (!preset.empty())
485                                                         preset += ",";
486                                                 preset += arg.defaultarg;
487                                         }
488                                         if (arg.mandatory) {
489                                                 docstring ldelim = arg.ldelim.empty() ?
490                                                                 from_ascii("{") : arg.ldelim;
491                                                 docstring rdelim = arg.rdelim.empty() ?
492                                                                 from_ascii("}") : arg.rdelim;
493                                                 os << ldelim << preset << rdelim;
494                                         } else if (!preset.empty()) {
495                                                 docstring ldelim = arg.ldelim.empty() ?
496                                                                 from_ascii("[") : arg.ldelim;
497                                                 docstring rdelim = arg.rdelim.empty() ?
498                                                                 from_ascii("]") : arg.rdelim;
499                                                 os << ldelim << preset << rdelim;
500                                         } else if (find(required.begin(), required.end(),
501                                                    (*lait).first) != required.end()) {
502                                                 docstring ldelim = arg.ldelim.empty() ?
503                                                                 from_ascii("[") : arg.ldelim;
504                                                 docstring rdelim = arg.rdelim.empty() ?
505                                                                 from_ascii("]") : arg.rdelim;
506                                                 os << ldelim << rdelim;
507                                         } else
508                                                 break;
509                                 }
510                         }
511                 }
512         }
513 }
514
515
516 } // namespace
517
518
519 void pushLanguageName(string const & lang_name, bool localswitch)
520 {
521         OutputState * state = getOutputState();
522
523         int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
524         state->lang_switch_depth_.push(nest_level);
525         state->open_polyglossia_lang_.push(lang_name);
526 }
527
528
529 void popLanguageName()
530 {
531         OutputState * state = getOutputState();
532
533         state->lang_switch_depth_.pop();
534         state->open_polyglossia_lang_.pop();
535 }
536
537
538 string const & openLanguageName()
539 {
540         OutputState * state = getOutputState();
541
542         return openLanguageName(state);
543 }
544
545
546 namespace {
547
548 void addArgInsets(Paragraph const & par, string const & prefix,
549                  Layout::LaTeXArgMap const & latexargs,
550                  map<int, InsetArgument const *> & ilist,
551                  vector<string> & required)
552 {
553         for (auto const & table : par.insetList()) {
554                 InsetArgument const * arg = table.inset->asInsetArgument();
555                 if (!arg)
556                         continue;
557                 if (arg->name().empty()) {
558                         LYXERR0("Error: Unnamed argument inset!");
559                         continue;
560                 }
561                 string const name = prefix.empty() ?
562                         arg->name() : split(arg->name(), ':');
563                 // why converting into an integer?
564                 unsigned int const nr = convert<unsigned int>(name);
565                 if (ilist.find(nr) == ilist.end())
566                         ilist[nr] = arg;
567                 Layout::LaTeXArgMap::const_iterator const lit =
568                         latexargs.find(arg->name());
569                 if (lit != latexargs.end()) {
570                         Layout::latexarg const & larg = lit->second;
571                         vector<string> req = getVectorFromString(larg.requires);
572                         move(req.begin(), req.end(), back_inserter(required));
573                 }
574         }
575 }
576
577 } // namespace
578
579
580 void latexArgInsets(Paragraph const & par, otexstream & os,
581                     OutputParams const & runparams,
582                     Layout::LaTeXArgMap const & latexargs,
583                     string const & prefix)
584 {
585         map<int, InsetArgument const *> ilist;
586         vector<string> required;
587         addArgInsets(par, prefix, latexargs, ilist, required);
588         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
589 }
590
591
592 void latexArgInsets(ParagraphList const & pars,
593                     ParagraphList::const_iterator pit,
594                     otexstream & os, OutputParams const & runparams,
595                     Layout::LaTeXArgMap const & latexargs,
596                     string const & prefix)
597 {
598         map<int, InsetArgument const *> ilist;
599         vector<string> required;
600
601         depth_type const current_depth = pit->params().depth();
602         Layout const current_layout = pit->layout();
603
604         // get the first paragraph in sequence with this layout and depth
605         pit_type offset = 0;
606         while (true) {
607                 if (lyx::prev(pit, offset) == pars.begin())
608                         break;
609                 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
610                 if (priorpit->layout() == current_layout
611                     && priorpit->params().depth() == current_depth)
612                         ++offset;
613                 else
614                         break;
615         }
616
617         ParagraphList::const_iterator spit = lyx::prev(pit, offset);
618
619         for (; spit != pars.end(); ++spit) {
620                 if (spit->layout() != current_layout ||
621                     spit->params().depth() < current_depth)
622                         break;
623                 if (spit->params().depth() > current_depth)
624                         continue;
625                 addArgInsets(*spit, prefix, latexargs, ilist, required);
626         }
627         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
628 }
629
630
631 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
632                              OutputParams const & runparams,
633                              Layout::LaTeXArgMap const & latexargs,
634                              string const & prefix)
635 {
636         map<int, InsetArgument const *> ilist;
637         vector<string> required;
638
639         for (Paragraph const & par : pars) {
640                 if (par.layout().hasArgs())
641                         // The InsetArguments inside this paragraph refer to this paragraph
642                         continue;
643                 addArgInsets(par, prefix, latexargs, ilist, required);
644         }
645         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
646 }
647
648
649 namespace {
650
651 // output the proper paragraph start according to latextype.
652 void parStartCommand(Paragraph const & par, otexstream & os,
653                      OutputParams const & runparams, Layout const & style)
654 {
655         switch (style.latextype) {
656         case LATEX_COMMAND:
657                 if (par.needsCProtection(runparams.moving_arg))
658                         os << "\\cprotect";
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         bool const localswitch = text.inset().forceLocalFontSwitch()
836                         || (using_begin_end && text.inset().forcePlainLayout());
837         if (localswitch) {
838                 lang_begin_command = use_polyglossia ?
839                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
840                 lang_end_command = "}";
841                 lang_command_termination.clear();
842         }
843         
844         bool const localswitch_needed = localswitch && par_lang != outer_lang;
845
846         // localswitches need to be closed and reopened at each par
847         if ((par_lang != prev_lang || localswitch_needed)
848              // check if we already put language command in TeXEnvironment()
849              && !(style.isEnvironment()
850                   && (pit == 0 || (priorpar->layout() != par.layout()
851                                    && priorpar->getDepth() <= par.getDepth())
852                       || priorpar->getDepth() < par.getDepth()))) {
853                 if (!localswitch
854                     && (!using_begin_end || langOpenedAtThisLevel(state))
855                     && !lang_end_command.empty()
856                     && prev_lang != outer_lang 
857                     && !prev_lang.empty()
858                     && (!using_begin_end || !style.isEnvironment())) {
859                         os << from_ascii(subst(lang_end_command,
860                                                "$$lang",
861                                                prev_lang))
862                            << lang_command_termination;
863                         if (using_begin_end)
864                                 popLanguageName();
865                 }
866
867                 // We need to open a new language if we couldn't close the previous
868                 // one (because there's no language_command_end); and even if we closed
869                 // the previous one, if the current language is different than the
870                 // outer_language (which is currently in effect once the previous one
871                 // is closed).
872                 if ((lang_end_command.empty() || par_lang != outer_lang
873                      || (!using_begin_end
874                          || (style.isEnvironment() && par_lang != prev_lang)))
875                         && !par_lang.empty()) {
876                         // If we're inside an inset, and that inset is within an \L or \R
877                         // (or equivalents), then within the inset, too, any opposite
878                         // language paragraph should appear within an \L or \R (in addition
879                         // to, outside of, the normal language switch commands).
880                         // This behavior is not correct for ArabTeX, though.
881                         if (!using_begin_end
882                             // not for ArabTeX
883                                 && par_language->lang() != "arabic_arabtex"
884                                 && outer_language->lang() != "arabic_arabtex"
885                             // are we in an inset?
886                             && runparams.local_font != 0
887                             // is the inset within an \L or \R?
888                             //
889                             // FIXME: currently, we don't check this; this means that
890                             // we'll have unnnecessary \L and \R commands, but that
891                             // doesn't seem to hurt (though latex will complain)
892                             //
893                             // is this paragraph in the opposite direction?
894                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
895                                 // FIXME: I don't have a working copy of the Arabi package, so
896                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
897                                 // or not...
898                                 if (par_language->lang() == "farsi")
899                                         os << "\\textFR{";
900                                 else if (outer_language->lang() == "farsi")
901                                         os << "\\textLR{";
902                                 else if (par_language->lang() == "arabic_arabi")
903                                         os << "\\textAR{";
904                                 else if (outer_language->lang() == "arabic_arabi")
905                                         os << "\\textLR{";
906                                 // remaining RTL languages currently is hebrew
907                                 else if (par_language->rightToLeft())
908                                         os << "\\R{";
909                                 else
910                                         os << "\\L{";
911                         }
912                         // With CJK, the CJK tag has to be closed first (see below)
913                         if (runparams.encoding->package() != Encoding::CJK
914                             && (par_lang != openLanguageName(state) || localswitch)
915                             && !par_lang.empty()) {
916                                 string bc = use_polyglossia ?
917                                           getPolyglossiaBegin(lang_begin_command, par_lang,
918                                                               par_language->polyglossiaOpts(),
919                                                               localswitch)
920                                           : subst(lang_begin_command, "$$lang", par_lang);
921                                 os << bc;
922                                 os << lang_command_termination;
923                                 if (using_begin_end)
924                                         pushLanguageName(par_lang, localswitch);
925                         }
926                 }
927         }
928
929         // Switch file encoding if necessary; no need to do this for "default"
930         // encoding, since this only affects the position of the outputted
931         // \inputencoding command; the encoding switch will occur when necessary
932         if (bparams.inputenc == "auto"
933                 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding  (see also switchEncoding())
934                 && runparams.encoding->package() != Encoding::none) {
935                 // Look ahead for future encoding changes.
936                 // We try to output them at the beginning of the paragraph,
937                 // since the \inputencoding command is not allowed e.g. in
938                 // sections. For this reason we only set runparams.moving_arg
939                 // after checking for the encoding change, otherwise the
940                 // change would be always avoided by switchEncoding().
941                 for (pos_type i = 0; i < par.size(); ++i) {
942                         char_type const c = par.getChar(i);
943                         Encoding const * const encoding =
944                                 par.getFontSettings(bparams, i).language()->encoding();
945                         if (encoding->package() != Encoding::CJK
946                                 && runparams.encoding->package() == Encoding::inputenc
947                                 && isASCII(c))
948                                 continue;
949                         if (par.isInset(i))
950                                 break;
951                         // All characters before c are in the ASCII range, and
952                         // c is non-ASCII (but no inset), so change the
953                         // encoding to that required by the language of c.
954                         // With CJK, only add switch if we have CJK content at the beginning
955                         // of the paragraph
956                         if (i != 0 && encoding->package() == Encoding::CJK)
957                                 continue;
958
959                         pair<bool, int> enc_switch = switchEncoding(os.os(),
960                                                 bparams, runparams, *encoding);
961                         // the following is necessary after a CJK environment in a multilingual
962                         // context (nesting issue).
963                         if (par_language->encoding()->package() == Encoding::CJK
964                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
965                                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
966                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
967                                 state->open_encoding_ = CJK;
968                         }
969                         if (encoding->package() != Encoding::none && enc_switch.first) {
970                                 if (enc_switch.second > 0) {
971                                         // the '%' is necessary to prevent unwanted whitespace
972                                         os << "%\n";
973                                 }
974                                 // With CJK, the CJK tag had to be closed first (see above)
975                                 if (runparams.encoding->package() == Encoding::CJK
976                                     && par_lang != openLanguageName(state)
977                                     && !par_lang.empty()) {
978                                         string bc = use_polyglossia ?
979                                                     getPolyglossiaBegin(lang_begin_command, par_lang,
980                                                                         par_language->polyglossiaOpts(),
981                                                                         localswitch)
982                                                     : subst(lang_begin_command, "$$lang", par_lang);
983                                         os << bc
984                                            << lang_command_termination;
985                                         if (using_begin_end)
986                                                 pushLanguageName(par_lang, localswitch);
987                                 }
988                                 runparams.encoding = encoding;
989                         }
990                         break;
991                 }
992         }
993
994         runparams.moving_arg |= style.needprotect;
995         Encoding const * const prev_encoding = runparams.encoding;
996
997         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
998         if (par.allowParagraphCustomization()) {
999                 if (par.params().startOfAppendix()) {
1000                         os << "\n\\appendix\n";
1001                 }
1002
1003                 // InTitle commands must use switches (not environments)
1004                 // inside the commands (see #9332)
1005                 if (style.intitle) {
1006                         if (!par.params().spacing().isDefault())
1007                         {
1008                                 if (runparams.moving_arg)
1009                                         os << "\\protect";
1010                                 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1011                         }
1012                 } else {
1013                         if (!par.params().spacing().isDefault()
1014                                 && (pit == 0 || !priorpar->hasSameLayout(par)))
1015                         {
1016                                 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1017                                     << '\n';
1018                         }
1019
1020                         if (style.isCommand()) {
1021                                 os << '\n';
1022                         }
1023                 }
1024         }
1025
1026         // For InTitle commands, we already started the command before
1027         // the language switch
1028         if (!intitle_command)
1029                 parStartCommand(par, os, runparams, style);
1030
1031         Font const outerfont = text.outerFont(pit);
1032
1033         // FIXME UNICODE
1034         os << from_utf8(everypar);
1035         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1036
1037         Font const font = par.empty()
1038                  ? par.getLayoutFont(bparams, outerfont)
1039                  : par.getFont(bparams, par.size() - 1, outerfont);
1040
1041         bool const is_command = style.isCommand();
1042
1043         // InTitle commands need to be closed after the language has been closed.
1044         if (!intitle_command) {
1045                 if (is_command) {
1046                         os << '}';
1047                         if (!style.postcommandargs().empty())
1048                                 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1049                         if (runparams.encoding != prev_encoding) {
1050                                 runparams.encoding = prev_encoding;
1051                                 os << setEncoding(prev_encoding->iconvName());
1052                         }
1053                 }
1054         }
1055
1056         bool pending_newline = false;
1057         bool unskip_newline = false;
1058         bool close_lang_switch = false;
1059         switch (style.latextype) {
1060         case LATEX_ITEM_ENVIRONMENT:
1061         case LATEX_LIST_ENVIRONMENT:
1062                 if ((nextpar && par_lang != nextpar_lang
1063                              && nextpar->getDepth() == par.getDepth())
1064                     || (atSameLastLangSwitchDepth(state) && nextpar
1065                             && nextpar->getDepth() < par.getDepth()))
1066                         close_lang_switch = using_begin_end;
1067                 if (nextpar && par.params().depth() < nextpar->params().depth())
1068                         pending_newline = true;
1069                 break;
1070         case LATEX_ENVIRONMENT: {
1071                 // if its the last paragraph of the current environment
1072                 // skip it otherwise fall through
1073                 if (nextpar
1074                     && ((nextpar->layout() != par.layout()
1075                            || nextpar->params().depth() != par.params().depth())
1076                         || (!using_begin_end || par_lang != nextpar_lang)))
1077                 {
1078                         close_lang_switch = using_begin_end;
1079                         break;
1080                 }
1081         }
1082         // possible
1083         // fall through
1084         default:
1085                 // we don't need it for the last paragraph and in InTitle commands!!!
1086                 if (nextpar && !intitle_command)
1087                         pending_newline = true;
1088         }
1089
1090         // InTitle commands use switches (not environments) for space settings
1091         if (par.allowParagraphCustomization() && !style.intitle) {
1092                 if (!par.params().spacing().isDefault()
1093                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1094                         if (pending_newline)
1095                                 os << '\n';
1096
1097                         string const endtag =
1098                                 par.params().spacing().writeEnvirEnd(useSetSpace);
1099                         if (prefixIs(endtag, "\\end{"))
1100                                 os << breakln;
1101
1102                         os << from_ascii(endtag);
1103                         pending_newline = true;
1104                 }
1105         }
1106
1107         // Closing the language is needed for the last paragraph in a given language
1108         // as well as for any InTitleCommand (since these set the language locally);
1109         // it is also needed if we're within an \L or \R that we may have opened above
1110         // (not necessarily in this paragraph) and are about to close.
1111         bool closing_rtl_ltr_environment = !using_begin_end
1112                 // not for ArabTeX
1113                 && (par_language->lang() != "arabic_arabtex"
1114                     && outer_language->lang() != "arabic_arabtex")
1115                 // have we opened an \L or \R environment?
1116                 && runparams.local_font != 0
1117                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1118                 // are we about to close the language?
1119                 &&((nextpar && par_lang != nextpar_lang)
1120                    || (runparams.isLastPar && par_lang != outer_lang));
1121
1122         if (localswitch_needed
1123             || (intitle_command && using_begin_end)
1124             || closing_rtl_ltr_environment
1125             || ((runparams.isLastPar || close_lang_switch)
1126                 && (par_lang != outer_lang || (using_begin_end
1127                                                 && style.isEnvironment()
1128                                                 && par_lang != nextpar_lang)))) {
1129                 // Since \selectlanguage write the language to the aux file,
1130                 // we need to reset the language at the end of footnote or
1131                 // float.
1132
1133                 if (!localswitch && (pending_newline || close_lang_switch))
1134                         os << '\n';
1135
1136                 // when the paragraph uses CJK, the language has to be closed earlier
1137                 if (font.language()->encoding()->package() != Encoding::CJK) {
1138                         if (lang_end_command.empty()) {
1139                                 // If this is a child, we should restore the
1140                                 // master language after the last paragraph.
1141                                 Language const * const current_language =
1142                                         (runparams.isLastPar && runparams.master_language)
1143                                                 ? runparams.master_language
1144                                                 : outer_language;
1145                                 string const current_lang = use_polyglossia
1146                                         ? getPolyglossiaEnvName(current_language)
1147                                         : current_language->babel();
1148                                 if (!current_lang.empty()
1149                                     && current_lang != openLanguageName(state)) {
1150                                         string bc = use_polyglossia ?
1151                                                     getPolyglossiaBegin(lang_begin_command, current_lang,
1152                                                                         current_language->polyglossiaOpts(),
1153                                                                         localswitch)
1154                                                   : subst(lang_begin_command, "$$lang", current_lang);
1155                                         os << bc;
1156                                         pending_newline = !localswitch;
1157                                         unskip_newline = !localswitch;
1158                                         if (using_begin_end)
1159                                                 pushLanguageName(current_lang, localswitch);
1160                                 }
1161                         } else if ((!using_begin_end ||
1162                                     langOpenedAtThisLevel(state)) &&
1163                                    !par_lang.empty()) {
1164                                 // If we are in an environment, we have to
1165                                 // close the "outer" language afterwards
1166                                 string const & cur_lang = openLanguageName(state);
1167                                 if (!style.isEnvironment()
1168                                     || (close_lang_switch
1169                                         && atSameLastLangSwitchDepth(state)
1170                                         && par_lang != outer_lang
1171                                         && (par_lang != cur_lang
1172                                             || (cur_lang != outer_lang
1173                                                 && nextpar
1174                                                 && style != nextpar->layout())))
1175                                     || (atSameLastLangSwitchDepth(state)
1176                                         && state->lang_switch_depth_.size()
1177                                         && cur_lang != par_lang))
1178                                 {
1179                                         if (using_begin_end && !localswitch)
1180                                                 os << breakln;
1181                                         os << from_ascii(subst(
1182                                                 lang_end_command,
1183                                                 "$$lang",
1184                                                 par_lang));
1185                                         pending_newline = !localswitch;
1186                                         unskip_newline = !localswitch;
1187                                         if (using_begin_end)
1188                                                 popLanguageName();
1189                                 }
1190                         }
1191                 }
1192         }
1193         if (closing_rtl_ltr_environment)
1194                 os << "}";
1195
1196         // InTitle commands need to be closed after the language has been closed.
1197         if (intitle_command) {
1198                 if (is_command) {
1199                         os << '}';
1200                         if (!style.postcommandargs().empty())
1201                                 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1202                         if (runparams.encoding != prev_encoding) {
1203                                 runparams.encoding = prev_encoding;
1204                                 os << setEncoding(prev_encoding->iconvName());
1205                         }
1206                 }
1207         }
1208
1209         bool const last_was_separator =
1210                 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1211
1212         if (pending_newline) {
1213                 if (unskip_newline)
1214                         // prevent unwanted whitespace
1215                         os << '%';
1216                 if (!os.afterParbreak() && !last_was_separator)
1217                         os << '\n';
1218         }
1219
1220         // if this is a CJK-paragraph and the next isn't, close CJK
1221         // also if the next paragraph is a multilingual environment (because of nesting)
1222         if (nextpar
1223                 && state->open_encoding_ == CJK
1224                 && (nextpar_language->encoding()->package() != Encoding::CJK
1225                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1226                 // inbetween environments, CJK has to be closed later (nesting!)
1227                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1228                 os << "\\end{CJK}\n";
1229                 state->open_encoding_ = none;
1230         }
1231
1232         // If this is the last paragraph, close the CJK environment
1233         // if necessary. If it's an environment, we'll have to \end that first.
1234         if (runparams.isLastPar && !style.isEnvironment()) {
1235                 switch (state->open_encoding_) {
1236                         case CJK: {
1237                                 // do nothing at the end of child documents
1238                                 if (maintext && buf.masterBuffer() != &buf)
1239                                         break;
1240                                 // end of main text
1241                                 if (maintext) {
1242                                         os << "\n\\end{CJK}\n";
1243                                 // end of an inset
1244                                 } else
1245                                         os << "\\end{CJK}";
1246                                 state->open_encoding_ = none;
1247                                 break;
1248                         }
1249                         case inputenc: {
1250                                 os << "\\egroup";
1251                                 state->open_encoding_ = none;
1252                                 break;
1253                         }
1254                         case none:
1255                         default:
1256                                 // do nothing
1257                                 break;
1258                 }
1259         }
1260
1261         // If this is the last paragraph, and a local_font was set upon entering
1262         // the inset, and we're using "auto" or "default" encoding, and not
1263         // compiling with XeTeX or LuaTeX, the encoding
1264         // should be set back to that local_font's encoding.
1265         if (runparams.isLastPar && runparams_in.local_font != 0
1266             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1267             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1268                 && !runparams.isFullUnicode()
1269            ) {
1270                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1271                 os << setEncoding(runparams_in.encoding->iconvName());
1272         }
1273         // Otherwise, the current encoding should be set for the next paragraph.
1274         else
1275                 runparams_in.encoding = runparams.encoding;
1276
1277
1278         // we don't need a newline for the last paragraph!!!
1279         // Note from JMarc: we will re-add a \n explicitly in
1280         // TeXEnvironment, because it is needed in this case
1281         if (nextpar && !os.afterParbreak() && !last_was_separator) {
1282                 // Make sure to start a new line
1283                 os << breakln;
1284                 Layout const & next_layout = nextpar->layout();
1285                 // A newline '\n' is always output before a command,
1286                 // so avoid doubling it.
1287                 if (!next_layout.isCommand()) {
1288                         // Here we now try to avoid spurious empty lines by
1289                         // outputting a paragraph break only if: (case 1) the
1290                         // paragraph style allows parbreaks and no \begin, \end
1291                         // or \item tags are going to follow (i.e., if the next
1292                         // isn't the first or the current isn't the last
1293                         // paragraph of an environment or itemize) and the
1294                         // depth and alignment of the following paragraph is
1295                         // unchanged, or (case 2) the following is a
1296                         // non-environment paragraph whose depth is increased
1297                         // but whose alignment is unchanged, or (case 3) the
1298                         // paragraph is not an environment and the next one is a
1299                         // non-itemize-like env at lower depth, or (case 4) the
1300                         // paragraph is a command not followed by an environment
1301                         // and the alignment of the current and next paragraph
1302                         // is unchanged, or (case 5) the current alignment is
1303                         // changed and a standard paragraph follows.
1304                         DocumentClass const & tclass = bparams.documentClass();
1305                         if ((style == next_layout
1306                              && !style.parbreak_is_newline
1307                              && !text.inset().getLayout().parbreakIsNewline()
1308                              && style.latextype != LATEX_ITEM_ENVIRONMENT
1309                              && style.latextype != LATEX_LIST_ENVIRONMENT
1310                              && style.align == par.getAlign()
1311                              && nextpar->getDepth() == par.getDepth()
1312                              && nextpar->getAlign() == par.getAlign())
1313                             || (!next_layout.isEnvironment()
1314                                 && nextpar->getDepth() > par.getDepth()
1315                                 && nextpar->getAlign() == par.getAlign())
1316                             || (!style.isEnvironment()
1317                                 && next_layout.latextype == LATEX_ENVIRONMENT
1318                                 && nextpar->getDepth() < par.getDepth())
1319                             || (style.isCommand()
1320                                 && !next_layout.isEnvironment()
1321                                 && style.align == par.getAlign()
1322                                 && next_layout.align == nextpar->getAlign())
1323                             || (style.align != par.getAlign()
1324                                 && tclass.isDefaultLayout(next_layout))) {
1325                                 os << '\n';
1326                         }
1327                 }
1328         }
1329
1330         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1331                 << &par << " next " << nextpar);
1332
1333         return;
1334 }
1335
1336
1337 // LaTeX all paragraphs
1338 void latexParagraphs(Buffer const & buf,
1339                      Text const & text,
1340                      otexstream & os,
1341                      OutputParams const & runparams,
1342                      string const & everypar)
1343 {
1344         LASSERT(runparams.par_begin <= runparams.par_end,
1345                 { os << "% LaTeX Output Error\n"; return; } );
1346
1347         BufferParams const & bparams = buf.params();
1348         BufferParams const & mparams = buf.masterParams();
1349
1350         bool const maintext = text.isMainText();
1351         bool const is_child = buf.masterBuffer() != &buf;
1352         bool const multibib_child = maintext && is_child
1353                         && mparams.multibib == "child";
1354
1355         if (multibib_child && mparams.useBiblatex())
1356                 os << "\\newrefsection";
1357         else if (multibib_child && mparams.useBibtopic()) {
1358                 os << "\\begin{btUnit}\n";
1359                 runparams.openbtUnit = true;
1360         }
1361
1362         // Open a CJK environment at the beginning of the main buffer
1363         // if the document's language is a CJK language
1364         // (but not in child documents)
1365         OutputState * state = getOutputState();
1366         if (maintext && !is_child
1367             && bparams.encoding().package() == Encoding::CJK) {
1368                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1369                 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1370                 state->open_encoding_ = CJK;
1371         }
1372         // if "auto begin" is switched off, explicitly switch the
1373         // language on at start
1374         string const mainlang = runparams.use_polyglossia
1375                 ? getPolyglossiaEnvName(bparams.language)
1376                 : bparams.language->babel();
1377         string const lang_begin_command = runparams.use_polyglossia ?
1378                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1379         string const lang_end_command = runparams.use_polyglossia ?
1380                 "\\end{$$lang}" : lyxrc.language_command_end;
1381         bool const using_begin_end = runparams.use_polyglossia ||
1382                                         !lang_end_command.empty();
1383
1384         if (maintext && !lyxrc.language_auto_begin &&
1385             !mainlang.empty()) {
1386                 // FIXME UNICODE
1387                 string bc = runparams.use_polyglossia ?
1388                             getPolyglossiaBegin(lang_begin_command, mainlang,
1389                                                 bparams.language->polyglossiaOpts())
1390                           : subst(lang_begin_command, "$$lang", mainlang);
1391                 os << bc;
1392                 os << '\n';
1393                 if (using_begin_end)
1394                         pushLanguageName(mainlang);
1395         }
1396
1397         ParagraphList const & paragraphs = text.paragraphs();
1398
1399         if (runparams.par_begin == runparams.par_end) {
1400                 // The full doc will be exported but it is easier to just rely on
1401                 // runparams range parameters that will be passed TeXEnvironment.
1402                 runparams.par_begin = 0;
1403                 runparams.par_end = paragraphs.size();
1404         }
1405
1406         pit_type pit = runparams.par_begin;
1407         // lastpit is for the language check after the loop.
1408         pit_type lastpit = pit;
1409         // variables used in the loop:
1410         bool was_title = false;
1411         bool already_title = false;
1412         DocumentClass const & tclass = bparams.documentClass();
1413
1414         // Did we already warn about inTitle layout mixing? (we only warn once)
1415         bool gave_layout_warning = false;
1416         for (; pit < runparams.par_end; ++pit) {
1417                 lastpit = pit;
1418                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1419
1420                 // FIXME This check should not be needed. We should
1421                 // perhaps issue an error if it is.
1422                 Layout const & layout = text.inset().forcePlainLayout() ?
1423                                 tclass.plainLayout() : par->layout();
1424
1425                 if (layout.intitle) {
1426                         if (already_title) {
1427                                 if (!gave_layout_warning && !runparams.dryrun) {
1428                                         gave_layout_warning = true;
1429                                         frontend::Alert::warning(_("Error in latexParagraphs"),
1430                                                         bformat(_("You are using at least one "
1431                                                           "layout (%1$s) intended for the title, "
1432                                                           "after using non-title layouts. This "
1433                                                           "could lead to missing or incorrect output."
1434                                                           ), layout.name()));
1435                                 }
1436                         } else if (!was_title) {
1437                                 was_title = true;
1438                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1439                                         os << "\\begin{"
1440                                                         << from_ascii(tclass.titlename())
1441                                                         << "}\n";
1442                                 }
1443                         }
1444                 } else if (was_title && !already_title && !layout.inpreamble) {
1445                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1446                                 os << "\\end{" << from_ascii(tclass.titlename())
1447                                                 << "}\n";
1448                         }
1449                         else {
1450                                 os << "\\" << from_ascii(tclass.titlename())
1451                                                 << "\n";
1452                         }
1453                         already_title = true;
1454                         was_title = false;
1455                 }
1456
1457                 if (layout.isCommand() && !layout.latexname().empty()
1458                     && layout.latexname() == bparams.multibib) {
1459                         if (runparams.openbtUnit)
1460                                 os << "\\end{btUnit}\n";
1461                         if (!bparams.useBiblatex()) {
1462                                 os << '\n' << "\\begin{btUnit}\n";
1463                                 runparams.openbtUnit = true;
1464                         }
1465                 }
1466
1467                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1468                         // This is a standard top level paragraph, TeX it and continue.
1469                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1470                         continue;
1471                 }
1472
1473                 TeXEnvironmentData const data =
1474                         prepareEnvironment(buf, text, par, os, runparams);
1475                 // pit can be changed in TeXEnvironment.
1476                 TeXEnvironment(buf, text, runparams, pit, os);
1477                 finishEnvironment(os, runparams, data);
1478         }
1479
1480         if (pit == runparams.par_end) {
1481                         // Make sure that the last paragraph is
1482                         // correctly terminated (because TeXOnePar does
1483                         // not add a \n in this case)
1484                         //os << '\n';
1485         }
1486
1487         // It might be that we only have a title in this document
1488         if (was_title && !already_title) {
1489                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1490                         os << "\\end{" << from_ascii(tclass.titlename())
1491                            << "}\n";
1492                 } else {
1493                         os << "\\" << from_ascii(tclass.titlename())
1494                            << "\n";
1495                 }
1496         }
1497
1498         if (maintext && !is_child && runparams.openbtUnit)
1499                 os << "\\end{btUnit}\n";
1500
1501         // if "auto end" is switched off, explicitly close the language at the end
1502         // but only if the last par is in a babel or polyglossia language
1503         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1504                 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1505                 os << from_utf8(subst(lang_end_command,
1506                                         "$$lang",
1507                                         mainlang))
1508                         << '\n';
1509                 if (using_begin_end)
1510                         popLanguageName();
1511         }
1512
1513         // If the last paragraph is an environment, we'll have to close
1514         // CJK at the very end to do proper nesting.
1515         if (maintext && !is_child && state->open_encoding_ == CJK) {
1516                 os << "\\end{CJK}\n";
1517                 state->open_encoding_ = none;
1518         }
1519         // Likewise for polyglossia or when using begin/end commands
1520         string const & cur_lang = openLanguageName(state);
1521         if (maintext && !is_child && !cur_lang.empty()) {
1522                 os << from_utf8(subst(lang_end_command,
1523                                         "$$lang",
1524                                         cur_lang))
1525                    << '\n';
1526                 if (using_begin_end)
1527                         popLanguageName();
1528         }
1529
1530         // reset inherited encoding
1531         if (state->cjk_inherited_ > 0) {
1532                 state->cjk_inherited_ -= 1;
1533                 if (state->cjk_inherited_ == 0)
1534                         state->open_encoding_ = CJK;
1535         }
1536
1537         if (multibib_child && mparams.useBibtopic()) {
1538                 os << "\\end{btUnit}\n";
1539                 runparams.openbtUnit = false;
1540         }
1541 }
1542
1543
1544 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1545                    OutputParams const & runparams, Encoding const & newEnc,
1546                    bool force, bool noswitchmacro)
1547 {
1548         // XeTeX/LuaTeX use only one encoding per document:
1549         // * with useNonTeXFonts: "utf8plain",
1550         // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1551         // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1552         if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1553                 return make_pair(false, 0);
1554
1555         Encoding const & oldEnc = *runparams.encoding;
1556         bool moving_arg = runparams.moving_arg;
1557         // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1558         bool const from_to_cjk =
1559                 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1560                 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1561         if (!force && !from_to_cjk
1562             && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1563                 return make_pair(false, 0);
1564
1565         // Do nothing if the encoding is unchanged.
1566         if (oldEnc.name() == newEnc.name())
1567                 return make_pair(false, 0);
1568
1569         // FIXME We ignore encoding switches from/to encodings that do
1570         // neither support the inputenc package nor the CJK package here.
1571         // This does of course only work in special cases (e.g. switch from
1572         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1573         // but it is the best we can do
1574         if (oldEnc.package() == Encoding::none
1575                 || newEnc.package() == Encoding::none)
1576                 return make_pair(false, 0);
1577
1578         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1579                 << oldEnc.name() << " to " << newEnc.name());
1580         os << setEncoding(newEnc.iconvName());
1581         if (bparams.inputenc == "default")
1582                 return make_pair(true, 0);
1583
1584         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1585         OutputState * state = getOutputState();
1586         switch (newEnc.package()) {
1587                 case Encoding::none:
1588                 case Encoding::japanese:
1589                         // shouldn't ever reach here, see above
1590                         return make_pair(true, 0);
1591                 case Encoding::inputenc: {
1592                         int count = inputenc_arg.length();
1593                         if (oldEnc.package() == Encoding::CJK &&
1594                             state->open_encoding_ == CJK) {
1595                                 os << "\\end{CJK}";
1596                                 state->open_encoding_ = none;
1597                                 count += 9;
1598                         }
1599                         else if (oldEnc.package() == Encoding::inputenc &&
1600                                  state->open_encoding_ == inputenc) {
1601                                 os << "\\egroup";
1602                                 state->open_encoding_ = none;
1603                                 count += 7;
1604                         }
1605                         if (runparams.local_font != 0
1606                             &&  oldEnc.package() == Encoding::CJK) {
1607                                 // within insets, \inputenc switches need
1608                                 // to be embraced within \bgroup...\egroup;
1609                                 // else CJK fails.
1610                                 os << "\\bgroup";
1611                                 count += 7;
1612                                 state->open_encoding_ = inputenc;
1613                         }
1614                         // with the japanese option, inputenc is omitted.
1615                         if (runparams.use_japanese || noswitchmacro)
1616                                 return make_pair(true, count);
1617                         os << "\\inputencoding{" << inputenc_arg << '}';
1618                         return make_pair(true, count + 16);
1619                 }
1620                 case Encoding::CJK: {
1621                         int count = inputenc_arg.length();
1622                         if (oldEnc.package() == Encoding::CJK &&
1623                             state->open_encoding_ == CJK) {
1624                                 os << "\\end{CJK}";
1625                                 count += 9;
1626                         }
1627                         if (oldEnc.package() == Encoding::inputenc &&
1628                             state->open_encoding_ == inputenc) {
1629                                 os << "\\egroup";
1630                                 count += 7;
1631                         }
1632                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1633                            << from_ascii(bparams.fonts_cjk) << "}";
1634                         state->open_encoding_ = CJK;
1635                         return make_pair(true, count + 15);
1636                 }
1637         }
1638         // Dead code to avoid a warning:
1639         return make_pair(true, 0);
1640
1641 }
1642
1643 } // namespace lyx