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.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
13 #include "output_latex.h"
15 #include "BiblioInfo.h"
17 #include "BufferParams.h"
20 #include "InsetList.h"
22 #include "LaTeXFeatures.h"
25 #include "OutputParams.h"
26 #include "Paragraph.h"
27 #include "ParagraphParameters.h"
28 #include "texstream.h"
29 #include "TextClass.h"
31 #include "insets/InsetBibitem.h"
32 #include "insets/InsetArgument.h"
34 #include "frontends/alert.h"
36 #include "support/lassert.h"
37 #include "support/convert.h"
38 #include "support/debug.h"
39 #include "support/lstrings.h"
40 #include "support/lyxalgo.h"
41 #include "support/textutils.h"
42 #include "support/gettext.h"
44 #include <QThreadStorage>
50 using namespace lyx::support;
66 OutputState() : open_encoding_(none), cjk_inherited_(0),
67 prev_env_language_(nullptr), nest_level_(0)
70 OpenEncoding open_encoding_;
72 Language const * prev_env_language_;
74 stack<int> lang_switch_depth_; // Both are always empty when
75 stack<string> open_polyglossia_lang_; // not using polyglossia
79 OutputState * getOutputState()
81 // FIXME An instance of OutputState should be kept around for each export
82 // instead of using local thread storage
83 static QThreadStorage<OutputState *> outputstate;
84 if (!outputstate.hasLocalData())
85 outputstate.setLocalData(new OutputState);
86 return outputstate.localData();
90 string const & openLanguageName(OutputState const * state)
92 // Return a reference to the last active language opened with
93 // polyglossia or when using begin/end commands. If none or when
94 // using babel with only a begin command, return a reference to
97 static string const empty;
99 return state->open_polyglossia_lang_.empty()
101 : state->open_polyglossia_lang_.top();
105 bool atSameLastLangSwitchDepth(OutputState const * state)
107 // Return true if the actual nest level is the same at which the
108 // language was switched when using polyglossia or begin/end
109 // commands. Instead, return always true when using babel with
110 // only a begin command.
112 return state->lang_switch_depth_.size() == 0
114 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
118 bool isLocalSwitch(OutputState const * state)
120 // Return true if the language was opened by a local command switch.
122 return state->lang_switch_depth_.size()
123 && state->lang_switch_depth_.top() < 0;
127 bool langOpenedAtThisLevel(OutputState const * state)
129 // Return true if the language was opened at the current nesting level.
131 return state->lang_switch_depth_.size()
132 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
136 string const getPolyglossiaEnvName(Language const * lang)
138 string result = lang->polyglossia();
139 if (result == "arabic")
140 // exceptional spelling; see polyglossia docs.
146 string const getPolyglossiaBegin(string const & lang_begin_command,
147 string const & lang, string const & opts,
148 bool const localswitch = false)
152 // we need to revert the upcasing done in getPolyglossiaEnvName()
153 // in case we have a local polyglossia command (\textarabic).
154 string language = localswitch ? ascii_lowercase(lang) : lang;
155 result = subst(lang_begin_command, "$$lang", language);
157 string options = opts.empty() ?
158 string() : "[" + opts + "]";
159 result = subst(result, "$$opts", options);
165 struct TeXEnvironmentData
168 Layout const * style;
169 Language const * par_language;
170 Encoding const * prev_encoding;
171 bool leftindent_open;
175 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
177 ParagraphList::const_iterator pit,
179 OutputParams const & runparams)
181 TeXEnvironmentData data;
183 BufferParams const & bparams = buf.params();
185 // FIXME This test should not be necessary.
186 // We should perhaps issue an error if it is.
187 Layout const & style = text.inset().forcePlainLayout() ?
188 bparams.documentClass().plainLayout() : pit->layout();
190 ParagraphList const & paragraphs = text.paragraphs();
191 ParagraphList::const_iterator const priorpit =
192 pit == paragraphs.begin() ? pit : prev(pit, 1);
194 OutputState * state = getOutputState();
195 bool const use_prev_env_language = state->prev_env_language_ != nullptr
196 && priorpit->layout().isEnvironment()
197 && (priorpit->getDepth() > pit->getDepth()
198 || (priorpit->getDepth() == pit->getDepth()
199 && priorpit->layout() != pit->layout()));
201 data.prev_encoding = runparams.encoding;
202 data.par_language = pit->getParLanguage(bparams);
203 Language const * const doc_language = bparams.language;
204 Language const * const prev_par_language =
205 (pit != paragraphs.begin())
206 ? (use_prev_env_language ? state->prev_env_language_
207 : priorpit->getParLanguage(bparams))
210 bool const use_polyglossia = runparams.use_polyglossia;
211 string const par_lang = use_polyglossia ?
212 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
213 string const prev_par_lang = use_polyglossia ?
214 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
215 string const doc_lang = use_polyglossia ?
216 getPolyglossiaEnvName(doc_language) : doc_language->babel();
217 string const lang_begin_command = use_polyglossia ?
218 "\\begin{$$lang}" : lyxrc.language_command_begin;
219 string const lang_end_command = use_polyglossia ?
220 "\\end{$$lang}" : lyxrc.language_command_end;
221 bool const using_begin_end = use_polyglossia ||
222 !lang_end_command.empty();
224 // For polyglossia, switch language outside of environment, if possible.
225 if (par_lang != prev_par_lang) {
226 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
227 !lang_end_command.empty() &&
228 prev_par_lang != doc_lang &&
229 !prev_par_lang.empty()) {
230 os << from_ascii(subst(
234 // the '%' is necessary to prevent unwanted whitespace
240 // If no language was explicitly opened and we are using
241 // polyglossia or begin/end commands, then the current
242 // language is the document language.
243 string const & cur_lang = using_begin_end
244 && state->lang_switch_depth_.size()
245 ? openLanguageName(state)
248 if ((lang_end_command.empty() ||
249 par_lang != doc_lang ||
250 par_lang != cur_lang) &&
252 string bc = use_polyglossia ?
253 getPolyglossiaBegin(lang_begin_command, par_lang,
254 data.par_language->polyglossiaOpts())
255 : subst(lang_begin_command, "$$lang", par_lang);
257 // the '%' is necessary to prevent unwanted whitespace
260 pushLanguageName(par_lang);
264 data.leftindent_open = false;
265 if (!pit->params().leftIndent().zero()) {
266 os << "\\begin{LyXParagraphLeftIndent}{"
267 << from_ascii(pit->params().leftIndent().asLatexString())
269 data.leftindent_open = true;
272 if (style.isEnvironment())
273 state->nest_level_ += 1;
275 if (style.isEnvironment() && !style.latexname().empty()) {
276 os << "\\begin{" << from_ascii(style.latexname()) << '}';
277 if (!style.latexargs().empty()) {
278 OutputParams rp = runparams;
279 rp.local_font = &pit->getFirstFontSettings(bparams);
280 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
282 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
284 << pit->params().labelWidthString()
286 } else if (style.labeltype == LABEL_BIBLIO) {
287 if (pit->params().labelWidthString().empty())
288 os << '{' << bibitemWidest(buf, runparams) << "}\n";
291 << pit->params().labelWidthString()
294 os << from_ascii(style.latexparam()) << '\n';
295 if (style.latextype == LATEX_BIB_ENVIRONMENT
296 || style.latextype == LATEX_ITEM_ENVIRONMENT
297 || style.latextype == LATEX_LIST_ENVIRONMENT) {
298 OutputParams rp = runparams;
299 rp.local_font = &pit->getFirstFontSettings(bparams);
300 latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
306 // in multilingual environments, the CJK tags have to be nested properly
307 data.cjk_nested = false;
308 if (!bparams.useNonTeXFonts
309 && (bparams.inputenc == "auto-legacy"
310 || bparams.inputenc == "auto-legacy-plain")
311 && data.par_language->encoding()->package() == Encoding::CJK
312 && state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
313 if (prev_par_language->encoding()->package() == Encoding::CJK) {
314 os << "\\begin{CJK}{"
315 << from_ascii(data.par_language->encoding()->latexName())
316 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
318 state->open_encoding_ = CJK;
319 data.cjk_nested = true;
325 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
326 TeXEnvironmentData const & data)
328 OutputState * state = getOutputState();
329 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
330 if (state->open_encoding_ == CJK && data.cjk_nested) {
331 // We need to close the encoding even if it does not change
332 // to do correct environment nesting
333 os << "\\end{CJK}\n";
334 state->open_encoding_ = none;
337 if (data.style->isEnvironment()) {
339 bool const using_begin_end =
340 runparams.use_polyglossia ||
341 !lyxrc.language_command_end.empty();
342 // Close any language opened at this nest level
343 if (using_begin_end) {
344 while (langOpenedAtThisLevel(state)) {
345 if (isLocalSwitch(state)) {
349 << openLanguageName(state)
355 state->nest_level_ -= 1;
356 string const & name = data.style->latexname();
358 os << "\\end{" << from_ascii(name) << "}\n";
359 state->prev_env_language_ = data.par_language;
360 if (runparams.encoding != data.prev_encoding) {
361 runparams.encoding = data.prev_encoding;
362 os << setEncoding(data.prev_encoding->iconvName());
366 if (data.leftindent_open) {
367 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
368 state->prev_env_language_ = data.par_language;
369 if (runparams.encoding != data.prev_encoding) {
370 runparams.encoding = data.prev_encoding;
371 os << setEncoding(data.prev_encoding->iconvName());
375 // Check whether we should output a blank line after the environment
376 if (!data.style->nextnoindent)
381 void TeXEnvironment(Buffer const & buf, Text const & text,
382 OutputParams const & runparams,
383 pit_type & pit, otexstream & os)
385 ParagraphList const & paragraphs = text.paragraphs();
386 ParagraphList::const_iterator ipar = paragraphs.constIterator(pit);
387 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
389 Layout const & current_layout = ipar->layout();
390 depth_type const current_depth = ipar->params().depth();
391 Length const & current_left_indent = ipar->params().leftIndent();
393 // This is for debugging purpose at the end.
394 pit_type const par_begin = pit;
395 for (; pit < runparams.par_end; ++pit) {
396 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
398 // check first if this is an higher depth paragraph.
399 bool go_out = (par->params().depth() < current_depth);
400 if (par->params().depth() == current_depth) {
401 // This environment is finished.
402 go_out |= (par->layout() != current_layout);
403 go_out |= (par->params().leftIndent() != current_left_indent);
406 // nothing to do here, restore pit and go out.
411 if (par->layout() == current_layout
412 && par->params().depth() == current_depth
413 && par->params().leftIndent() == current_left_indent) {
414 // We are still in the same environment so TeXOnePar and continue;
415 TeXOnePar(buf, text, pit, os, runparams);
419 // We are now in a deeper environment.
420 // Either par->layout() != current_layout
421 // Or par->params().depth() > current_depth
422 // Or par->params().leftIndent() != current_left_indent)
424 // FIXME This test should not be necessary.
425 // We should perhaps issue an error if it is.
426 bool const force_plain_layout = text.inset().forcePlainLayout();
427 Layout const & style = force_plain_layout
428 ? buf.params().documentClass().plainLayout()
431 if (!style.isEnvironment()) {
432 // This is a standard paragraph, no need to call TeXEnvironment.
433 TeXOnePar(buf, text, pit, os, runparams);
437 // This is a new environment.
438 TeXEnvironmentData const data =
439 prepareEnvironment(buf, text, par, os, runparams);
440 // Recursive call to TeXEnvironment!
441 TeXEnvironment(buf, text, runparams, pit, os);
442 finishEnvironment(os, runparams, data);
445 if (pit != runparams.par_end)
446 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
450 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
451 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
453 unsigned int const argnr = latexargs.size();
457 // Default and preset args are always output, so if they require
458 // other arguments, consider this.
459 for (auto const & larg : latexargs) {
460 Layout::latexarg const & arg = larg.second;
461 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
462 vector<string> req = getVectorFromString(arg.requires);
463 required.insert(required.end(), req.begin(), req.end());
467 for (unsigned int i = 1; i <= argnr; ++i) {
468 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
469 bool inserted = false;
470 if (lit != ilist.end()) {
471 InsetArgument const * ins = (*lit).second;
473 Layout::LaTeXArgMap::const_iterator const lait =
474 latexargs.find(ins->name());
475 if (lait != latexargs.end()) {
476 Layout::latexarg arg = (*lait).second;
480 ldelim = arg.mandatory ?
481 from_ascii("{") : from_ascii("[");
482 rdelim = arg.mandatory ?
483 from_ascii("}") : from_ascii("]");
485 if (!arg.ldelim.empty())
487 if (!arg.rdelim.empty())
489 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
490 if (prefix == "listpreamble:")
497 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
498 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
499 for (; lait != laend; ++lait) {
500 string const name = prefix + convert<string>(i);
501 if ((*lait).first == name) {
502 Layout::latexarg arg = (*lait).second;
503 docstring preset = arg.presetarg;
504 if (!arg.defaultarg.empty()) {
507 preset += arg.defaultarg;
510 docstring ldelim = arg.ldelim.empty() ?
511 from_ascii("{") : arg.ldelim;
512 docstring rdelim = arg.rdelim.empty() ?
513 from_ascii("}") : arg.rdelim;
514 os << ldelim << preset << rdelim;
515 } else if (!preset.empty()) {
516 docstring ldelim = arg.ldelim.empty() ?
517 from_ascii("[") : arg.ldelim;
518 docstring rdelim = arg.rdelim.empty() ?
519 from_ascii("]") : arg.rdelim;
520 os << ldelim << preset << rdelim;
521 } else if (find(required.begin(), required.end(),
522 (*lait).first) != required.end()) {
523 docstring ldelim = arg.ldelim.empty() ?
524 from_ascii("[") : arg.ldelim;
525 docstring rdelim = arg.rdelim.empty() ?
526 from_ascii("]") : arg.rdelim;
527 os << ldelim << rdelim;
534 if (runparams.for_search) {
535 // Mark end of arguments for findadv() only
536 os << "\\endarguments{}";
544 void pushLanguageName(string const & lang_name, bool localswitch)
546 OutputState * state = getOutputState();
548 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
549 state->lang_switch_depth_.push(nest_level);
550 state->open_polyglossia_lang_.push(lang_name);
554 void popLanguageName()
556 OutputState * state = getOutputState();
558 state->lang_switch_depth_.pop();
559 state->open_polyglossia_lang_.pop();
563 string const & openLanguageName()
565 OutputState * state = getOutputState();
567 return openLanguageName(state);
573 void addArgInsets(Paragraph const & par, string const & prefix,
574 Layout::LaTeXArgMap const & latexargs,
575 map<int, InsetArgument const *> & ilist,
576 vector<string> & required)
578 for (auto const & table : par.insetList()) {
579 InsetArgument const * arg = table.inset->asInsetArgument();
582 if (arg->name().empty()) {
583 LYXERR0("Error: Unnamed argument inset!");
586 string const name = prefix.empty() ?
587 arg->name() : split(arg->name(), ':');
588 // why converting into an integer?
589 unsigned int const nr = convert<unsigned int>(name);
590 if (ilist.find(nr) == ilist.end())
592 Layout::LaTeXArgMap::const_iterator const lit =
593 latexargs.find(arg->name());
594 if (lit != latexargs.end()) {
595 Layout::latexarg const & larg = lit->second;
596 vector<string> req = getVectorFromString(larg.requires);
597 move(req.begin(), req.end(), back_inserter(required));
605 void latexArgInsets(Paragraph const & par, otexstream & os,
606 OutputParams const & runparams,
607 Layout::LaTeXArgMap const & latexargs,
608 string const & prefix)
610 map<int, InsetArgument const *> ilist;
611 vector<string> required;
612 addArgInsets(par, prefix, latexargs, ilist, required);
613 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
617 void latexArgInsets(ParagraphList const & pars,
618 ParagraphList::const_iterator pit,
619 otexstream & os, OutputParams const & runparams,
620 Layout::LaTeXArgMap const & latexargs,
621 string const & prefix)
623 map<int, InsetArgument const *> ilist;
624 vector<string> required;
626 depth_type const current_depth = pit->params().depth();
627 Layout const current_layout = pit->layout();
629 // get the first paragraph in sequence with this layout and depth
632 if (lyx::prev(pit, offset) == pars.begin())
634 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
635 if (priorpit->layout() == current_layout
636 && priorpit->params().depth() == current_depth)
642 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
644 for (; spit != pars.end(); ++spit) {
645 if (spit->layout() != current_layout ||
646 spit->params().depth() < current_depth)
648 if (spit->params().depth() > current_depth)
650 addArgInsets(*spit, prefix, latexargs, ilist, required);
652 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
656 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
657 OutputParams const & runparams,
658 Layout::LaTeXArgMap const & latexargs,
659 string const & prefix)
661 map<int, InsetArgument const *> ilist;
662 vector<string> required;
664 for (Paragraph const & par : pars) {
665 if (par.layout().hasArgs())
666 // The InsetArguments inside this paragraph refer to this paragraph
668 addArgInsets(par, prefix, latexargs, ilist, required);
670 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
676 // output the proper paragraph start according to latextype.
677 void parStartCommand(Paragraph const & par, otexstream & os,
678 OutputParams const & runparams, Layout const & style)
680 switch (style.latextype) {
682 if (par.needsCProtection(runparams.moving_arg)) {
683 if (contains(runparams.active_chars, '^'))
684 // cprotect relies on ^ being on catcode 7
685 os << "\\begingroup\\catcode`\\^=7";
688 os << '\\' << from_ascii(style.latexname());
691 if (!style.latexargs().empty())
692 latexArgInsets(par, os, runparams, style.latexargs());
693 os << from_ascii(style.latexparam());
695 case LATEX_ITEM_ENVIRONMENT:
696 case LATEX_LIST_ENVIRONMENT:
697 if (runparams.for_search) {
698 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
701 os << "\\" + style.itemcommand();
703 if (!style.itemargs().empty())
704 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
708 case LATEX_ENVIRONMENT:
709 if (runparams.for_search) {
710 os << "\\latexenvironment{" << style.latexname() << "}{";
713 case LATEX_BIB_ENVIRONMENT:
714 // ignore this, the inset will write itself
723 // FIXME: this should be anonymous
724 void TeXOnePar(Buffer const & buf,
728 OutputParams const & runparams_in,
729 string const & everypar,
730 int start_pos, int end_pos,
733 BufferParams const & bparams = runparams_in.is_child
734 ? buf.masterParams() : buf.params();
735 ParagraphList const & paragraphs = text.paragraphs();
736 Paragraph const & par = paragraphs.at(pit);
737 // FIXME This check should not really be needed.
738 // Perhaps we should issue an error if it is.
739 Layout const & style = text.inset().forcePlainLayout() ?
740 bparams.documentClass().plainLayout() : par.layout();
742 if (style.inpreamble && !force)
745 // Do not output empty commands if the whole paragraph has
746 // been deleted with ct and changes are not output.
747 if (!runparams_in.for_search && style.latextype != LATEX_ENVIRONMENT
748 && par.size() > 0 && par.isDeleted(0, par.size()) && !bparams.output_changes)
751 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
754 OutputParams runparams = runparams_in;
755 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
756 // We reinitialize par begin and end to be on the safe side
757 // with embedded inset as we don't know if they set those
759 runparams.par_begin = 0;
760 runparams.par_end = 0;
762 bool const maintext = text.isMainText();
763 // we are at the beginning of an inset and CJK is already open;
764 // we count inheritation levels to get the inset nesting right.
765 OutputState * state = getOutputState();
766 if (pit == 0 && !maintext
767 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
768 state->cjk_inherited_ += 1;
769 state->open_encoding_ = none;
772 if (text.inset().isPassThru()) {
773 Font const outerfont = text.outerFont(pit);
775 // No newline before first paragraph in this lyxtext
776 if (pit > 0 && !text.inset().getLayout().parbreakIgnored()) {
778 if (!text.inset().getLayout().parbreakIsNewline())
782 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
786 Paragraph const * nextpar = runparams.isLastPar
787 ? nullptr : ¶graphs.at(pit + 1);
789 bool const intitle_command = style.intitle && style.isCommand();
790 // Intitle commands switch languages locally, thus increase
791 // language nesting level
793 state->nest_level_ += 1;
795 if (style.pass_thru) {
796 Font const outerfont = text.outerFont(pit);
797 parStartCommand(par, os, runparams, style);
798 if (style.isCommand() && style.needprotect)
799 // Due to the moving argument, some fragile
800 // commands (labels, index entries)
801 // are output after this command (#2154)
802 runparams.postpone_fragile_stuff = true;
806 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
808 // I did not create a parEndCommand for this minuscule
809 // task because in the other user of parStartCommand
810 // the code is different (JMarc)
811 if (style.isCommand()) {
813 if (par.needsCProtection(runparams.moving_arg)
814 && contains(runparams.active_chars, '^'))
820 if (!style.parbreak_is_newline) {
822 } else if (nextpar && !style.isEnvironment()) {
823 Layout const nextstyle = text.inset().forcePlainLayout()
824 ? bparams.documentClass().plainLayout()
826 if (nextstyle.name() != style.name())
833 // This paragraph's language
834 Language const * const par_language = par.getParLanguage(bparams);
835 Language const * const nextpar_language = nextpar ?
836 nextpar->getParLanguage(bparams) : nullptr;
837 // The document's language
838 Language const * const doc_language = bparams.language;
839 // The language that was in effect when the environment this paragraph is
840 // inside of was opened
841 Language const * const outer_language =
842 (runparams.local_font != nullptr) ?
843 runparams.local_font->language() : doc_language;
845 Paragraph const * priorpar = (pit == 0) ? nullptr : ¶graphs.at(pit - 1);
847 // The previous language that was in effect is the language of the
848 // previous paragraph, unless the previous paragraph is inside an
849 // environment with nesting depth greater than (or equal to, but with
850 // a different layout) the current one. If there is no previous
851 // paragraph, the previous language is the outer language.
852 // Note further that we take the outer language also if the prior par
853 // is PassThru, since in that case it has latex_language, and all secondary
854 // languages have been closed (#10793).
855 bool const use_prev_env_language = state->prev_env_language_ != nullptr
857 && priorpar->layout().isEnvironment()
858 && (priorpar->getDepth() > par.getDepth()
859 || (priorpar->getDepth() == par.getDepth()
860 && priorpar->layout() != par.layout()));
862 // We need to ignore previous intitle commands since languages
863 // are switched locally there (# 11514)
864 // There might be paragraphs before the title, so we check this.
865 Paragraph * prior_nontitle_par = nullptr;
866 if (!intitle_command) {
870 Paragraph const * tmppar = ¶graphs.at(ppit);
871 if (tmppar->layout().intitle && tmppar->layout().isCommand())
873 prior_nontitle_par = const_cast<Paragraph*>(tmppar);
877 Language const * const prev_language =
878 runparams_in.for_search
879 ? languages.getLanguage("ignore")
880 : (prior_nontitle_par && !prior_nontitle_par->isPassThru())
881 ? (use_prev_env_language
882 ? state->prev_env_language_
883 : prior_nontitle_par->getParLanguage(bparams))
886 bool const use_polyglossia = runparams.use_polyglossia;
887 string const par_lang = use_polyglossia ?
888 getPolyglossiaEnvName(par_language): par_language->babel();
889 string const prev_lang = use_polyglossia ?
890 getPolyglossiaEnvName(prev_language) : prev_language->babel();
891 string const outer_lang = use_polyglossia ?
892 getPolyglossiaEnvName(outer_language) : outer_language->babel();
893 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
894 getPolyglossiaEnvName(nextpar_language) :
895 nextpar_language->babel()) : string();
896 string lang_begin_command = use_polyglossia ?
897 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
898 string lang_end_command = use_polyglossia ?
899 "\\end{$$lang}" : lyxrc.language_command_end;
900 // the '%' is necessary to prevent unwanted whitespace
901 string lang_command_termination = "%\n";
902 bool const using_begin_end = use_polyglossia ||
903 !lang_end_command.empty();
905 // For InTitle commands, we need to switch the language inside the command
906 // (see #10849); thus open the command here.
907 if (intitle_command) {
908 parStartCommand(par, os, runparams, style);
909 if (style.isCommand() && style.needprotect)
910 // Due to the moving argument, some fragile
911 // commands (labels, index entries)
912 // are output after this command (#2154)
913 runparams.postpone_fragile_stuff = true;
917 // In some insets (such as Arguments), we cannot use \selectlanguage.
918 // Also, if an RTL language is set via environment in polyglossia,
919 // only a nested \\text<lang> command will reset the direction for LTR
920 // languages (see # 10111).
921 bool const in_polyglossia_rtl_env =
923 && runparams.local_font != nullptr
924 && outer_language->rightToLeft()
925 && !par_language->rightToLeft();
926 bool const localswitch =
927 (runparams_in.for_search
928 || text.inset().forceLocalFontSwitch()
929 || (using_begin_end && text.inset().forcePlainLayout())
930 || in_polyglossia_rtl_env)
931 && !text.inset().forceParDirectionSwitch();
933 lang_begin_command = use_polyglossia ?
934 "\\text$$lang$$opts{" : lyxrc.language_command_local;
935 lang_end_command = "}";
936 lang_command_termination.clear();
939 bool const localswitch_needed = localswitch && par_lang != outer_lang;
941 // localswitches need to be closed and reopened at each par
942 if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
943 // check if we already put language command in TeXEnvironment()
944 && !(style.isEnvironment()
945 && (pit == 0 || (priorpar->layout() != par.layout()
946 && priorpar->getDepth() <= par.getDepth())
947 || priorpar->getDepth() < par.getDepth())))) {
949 && (!using_begin_end || langOpenedAtThisLevel(state))
950 && !lang_end_command.empty()
951 && prev_lang != outer_lang
952 && !prev_lang.empty()
953 && (!using_begin_end || !style.isEnvironment())) {
954 os << from_ascii(subst(lang_end_command,
957 << lang_command_termination;
962 // We need to open a new language if we couldn't close the previous
963 // one (because there's no language_command_end); and even if we closed
964 // the previous one, if the current language is different than the
965 // outer_language (which is currently in effect once the previous one
967 if ((lang_end_command.empty() || par_lang != outer_lang
969 || (style.isEnvironment() && par_lang != prev_lang)))
970 && !par_lang.empty()) {
971 // If we're inside an inset, and that inset is within an \L or \R
972 // (or equivalents), then within the inset, too, any opposite
973 // language paragraph should appear within an \L or \R (in addition
974 // to, outside of, the normal language switch commands).
975 // This behavior is not correct for ArabTeX, though.
978 && par_language->lang() != "arabic_arabtex"
979 && outer_language->lang() != "arabic_arabtex"
980 // are we in an inset?
981 && runparams.local_font != nullptr
982 // is the inset within an \L or \R?
984 // FIXME: currently, we don't check this; this means that
985 // we'll have unnnecessary \L and \R commands, but that
986 // doesn't seem to hurt (though latex will complain)
988 // is this paragraph in the opposite direction?
989 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
990 // FIXME: I don't have a working copy of the Arabi package, so
991 // I'm not sure if the farsi and arabic_arabi stuff is correct
993 if (par_language->lang() == "farsi")
995 else if (outer_language->lang() == "farsi")
997 else if (par_language->lang() == "arabic_arabi")
999 else if (outer_language->lang() == "arabic_arabi")
1001 // remaining RTL languages currently is hebrew
1002 else if (par_language->rightToLeft())
1007 // With CJK, the CJK tag has to be closed first (see below)
1008 if ((runparams.encoding->package() != Encoding::CJK
1009 || bparams.useNonTeXFonts
1010 || runparams.for_search)
1011 && (par_lang != openLanguageName(state) || localswitch || intitle_command)
1012 && !par_lang.empty()) {
1013 string bc = use_polyglossia ?
1014 getPolyglossiaBegin(lang_begin_command, par_lang,
1015 par_language->polyglossiaOpts(),
1017 : subst(lang_begin_command, "$$lang", par_lang);
1019 os << lang_command_termination;
1020 if (using_begin_end)
1021 pushLanguageName(par_lang, localswitch);
1026 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
1027 // encoding, since this only affects the position of the outputted
1028 // \inputencoding command; the encoding switch will occur when necessary
1029 if (bparams.inputenc == "auto-legacy"
1030 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
1031 && runparams.encoding->package() != Encoding::japanese
1032 && runparams.encoding->package() != Encoding::none) {
1033 // Look ahead for future encoding changes.
1034 // We try to output them at the beginning of the paragraph,
1035 // since the \inputencoding command is not allowed e.g. in
1036 // sections. For this reason we only set runparams.moving_arg
1037 // after checking for the encoding change, otherwise the
1038 // change would be always avoided by switchEncoding().
1039 for (pos_type i = 0; i < par.size(); ++i) {
1040 char_type const c = par.getChar(i);
1041 Encoding const * const encoding =
1042 par.getFontSettings(bparams, i).language()->encoding();
1043 if (encoding->package() != Encoding::CJK
1044 && runparams.encoding->package() == Encoding::inputenc
1049 // All characters before c are in the ASCII range, and
1050 // c is non-ASCII (but no inset), so change the
1051 // encoding to that required by the language of c.
1052 // With CJK, only add switch if we have CJK content at the beginning
1054 if (i != 0 && encoding->package() == Encoding::CJK)
1057 pair<bool, int> enc_switch = switchEncoding(os.os(),
1058 bparams, runparams, *encoding);
1059 // the following is necessary after a CJK environment in a multilingual
1060 // context (nesting issue).
1061 if (par_language->encoding()->package() == Encoding::CJK
1062 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1063 os << "\\begin{CJK}{"
1064 << from_ascii(par_language->encoding()->latexName())
1065 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1066 state->open_encoding_ = CJK;
1068 if (encoding->package() != Encoding::none && enc_switch.first) {
1069 if (enc_switch.second > 0) {
1070 // the '%' is necessary to prevent unwanted whitespace
1073 // With CJK, the CJK tag had to be closed first (see above)
1074 if (runparams.encoding->package() == Encoding::CJK
1075 && par_lang != openLanguageName(state)
1076 && !par_lang.empty()) {
1077 os << subst(lang_begin_command, "$$lang", par_lang)
1078 << lang_command_termination;
1079 if (using_begin_end)
1080 pushLanguageName(par_lang, localswitch);
1082 runparams.encoding = encoding;
1088 runparams.moving_arg |= style.needprotect;
1089 if (style.needmboxprotect)
1090 ++runparams.inulemcmd;
1091 Encoding const * const prev_encoding = runparams.encoding;
1093 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1094 if (par.allowParagraphCustomization()) {
1095 if (par.params().startOfAppendix()) {
1096 os << "\n\\appendix\n";
1099 // InTitle commands must use switches (not environments)
1100 // inside the commands (see #9332)
1101 if (style.intitle) {
1102 if (!par.params().spacing().isDefault())
1104 if (runparams.moving_arg)
1106 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1109 if (!par.params().spacing().isDefault()
1110 && (pit == 0 || !priorpar->hasSameLayout(par)))
1112 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1116 if (style.isCommand()) {
1122 // For InTitle commands, we already started the command before
1123 // the language switch
1124 if (!intitle_command) {
1125 parStartCommand(par, os, runparams, style);
1126 if (style.isCommand() && style.needprotect)
1127 // Due to the moving argument, some fragile
1128 // commands (labels, index entries)
1129 // are output after this command (#2154)
1130 runparams.postpone_fragile_stuff = true;
1133 Font const outerfont = text.outerFont(pit);
1136 os << from_utf8(everypar);
1137 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1139 Font const font = par.empty()
1140 ? par.getLayoutFont(bparams, outerfont)
1141 : par.getFont(bparams, par.size() - 1, outerfont);
1143 bool const is_command = style.isCommand();
1145 // InTitle commands need to be closed after the language has been closed.
1146 if (!intitle_command) {
1149 if (!style.postcommandargs().empty())
1150 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1151 if (!runparams.post_macro.empty()) {
1152 // Output the stored fragile commands (labels, indices etc.)
1153 // that need to be output after the command with moving argument.
1154 os << runparams.post_macro;
1155 runparams.post_macro.clear();
1157 if (par.needsCProtection(runparams.moving_arg)
1158 && contains(runparams.active_chars, '^'))
1160 if (runparams.encoding != prev_encoding) {
1161 runparams.encoding = prev_encoding;
1162 os << setEncoding(prev_encoding->iconvName());
1167 bool pending_newline = false;
1168 bool unskip_newline = false;
1169 bool close_lang_switch = false;
1170 switch (style.latextype) {
1171 case LATEX_ITEM_ENVIRONMENT:
1172 case LATEX_LIST_ENVIRONMENT:
1173 if ((nextpar && par_lang != nextpar_lang
1174 && nextpar->getDepth() == par.getDepth())
1175 || (atSameLastLangSwitchDepth(state) && nextpar
1176 && nextpar->getDepth() < par.getDepth()))
1177 close_lang_switch = using_begin_end;
1178 if (nextpar && par.params().depth() < nextpar->params().depth())
1179 pending_newline = !text.inset().getLayout().parbreakIgnored();
1181 case LATEX_ENVIRONMENT: {
1182 // if it's the last paragraph of the current environment
1183 // skip it otherwise fall through
1185 && ((nextpar->layout() != par.layout()
1186 || nextpar->params().depth() != par.params().depth())
1187 || (!using_begin_end || par_lang != nextpar_lang)))
1189 close_lang_switch = using_begin_end;
1196 // we don't need it for the last paragraph and in InTitle commands!!!
1197 if (nextpar && !intitle_command)
1198 pending_newline = !text.inset().getLayout().parbreakIgnored();
1201 // InTitle commands use switches (not environments) for space settings
1202 if (par.allowParagraphCustomization() && !style.intitle) {
1203 if (!par.params().spacing().isDefault()
1204 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1205 if (pending_newline)
1208 string const endtag =
1209 par.params().spacing().writeEnvirEnd(useSetSpace);
1210 if (prefixIs(endtag, "\\end{"))
1213 os << from_ascii(endtag);
1214 pending_newline = true;
1218 // Closing the language is needed for the last paragraph in a given language
1219 // as well as for any InTitleCommand (since these set the language locally);
1220 // it is also needed if we're within an \L or \R that we may have opened above
1221 // (not necessarily in this paragraph) and are about to close.
1222 bool closing_rtl_ltr_environment = !using_begin_end
1224 && (par_language->lang() != "arabic_arabtex"
1225 && outer_language->lang() != "arabic_arabtex")
1226 // have we opened an \L or \R environment?
1227 && runparams.local_font != nullptr
1228 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1229 // are we about to close the language?
1230 &&((nextpar && par_lang != nextpar_lang)
1231 || (runparams.isLastPar && par_lang != outer_lang));
1233 if (localswitch_needed
1234 || (intitle_command && using_begin_end)
1235 || closing_rtl_ltr_environment
1236 || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1237 && (par_lang != outer_lang || (using_begin_end
1238 && style.isEnvironment()
1239 && par_lang != nextpar_lang)))) {
1240 // Since \selectlanguage write the language to the aux file,
1241 // we need to reset the language at the end of footnote or
1244 if (!localswitch && (pending_newline || close_lang_switch))
1247 // when the paragraph uses CJK, the language has to be closed earlier
1248 if ((font.language()->encoding()->package() != Encoding::CJK)
1249 || bparams.useNonTeXFonts
1250 || runparams_in.for_search) {
1251 if (lang_end_command.empty()) {
1252 // If this is a child, we should restore the
1253 // master language after the last paragraph.
1254 Language const * const current_language =
1255 (runparams.isLastPar && runparams.master_language)
1256 ? runparams.master_language
1258 string const current_lang = use_polyglossia
1259 ? getPolyglossiaEnvName(current_language)
1260 : current_language->babel();
1261 if (!current_lang.empty()
1262 && current_lang != openLanguageName(state)) {
1263 string bc = use_polyglossia ?
1264 getPolyglossiaBegin(lang_begin_command, current_lang,
1265 current_language->polyglossiaOpts(),
1267 : subst(lang_begin_command, "$$lang", current_lang);
1269 pending_newline = !localswitch
1270 && !text.inset().getLayout().parbreakIgnored();
1271 unskip_newline = !localswitch;
1272 if (using_begin_end)
1273 pushLanguageName(current_lang, localswitch);
1275 } else if ((!using_begin_end ||
1276 langOpenedAtThisLevel(state)) &&
1277 !par_lang.empty()) {
1278 // If we are in an environment, we have to
1279 // close the "outer" language afterwards
1280 string const & cur_lang = openLanguageName(state);
1281 if (!style.isEnvironment()
1282 || (close_lang_switch
1283 && atSameLastLangSwitchDepth(state)
1284 && par_lang != outer_lang
1285 && (par_lang != cur_lang
1286 || (cur_lang != outer_lang
1288 && style != nextpar->layout())))
1289 || (atSameLastLangSwitchDepth(state)
1290 && state->lang_switch_depth_.size()
1291 && cur_lang != par_lang)
1292 || in_polyglossia_rtl_env)
1294 if (using_begin_end && !localswitch)
1296 os << from_ascii(subst(
1300 pending_newline = !localswitch
1301 && !text.inset().getLayout().parbreakIgnored();
1302 unskip_newline = !localswitch;
1303 if (using_begin_end)
1309 if (closing_rtl_ltr_environment)
1312 // InTitle commands need to be closed after the language has been closed.
1313 if (intitle_command) {
1315 if (!style.postcommandargs().empty())
1316 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1317 if (!runparams.post_macro.empty()) {
1318 // Output the stored fragile commands (labels, indices etc.)
1319 // that need to be output after the command with moving argument.
1320 os << runparams.post_macro;
1321 runparams.post_macro.clear();
1323 if (par.needsCProtection(runparams.moving_arg)
1324 && contains(runparams.active_chars, '^'))
1326 if (runparams.encoding != prev_encoding) {
1327 runparams.encoding = prev_encoding;
1328 os << setEncoding(prev_encoding->iconvName());
1332 bool const last_was_separator =
1333 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1335 if (pending_newline) {
1337 // prevent unwanted whitespace
1339 if (!os.afterParbreak() && !last_was_separator)
1343 // if this is a CJK-paragraph and the next isn't, close CJK
1344 // also if the next paragraph is a multilingual environment (because of nesting)
1345 if (nextpar && state->open_encoding_ == CJK
1346 && bparams.encoding().iconvName() != "UTF-8"
1347 && bparams.encoding().package() != Encoding::CJK
1348 && (nextpar_language->encoding()->package() != Encoding::CJK
1349 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1350 // inbetween environments, CJK has to be closed later (nesting!)
1351 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1352 os << "\\end{CJK}\n";
1353 state->open_encoding_ = none;
1356 // If this is the last paragraph, close the CJK environment
1357 // if necessary. If it's an environment or nested in an environment,
1358 // we'll have to \end that first.
1359 if (runparams.isLastPar && !style.isEnvironment()
1360 && par.params().depth() < 1) {
1361 switch (state->open_encoding_) {
1363 // do nothing at the end of child documents
1364 if (maintext && buf.masterBuffer() != &buf)
1366 // end of main text: also insert a \clearpage (see #5386)
1368 os << "\n\\clearpage\n\\end{CJK}\n";
1372 state->open_encoding_ = none;
1376 // FIXME: If we are in an inset and the switch happened outside this inset,
1377 // do not switch back at the end of the inset (bug #8479)
1378 // The following attempt does not help with listings-caption in a CJK document:
1379 // if (runparams_in.local_font != 0
1380 // && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1383 state->open_encoding_ = none;
1393 // Information about local language is stored as a font feature.
1394 // If this is the last paragraph of the inset and a local_font was set upon entering
1395 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1396 // ensure the encoding is set back to the default encoding of the local language.
1397 if (runparams.isLastPar && runparams_in.local_font != nullptr
1398 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1399 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1400 && !runparams.isFullUnicode()
1402 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1403 os << setEncoding(runparams_in.encoding->iconvName());
1405 // Otherwise, the current encoding should be set for the next paragraph.
1407 runparams_in.encoding = runparams.encoding;
1409 // Also pass the post_macros upstream
1410 runparams_in.post_macro = runparams.post_macro;
1413 // we don't need a newline for the last paragraph!!!
1414 // Note from JMarc: we will re-add a \n explicitly in
1415 // TeXEnvironment, because it is needed in this case
1416 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1417 Layout const & next_layout = nextpar->layout();
1418 if (!text.inset().getLayout().parbreakIgnored())
1419 // Make sure to start a new line
1421 // A newline '\n' is always output before a command,
1422 // so avoid doubling it.
1423 if (!next_layout.isCommand()) {
1424 // Here we now try to avoid spurious empty lines by
1425 // outputting a paragraph break only if: (case 1) the
1426 // paragraph style allows parbreaks and no \begin, \end
1427 // or \item tags are going to follow (i.e., if the next
1428 // isn't the first or the current isn't the last
1429 // paragraph of an environment or itemize) and the
1430 // depth and alignment of the following paragraph is
1431 // unchanged, or (case 2) the following is a
1432 // non-environment paragraph whose depth is increased
1433 // but whose alignment is unchanged, or (case 3) the
1434 // paragraph is not an environment and the next one is a
1435 // non-itemize-like env at lower depth, or (case 4) the
1436 // paragraph is a command not followed by an environment
1437 // and the alignment of the current and next paragraph
1438 // is unchanged, or (case 5) the current alignment is
1439 // changed and a standard paragraph follows.
1440 DocumentClass const & tclass = bparams.documentClass();
1441 if ((style == next_layout
1442 && !style.parbreak_is_newline
1443 && !text.inset().getLayout().parbreakIsNewline()
1444 && !text.inset().getLayout().parbreakIgnored()
1445 && style.latextype != LATEX_ITEM_ENVIRONMENT
1446 && style.latextype != LATEX_LIST_ENVIRONMENT
1447 && style.align == par.getAlign(bparams)
1448 && nextpar->getDepth() == par.getDepth()
1449 && nextpar->getAlign(bparams) == par.getAlign(bparams))
1450 || (!next_layout.isEnvironment()
1451 && nextpar->getDepth() > par.getDepth()
1452 && nextpar->getAlign(bparams) == next_layout.align)
1453 || (!style.isEnvironment()
1454 && next_layout.latextype == LATEX_ENVIRONMENT
1455 && nextpar->getDepth() < par.getDepth())
1456 || (style.isCommand()
1457 && !next_layout.isEnvironment()
1458 && style.align == par.getAlign(bparams)
1459 && next_layout.align == nextpar->getAlign(bparams))
1460 || (style.align != par.getAlign(bparams)
1461 && tclass.isDefaultLayout(next_layout))) {
1467 // Reset language nesting level after intitle command
1468 if (intitle_command)
1469 state->nest_level_ -= 1;
1471 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1472 << &par << " next " << nextpar);
1478 // LaTeX all paragraphs
1479 void latexParagraphs(Buffer const & buf,
1482 OutputParams const & runparams,
1483 string const & everypar)
1485 LASSERT(runparams.par_begin <= runparams.par_end,
1486 { os << "% LaTeX Output Error\n"; return; } );
1488 BufferParams const & bparams = buf.params();
1489 BufferParams const & mparams = buf.masterParams();
1491 bool const maintext = text.isMainText();
1492 bool const is_child = buf.masterBuffer() != &buf;
1493 bool const multibib_child = maintext && is_child
1494 && mparams.multibib == "child";
1496 if (multibib_child && mparams.useBiblatex())
1497 os << "\\newrefsection";
1498 else if (multibib_child && mparams.useBibtopic()
1499 && !buf.masterBibInfo().empty()) {
1500 os << "\\begin{btUnit}\n";
1501 runparams.openbtUnit = true;
1504 // Open a CJK environment at the beginning of the main buffer
1505 // if the document's main encoding requires the CJK package
1506 // or the document encoding is utf8 and the CJK package is required
1507 // (but not in child documents or documents using system fonts):
1508 OutputState * state = getOutputState();
1509 if (maintext && !is_child && !bparams.useNonTeXFonts
1510 && (bparams.encoding().package() == Encoding::CJK
1511 || (bparams.encoding().name() == "utf8"
1512 && runparams.use_CJK))
1514 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1515 ? from_ascii("UTF8")
1516 : from_ascii(bparams.encoding().latexName());
1517 os << "\\begin{CJK}{" << cjkenc
1518 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1519 state->open_encoding_ = CJK;
1521 // if "auto begin" is switched off, explicitly switch the
1522 // language on at start
1523 string const mainlang = runparams.use_polyglossia
1524 ? getPolyglossiaEnvName(bparams.language)
1525 : bparams.language->babel();
1526 string const lang_begin_command = runparams.use_polyglossia ?
1527 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1528 string const lang_end_command = runparams.use_polyglossia ?
1529 "\\end{$$lang}" : lyxrc.language_command_end;
1530 bool const using_begin_end = runparams.use_polyglossia ||
1531 !lang_end_command.empty();
1533 if (maintext && !lyxrc.language_auto_begin &&
1534 !mainlang.empty()) {
1536 string bc = runparams.use_polyglossia ?
1537 getPolyglossiaBegin(lang_begin_command, mainlang,
1538 bparams.language->polyglossiaOpts())
1539 : subst(lang_begin_command, "$$lang", mainlang);
1542 if (using_begin_end)
1543 pushLanguageName(mainlang);
1546 ParagraphList const & paragraphs = text.paragraphs();
1548 if (runparams.par_begin == runparams.par_end) {
1549 // The full doc will be exported but it is easier to just rely on
1550 // runparams range parameters that will be passed TeXEnvironment.
1551 runparams.par_begin = 0;
1552 runparams.par_end = paragraphs.size();
1555 pit_type pit = runparams.par_begin;
1556 // lastpit is for the language check after the loop.
1557 pit_type lastpit = pit;
1558 // variables used in the loop:
1559 bool was_title = false;
1560 bool already_title = false;
1561 DocumentClass const & tclass = bparams.documentClass();
1563 // Did we already warn about inTitle layout mixing? (we only warn once)
1564 bool gave_layout_warning = false;
1565 for (; pit < runparams.par_end; ++pit) {
1567 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1569 // FIXME This check should not be needed. We should
1570 // perhaps issue an error if it is.
1571 Layout const & layout = text.inset().forcePlainLayout() ?
1572 tclass.plainLayout() : par->layout();
1574 if (layout.intitle) {
1575 if (already_title) {
1576 if (!gave_layout_warning && !runparams.dryrun) {
1577 gave_layout_warning = true;
1578 frontend::Alert::warning(_("Error in latexParagraphs"),
1579 bformat(_("You are using at least one "
1580 "layout (%1$s) intended for the title, "
1581 "after using non-title layouts. This "
1582 "could lead to missing or incorrect output."
1585 } else if (!was_title) {
1587 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1589 << from_ascii(tclass.titlename())
1593 } else if (was_title && !already_title && !layout.inpreamble) {
1594 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1595 os << "\\end{" << from_ascii(tclass.titlename())
1599 os << "\\" << from_ascii(tclass.titlename())
1602 already_title = true;
1606 if (layout.isCommand() && !layout.latexname().empty()
1607 && layout.latexname() == bparams.multibib) {
1608 if (runparams.openbtUnit)
1609 os << "\\end{btUnit}\n";
1610 if (!bparams.useBiblatex()
1611 && !buf.masterBibInfo().empty()) {
1612 os << '\n' << "\\begin{btUnit}\n";
1613 runparams.openbtUnit = true;
1617 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1618 // This is a standard top level paragraph, TeX it and continue.
1619 TeXOnePar(buf, text, pit, os, runparams, everypar);
1623 TeXEnvironmentData const data =
1624 prepareEnvironment(buf, text, par, os, runparams);
1625 // pit can be changed in TeXEnvironment.
1626 TeXEnvironment(buf, text, runparams, pit, os);
1627 finishEnvironment(os, runparams, data);
1630 // FIXME: uncomment the content or remove this block
1631 if (pit == runparams.par_end) {
1632 // Make sure that the last paragraph is
1633 // correctly terminated (because TeXOnePar does
1634 // not add a \n in this case)
1638 // It might be that we only have a title in this document
1639 if (was_title && !already_title) {
1640 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1641 os << "\\end{" << from_ascii(tclass.titlename())
1644 os << "\\" << from_ascii(tclass.titlename())
1649 if (maintext && !is_child && runparams.openbtUnit)
1650 os << "\\end{btUnit}\n";
1652 // if "auto end" is switched off, explicitly close the language at the end
1653 // but only if the last par is in a babel or polyglossia language
1654 Language const * const lastpar_language =
1655 paragraphs.at(lastpit).getParLanguage(bparams);
1656 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1657 lastpar_language->encoding()->package() != Encoding::CJK) {
1658 os << from_utf8(subst(lang_end_command,
1662 // If we have language_auto_begin, the stack will
1663 // already be empty, nothing to pop()
1664 if (using_begin_end && !lyxrc.language_auto_begin)
1668 // If the last paragraph is an environment, we'll have to close
1669 // CJK at the very end to do proper nesting.
1670 if (maintext && !is_child && state->open_encoding_ == CJK) {
1671 os << "\\clearpage\n\\end{CJK}\n";
1672 state->open_encoding_ = none;
1674 // Likewise for polyglossia or when using begin/end commands
1675 // or at the very end of an active branch inset with a language switch
1676 Language const * const outer_language = (runparams.local_font != nullptr)
1677 ? runparams.local_font->language() : bparams.language;
1678 string const & prev_lang = runparams.use_polyglossia
1679 ? getPolyglossiaEnvName(outer_language)
1680 : outer_language->babel();
1681 string const lastpar_lang = runparams.use_polyglossia ?
1682 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1683 string const & cur_lang = openLanguageName(state);
1684 if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1685 || (maintext && !is_child)) && !cur_lang.empty()) {
1686 os << from_utf8(subst(lang_end_command,
1690 if (using_begin_end)
1692 } else if (runparams.inbranch && !using_begin_end
1693 && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1694 // with !using_begin_end, cur_lang is empty, so we need to
1695 // compare against the paragraph language (and we are in the
1696 // last paragraph at this point)
1697 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1700 // reset inherited encoding
1701 if (state->cjk_inherited_ > 0) {
1702 state->cjk_inherited_ -= 1;
1703 if (state->cjk_inherited_ == 0)
1704 state->open_encoding_ = CJK;
1707 if (multibib_child && mparams.useBibtopic()) {
1708 os << "\\end{btUnit}\n";
1709 runparams.openbtUnit = false;
1713 // Switch the input encoding for some part(s) of the document.
1714 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1715 OutputParams const & runparams, Encoding const & newEnc,
1716 bool force, bool noswitchmacro)
1718 // Never switch encoding with XeTeX/LuaTeX
1719 // or if we're in a moving argument or inherit the outer encoding.
1720 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1721 return make_pair(false, 0);
1723 // Only switch for auto-selected legacy encodings (inputenc setting
1724 // "auto-legacy" or "auto-legacy-plain").
1725 // The "listings" environment can force a switch also with other
1726 // encoding settings (it does not support variable width encodings
1727 // (utf8, jis, ...) under 8-bit latex engines).
1728 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1729 || runparams.moving_arg))
1730 return make_pair(false, 0);
1732 Encoding const & oldEnc = *runparams.encoding;
1733 // Do not switch, if the encoding is unchanged or switching is not supported.
1734 if (oldEnc.name() == newEnc.name()
1735 || oldEnc.package() == Encoding::japanese
1736 || oldEnc.package() == Encoding::none
1737 || newEnc.package() == Encoding::none
1738 || runparams.for_search)
1739 return make_pair(false, 0);
1740 // FIXME We ignore encoding switches from/to encodings that do
1741 // neither support the inputenc package nor the CJK package here.
1742 // This may fail for characters not supported by "unicodesymbols"
1743 // or for non-ASCII characters in "listings"
1744 // but it is the best we can do.
1747 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1748 << oldEnc.name() << " to " << newEnc.name());
1749 os << setEncoding(newEnc.iconvName());
1750 if (bparams.inputenc == "auto-legacy-plain")
1751 return make_pair(true, 0);
1753 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1754 OutputState * state = getOutputState();
1755 switch (newEnc.package()) {
1756 case Encoding::none:
1757 case Encoding::japanese:
1758 // shouldn't ever reach here (see above) but avoids warning.
1759 return make_pair(true, 0);
1760 case Encoding::inputenc: {
1761 int count = inputenc_arg.length();
1762 if (oldEnc.package() == Encoding::CJK &&
1763 state->open_encoding_ == CJK) {
1765 state->open_encoding_ = none;
1768 else if (oldEnc.package() == Encoding::inputenc &&
1769 state->open_encoding_ == inputenc) {
1771 state->open_encoding_ = none;
1774 if (runparams.local_font != nullptr
1775 && oldEnc.package() == Encoding::CJK) {
1776 // within insets, \inputenc switches need
1777 // to be embraced within \bgroup...\egroup;
1781 state->open_encoding_ = inputenc;
1784 return make_pair(true, count);
1785 os << "\\inputencoding{" << inputenc_arg << '}';
1786 return make_pair(true, count + 16);
1788 case Encoding::CJK: {
1789 int count = inputenc_arg.length();
1790 if (oldEnc.package() == Encoding::CJK &&
1791 state->open_encoding_ == CJK) {
1795 if (oldEnc.package() == Encoding::inputenc &&
1796 state->open_encoding_ == inputenc) {
1800 os << "\\begin{CJK}{"
1801 << from_ascii(newEnc.latexName()) << "}{"
1802 << from_ascii(bparams.fonts_cjk) << "}";
1803 state->open_encoding_ = CJK;
1804 return make_pair(true, count + 15);
1807 // Dead code to avoid a warning:
1808 return make_pair(true, 0);