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"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "texstream.h"
27 #include "TextClass.h"
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetArgument.h"
32 #include "frontends/alert.h"
34 #include "support/lassert.h"
35 #include "support/convert.h"
36 #include "support/debug.h"
37 #include "support/lstrings.h"
38 #include "support/textutils.h"
39 #include "support/gettext.h"
41 #include <QThreadStorage>
47 using namespace lyx::support;
63 OutputState() : prev_env_language_(nullptr), open_encoding_(none),
64 cjk_inherited_(0), nest_level_(0)
67 Language const * prev_env_language_;
68 stack<int> lang_switch_depth_; // Both are always empty when
69 stack<string> open_polyglossia_lang_; // not using polyglossia
70 OpenEncoding open_encoding_;
76 OutputState * getOutputState()
78 // FIXME An instance of OutputState should be kept around for each export
79 // instead of using local thread storage
80 static QThreadStorage<OutputState *> outputstate;
81 if (!outputstate.hasLocalData())
82 outputstate.setLocalData(new OutputState);
83 return outputstate.localData();
87 string const & openLanguageName(OutputState const * state)
89 // Return a reference to the last active language opened with
90 // polyglossia or when using begin/end commands. If none or when
91 // using babel with only a begin command, return a reference to
94 static string const empty;
96 return state->open_polyglossia_lang_.empty()
98 : state->open_polyglossia_lang_.top();
102 bool atSameLastLangSwitchDepth(OutputState const * state)
104 // Return true if the actual nest level is the same at which the
105 // language was switched when using polyglossia or begin/end
106 // commands. Instead, return always true when using babel with
107 // only a begin command.
109 return state->lang_switch_depth_.empty()
111 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
115 bool isLocalSwitch(OutputState const * state)
117 // Return true if the language was opened by a local command switch.
119 return !state->lang_switch_depth_.empty()
120 && state->lang_switch_depth_.top() < 0;
124 bool langOpenedAtThisLevel(OutputState const * state)
126 // Return true if the language was opened at the current nesting level.
128 return !state->lang_switch_depth_.empty()
129 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
133 string const getPolyglossiaEnvName(Language const * lang)
135 string result = lang->polyglossia();
136 if (result == "arabic")
137 // exceptional spelling; see polyglossia docs.
143 string const getPolyglossiaBegin(string const & lang_begin_command,
144 string const & lang, string const & opts,
145 bool const localswitch = false)
149 // we need to revert the upcasing done in getPolyglossiaEnvName()
150 // in case we have a local polyglossia command (\textarabic).
151 string language = localswitch ? ascii_lowercase(lang) : lang;
152 result = subst(lang_begin_command, "$$lang", language);
154 string options = opts.empty() ?
155 string() : "[" + opts + "]";
156 result = subst(result, "$$opts", options);
162 struct TeXEnvironmentData
164 Layout const * style;
165 Language const * par_language;
166 Encoding const * prev_encoding;
168 bool leftindent_open;
172 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
174 ParagraphList::const_iterator pit,
176 OutputParams const & runparams)
178 TeXEnvironmentData data;
180 BufferParams const & bparams = buf.params();
182 // FIXME This test should not be necessary.
183 // We should perhaps issue an error if it is.
184 Layout const & style = text.inset().forcePlainLayout() ?
185 bparams.documentClass().plainLayout() : pit->layout();
187 ParagraphList const & paragraphs = text.paragraphs();
188 bool const firstpar = pit == paragraphs.begin();
189 ParagraphList::const_iterator const priorpit =
190 firstpar ? pit : prev(pit, 1);
192 OutputState * state = getOutputState();
193 bool const use_prev_env_language = state->prev_env_language_ != nullptr
194 && priorpit->layout().isEnvironment()
195 && (priorpit->getDepth() > pit->getDepth()
196 || (priorpit->getDepth() == pit->getDepth()
197 && priorpit->layout() != pit->layout()));
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 // use font at inset or document language in first paragraph
204 firstpar ? (runparams.local_font ?
205 runparams.local_font->language()
207 : (use_prev_env_language ?
208 state->prev_env_language_
209 : priorpit->getParLanguage(bparams));
211 bool const use_polyglossia = runparams.use_polyglossia;
212 string const par_lang = use_polyglossia ?
213 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
214 string const prev_par_lang = use_polyglossia ?
215 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
216 string const doc_lang = use_polyglossia ?
217 getPolyglossiaEnvName(doc_language) : doc_language->babel();
218 string const lang_begin_command = use_polyglossia ?
219 "\\begin{$$lang}" : lyxrc.language_command_begin;
220 string const lang_end_command = use_polyglossia ?
221 "\\end{$$lang}" : lyxrc.language_command_end;
222 bool const using_begin_end = use_polyglossia ||
223 !lang_end_command.empty();
225 // For polyglossia, switch language outside of environment, if possible.
226 // However, if we are at the start of an inset, do not close languages
228 if (par_lang != prev_par_lang) {
230 && (!using_begin_end || langOpenedAtThisLevel(state))
231 && !lang_end_command.empty()
232 && prev_par_lang != doc_lang
233 && !prev_par_lang.empty()) {
234 os << from_ascii(subst(
238 // the '%' is necessary to prevent unwanted whitespace
244 // If no language was explicitly opened and we are using
245 // polyglossia or begin/end commands, then the current
246 // language is the document language.
247 string const & cur_lang = using_begin_end
248 && !state->lang_switch_depth_.empty()
249 ? openLanguageName(state)
252 if ((lang_end_command.empty() ||
253 par_lang != doc_lang ||
254 par_lang != cur_lang) &&
256 string bc = use_polyglossia ?
257 getPolyglossiaBegin(lang_begin_command, par_lang,
258 data.par_language->polyglossiaOpts())
259 : subst(lang_begin_command, "$$lang", par_lang);
261 // the '%' is necessary to prevent unwanted whitespace
264 pushLanguageName(par_lang);
268 data.leftindent_open = false;
269 if (!pit->params().leftIndent().zero()) {
270 os << "\\begin{LyXParagraphLeftIndent}{"
271 << from_ascii(pit->params().leftIndent().asLatexString())
273 data.leftindent_open = true;
276 if (style.isEnvironment())
277 state->nest_level_ += 1;
279 if (style.isEnvironment() && !style.latexname().empty()) {
280 os << "\\begin{" << from_ascii(style.latexname()) << '}';
281 if (!style.latexargs().empty()) {
282 OutputParams rp = runparams;
283 rp.local_font = &pit->getFirstFontSettings(bparams);
284 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
286 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
288 << pit->params().labelWidthString()
290 } else if (style.labeltype == LABEL_BIBLIO) {
291 if (pit->params().labelWidthString().empty())
292 os << '{' << bibitemWidest(buf, runparams) << "}\n";
295 << pit->params().labelWidthString()
298 os << from_ascii(style.latexparam()) << '\n';
299 if (style.latextype == LATEX_BIB_ENVIRONMENT
300 || style.latextype == LATEX_ITEM_ENVIRONMENT
301 || style.latextype == LATEX_LIST_ENVIRONMENT) {
302 OutputParams rp = runparams;
303 rp.local_font = &pit->getFirstFontSettings(bparams);
304 latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
310 // in multilingual environments, the CJK tags have to be nested properly
311 data.cjk_nested = false;
312 if (!bparams.useNonTeXFonts
313 && (bparams.inputenc == "auto-legacy"
314 || bparams.inputenc == "auto-legacy-plain")
315 && data.par_language->encoding()->package() == Encoding::CJK
316 && state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
317 if (prev_par_language->encoding()->package() == Encoding::CJK) {
318 os << "\\begin{CJK}{"
319 << from_ascii(data.par_language->encoding()->latexName())
320 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
322 state->open_encoding_ = CJK;
323 data.cjk_nested = true;
329 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
330 TeXEnvironmentData const & data, bool const maintext,
333 OutputState * state = getOutputState();
334 // BufferParams const & bparams = buf.params();
335 // FIXME: for speedup shortcut below, would require passing of "buf" as argument
336 if (state->open_encoding_ == CJK && data.cjk_nested) {
337 // We need to close the encoding even if it does not change
338 // to do correct environment nesting
339 os << "\\end{CJK}\n";
340 state->open_encoding_ = none;
343 if (data.style->isEnvironment()) {
345 bool const using_begin_end =
346 runparams.use_polyglossia ||
347 !lyxrc.language_command_end.empty();
348 // Close any language opened at this nest level
349 if (using_begin_end) {
350 while (langOpenedAtThisLevel(state)) {
351 if (isLocalSwitch(state)) {
355 << openLanguageName(state)
361 if (data.style->latextype == LATEX_BIB_ENVIRONMENT)
362 // bibliography needs a blank line after
363 // each item for backref to function properly
366 state->nest_level_ -= 1;
367 string const & name = data.style->latexname();
369 os << "\\end{" << from_ascii(name) << "}\n";
370 state->prev_env_language_ = data.par_language;
371 if (runparams.encoding != data.prev_encoding) {
372 runparams.encoding = data.prev_encoding;
373 os << setEncoding(data.prev_encoding->iconvName());
375 // If this is the last par of an inset, the language needs
376 // to be closed after the environment
377 if (lastpar && !maintext) {
378 if (using_begin_end && langOpenedAtThisLevel(state)) {
379 if (isLocalSwitch(state)) {
383 << openLanguageName(state)
391 if (data.leftindent_open) {
392 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
393 state->prev_env_language_ = data.par_language;
394 if (runparams.encoding != data.prev_encoding) {
395 runparams.encoding = data.prev_encoding;
396 os << setEncoding(data.prev_encoding->iconvName());
400 // Check whether we should output a blank line after the environment
401 if (!data.style->nextnoindent)
406 void TeXEnvironment(Buffer const & buf, Text const & text,
407 OutputParams const & runparams,
408 pit_type & pit, otexstream & os)
410 ParagraphList const & paragraphs = text.paragraphs();
411 ParagraphList::const_iterator ipar = paragraphs.iterator_at(pit);
412 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
414 Layout const & current_layout = ipar->layout();
415 depth_type const current_depth = ipar->params().depth();
416 Length const & current_left_indent = ipar->params().leftIndent();
418 // This is for debugging purpose at the end.
419 pit_type const par_begin = pit;
420 for (; pit < runparams.par_end; ++pit) {
421 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
423 // check first if this is an higher depth paragraph.
424 bool go_out = (par->params().depth() < current_depth);
425 if (par->params().depth() == current_depth) {
426 // This environment is finished.
427 go_out |= (par->layout() != current_layout);
428 go_out |= (par->params().leftIndent() != current_left_indent);
431 // nothing to do here, restore pit and go out.
436 if (par->layout() == current_layout
437 && par->params().depth() == current_depth
438 && par->params().leftIndent() == current_left_indent) {
439 // We are still in the same environment so TeXOnePar and continue;
440 TeXOnePar(buf, text, pit, os, runparams);
444 // We are now in a deeper environment.
445 // Either par->layout() != current_layout
446 // Or par->params().depth() > current_depth
447 // Or par->params().leftIndent() != current_left_indent)
449 // FIXME This test should not be necessary.
450 // We should perhaps issue an error if it is.
451 bool const force_plain_layout = text.inset().forcePlainLayout();
452 Layout const & style = force_plain_layout
453 ? buf.params().documentClass().plainLayout()
456 if (!style.isEnvironment()) {
457 // This is a standard paragraph, no need to call TeXEnvironment.
458 TeXOnePar(buf, text, pit, os, runparams);
462 // Do not output empty environments if the whole paragraph has
463 // been deleted with ct and changes are not output.
465 if (runparams.for_searchAdv == OutputParams::NoSearch)
466 output_changes = buf.params().output_changes;
468 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
469 if (size_t(pit + 1) < paragraphs.size()) {
470 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
471 Paragraph const & cpar = paragraphs.at(pit);
472 if ((par->layout() != nextpar->layout()
473 || par->params().depth() == nextpar->params().depth()
474 || par->params().leftIndent() == nextpar->params().leftIndent())
476 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
477 if (!output_changes && !cpar.parEndChange().deleted())
483 // This is a new environment.
484 TeXEnvironmentData const data =
485 prepareEnvironment(buf, text, par, os, runparams);
486 // Recursive call to TeXEnvironment!
487 TeXEnvironment(buf, text, runparams, pit, os);
488 bool const lastpar = size_t(pit + 1) >= paragraphs.size();
489 finishEnvironment(os, runparams, data, text.isMainText(), lastpar);
492 if (pit != runparams.par_end)
493 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
497 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
498 map<size_t, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
500 size_t const argnr = latexargs.size();
504 // Default and preset args are always output, so if they require
505 // other arguments, consider this.
506 for (auto const & larg : latexargs) {
507 Layout::latexarg const & arg = larg.second;
508 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.required.empty()) {
509 vector<string> req = getVectorFromString(arg.required);
510 required.insert(required.end(), req.begin(), req.end());
514 for (size_t i = 1; i <= argnr; ++i) {
515 map<size_t, InsetArgument const *>::const_iterator lit = ilist.find(i);
516 bool inserted = false;
517 if (lit != ilist.end()) {
518 InsetArgument const * ins = lit->second;
520 Layout::LaTeXArgMap::const_iterator const lait =
521 latexargs.find(ins->name());
522 if (lait != latexargs.end()) {
523 Layout::latexarg arg = lait->second;
527 ldelim = arg.mandatory ?
528 from_ascii("{") : from_ascii("[");
529 rdelim = arg.mandatory ?
530 from_ascii("}") : from_ascii("]");
532 if (!arg.ldelim.empty())
534 if (!arg.rdelim.empty())
536 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
537 if (prefix == "listpreamble:")
544 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
545 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
546 for (; lait != laend; ++lait) {
547 string const name = prefix + convert<string>(i);
548 if ((*lait).first == name) {
549 Layout::latexarg arg = (*lait).second;
550 docstring preset = arg.presetarg;
551 if (!arg.defaultarg.empty()) {
554 preset += arg.defaultarg;
557 docstring ldelim = arg.ldelim.empty() ?
558 from_ascii("{") : arg.ldelim;
559 docstring rdelim = arg.rdelim.empty() ?
560 from_ascii("}") : arg.rdelim;
561 os << ldelim << preset << rdelim;
562 } else if (!preset.empty()) {
563 docstring ldelim = arg.ldelim.empty() ?
564 from_ascii("[") : arg.ldelim;
565 docstring rdelim = arg.rdelim.empty() ?
566 from_ascii("]") : arg.rdelim;
567 os << ldelim << preset << rdelim;
568 } else if (find(required.begin(), required.end(),
569 (*lait).first) != required.end()) {
570 docstring ldelim = arg.ldelim.empty() ?
571 from_ascii("[") : arg.ldelim;
572 docstring rdelim = arg.rdelim.empty() ?
573 from_ascii("]") : arg.rdelim;
574 os << ldelim << rdelim;
581 if ((runparams.for_searchAdv != OutputParams::NoSearch) && argnr > 1) {
582 // Mark end of arguments for findadv() only
583 os << "\\endarguments{}";
591 void pushLanguageName(string const & lang_name, bool localswitch)
593 OutputState * state = getOutputState();
595 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
596 state->lang_switch_depth_.push(nest_level);
597 state->open_polyglossia_lang_.push(lang_name);
601 void popLanguageName()
603 OutputState * state = getOutputState();
605 state->lang_switch_depth_.pop();
606 state->open_polyglossia_lang_.pop();
610 string const & openLanguageName()
612 OutputState * state = getOutputState();
614 return openLanguageName(state);
620 void addArgInsets(Paragraph const & par, string const & prefix,
621 Layout::LaTeXArgMap const & latexargs,
622 map<size_t, InsetArgument const *> & ilist,
623 vector<string> & required)
625 for (auto const & table : par.insetList()) {
626 InsetArgument const * arg = table.inset->asInsetArgument();
629 if (arg->name().empty()) {
630 LYXERR0("Error: Unnamed argument inset!");
633 string const name = prefix.empty() ?
634 arg->name() : split(arg->name(), ':');
635 size_t const nr = convert<size_t>(name);
636 ilist.insert({nr, arg});
637 Layout::LaTeXArgMap::const_iterator const lit =
638 latexargs.find(arg->name());
639 if (lit != latexargs.end()) {
640 Layout::latexarg const & larg = lit->second;
641 vector<string> req = getVectorFromString(larg.required);
642 move(req.begin(), req.end(), back_inserter(required));
650 void latexArgInsets(Paragraph const & par, otexstream & os,
651 OutputParams const & runparams,
652 Layout::LaTeXArgMap const & latexargs,
653 string const & prefix)
655 map<size_t, InsetArgument const *> ilist;
656 vector<string> required;
657 addArgInsets(par, prefix, latexargs, ilist, required);
658 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
662 void latexArgInsets(ParagraphList const & pars,
663 ParagraphList::const_iterator pit,
664 otexstream & os, OutputParams const & runparams,
665 Layout::LaTeXArgMap const & latexargs,
666 string const & prefix)
668 map<size_t, InsetArgument const *> ilist;
669 vector<string> required;
671 depth_type const current_depth = pit->params().depth();
672 Layout const current_layout = pit->layout();
674 // get the first paragraph in sequence with this layout and depth
675 ptrdiff_t offset = 0;
677 if (prev(pit, offset) == pars.begin())
679 ParagraphList::const_iterator priorpit = prev(pit, offset + 1);
680 if (priorpit->layout() == current_layout
681 && priorpit->params().depth() == current_depth)
687 ParagraphList::const_iterator spit = prev(pit, offset);
688 for (; spit != pars.end(); ++spit) {
689 if (spit->layout() != current_layout ||
690 spit->params().depth() < current_depth)
692 if (spit->params().depth() > current_depth)
694 addArgInsets(*spit, prefix, latexargs, ilist, required);
696 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
700 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
701 OutputParams const & runparams,
702 Layout::LaTeXArgMap const & latexargs,
703 string const & prefix)
705 map<size_t, InsetArgument const *> ilist;
706 vector<string> required;
708 for (Paragraph const & par : pars) {
709 if (par.layout().hasArgs())
710 // The InsetArguments inside this paragraph refer to this paragraph
712 addArgInsets(par, prefix, latexargs, ilist, required);
714 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
720 // output the proper paragraph start according to latextype.
721 void parStartCommand(Paragraph const & par, otexstream & os,
722 OutputParams const & runparams, Layout const & style)
724 switch (style.latextype) {
726 if (par.needsCProtection(runparams.moving_arg)) {
727 if (contains(runparams.active_chars, '^'))
728 // cprotect relies on ^ being on catcode 7
729 os << "\\begingroup\\catcode`\\^=7";
732 os << '\\' << from_ascii(style.latexname());
735 if (!style.latexargs().empty())
736 latexArgInsets(par, os, runparams, style.latexargs());
737 os << from_ascii(style.latexparam());
739 case LATEX_ITEM_ENVIRONMENT:
740 case LATEX_LIST_ENVIRONMENT:
741 if (runparams.for_searchAdv != OutputParams::NoSearch) {
742 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
745 os << "\\" + style.itemcommand();
747 if (!style.itemargs().empty())
748 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
752 case LATEX_ENVIRONMENT:
753 if (runparams.for_searchAdv != OutputParams::NoSearch) {
754 os << "\\latexenvironment{" << style.latexname() << "}{";
757 case LATEX_BIB_ENVIRONMENT:
758 // ignore this, the inset will write itself
767 // FIXME: this should be anonymous
768 void TeXOnePar(Buffer const & buf,
772 OutputParams const & runparams_in,
773 string const & everypar,
774 int start_pos, int end_pos,
777 BufferParams const & bparams = runparams_in.is_child
778 ? buf.masterParams() : buf.params();
779 ParagraphList const & paragraphs = text.paragraphs();
780 Paragraph const & par = paragraphs.at(pit);
781 // FIXME This check should not really be needed.
782 // Perhaps we should issue an error if it is.
783 Layout const & style = text.inset().forcePlainLayout() ?
784 bparams.documentClass().plainLayout() : par.layout();
786 if (style.inpreamble && !force)
789 // Do not output empty commands if the whole paragraph has
790 // been deleted with ct and changes are not output.
791 if ((runparams_in.for_searchAdv != OutputParams::SearchWithDeleted) && style.latextype != LATEX_ENVIRONMENT
792 && !par.empty() && par.isDeleted(0, par.size()) && !bparams.output_changes)
795 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
798 OutputParams runparams = runparams_in;
799 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
800 // We reinitialize par begin and end to be on the safe side
801 // with embedded inset as we don't know if they set those
803 runparams.par_begin = 0;
804 runparams.par_end = 0;
806 bool const maintext = text.isMainText();
807 // we are at the beginning of an inset and CJK is already open;
808 // we count inheritation levels to get the inset nesting right.
809 OutputState * state = getOutputState();
810 if (pit == 0 && !maintext
811 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
812 state->cjk_inherited_ += 1;
813 state->open_encoding_ = none;
816 // This paragraph is merged and we do not show changes in the output
817 bool const merged_par = !bparams.output_changes && par.parEndChange().deleted();
819 if (text.inset().isPassThru()) {
820 Font const outerfont = text.outerFont(pit);
822 // No newline before first paragraph in this lyxtext
823 if (pit > 0 && !text.inset().getLayout().parbreakIgnored() && !merged_par) {
825 if (!text.inset().getLayout().parbreakIsNewline())
829 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
833 Paragraph const * nextpar = runparams.isLastPar
834 ? nullptr : ¶graphs.at(pit + 1);
836 bool const intitle_command = style.intitle && style.isCommand();
837 // Intitle commands switch languages locally, thus increase
838 // language nesting level
840 state->nest_level_ += 1;
842 if (style.pass_thru) {
843 Font const outerfont = text.outerFont(pit);
844 parStartCommand(par, os, runparams, style);
845 if (style.isCommand() && style.needprotect)
846 // Due to the moving argument, some fragile
847 // commands (labels, index entries)
848 // are output after this command (#2154)
849 runparams.postpone_fragile_stuff =
850 bparams.postpone_fragile_content;
854 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
856 // I did not create a parEndCommand for this minuscule
857 // task because in the other user of parStartCommand
858 // the code is different (JMarc)
859 if (style.isCommand()) {
861 if (par.needsCProtection(runparams.moving_arg)
862 && contains(runparams.active_chars, '^'))
869 else if (!merged_par)
871 if (!style.parbreak_is_newline && !merged_par) {
873 } else if (nextpar && !style.isEnvironment()) {
874 Layout const nextstyle = text.inset().forcePlainLayout()
875 ? bparams.documentClass().plainLayout()
877 if (nextstyle.name() != style.name() && !merged_par)
884 // This paragraph's language
885 Language const * const par_language = par.getParLanguage(bparams);
886 Language const * const nextpar_language = nextpar ?
887 nextpar->getParLanguage(bparams) : nullptr;
888 // The document's language
889 Language const * const doc_language = bparams.language;
890 // The language that was in effect when the environment this paragraph is
891 // inside of was opened
892 Language const * const outer_language =
893 (runparams.local_font != nullptr) ?
894 runparams.local_font->language() : doc_language;
896 Paragraph const * priorpar = (pit == 0) ? nullptr : ¶graphs.at(pit - 1);
898 // The previous language that was in effect is the language of the
899 // previous paragraph, unless the previous paragraph is inside an
900 // environment with nesting depth greater than (or equal to, but with
901 // a different layout) the current one. If there is no previous
902 // paragraph, the previous language is the outer language.
903 // Note further that we take the outer language also if the prior par
904 // is PassThru, since in that case it has latex_language, and all secondary
905 // languages have been closed (#10793).
906 bool const use_prev_env_language = state->prev_env_language_ != nullptr
908 && priorpar->layout().isEnvironment()
909 && (priorpar->getDepth() > par.getDepth()
910 || (priorpar->getDepth() == par.getDepth()
911 && priorpar->layout() != par.layout()));
913 // We need to ignore previous intitle commands since languages
914 // are switched locally there (# 11514)
915 // There might be paragraphs before the title, so we check this.
916 Paragraph * prior_nontitle_par = nullptr;
917 if (!intitle_command) {
921 Paragraph const * tmppar = ¶graphs.at(ppit);
922 if (tmppar->layout().intitle && tmppar->layout().isCommand())
924 prior_nontitle_par = const_cast<Paragraph*>(tmppar);
928 Language const * const prev_language =
929 runparams_in.for_searchAdv != OutputParams::NoSearch
930 ? languages.getLanguage("ignore")
931 : (prior_nontitle_par && !prior_nontitle_par->isPassThru())
932 ? (use_prev_env_language
933 ? state->prev_env_language_
934 : prior_nontitle_par->getParLanguage(bparams))
937 bool const use_polyglossia = runparams.use_polyglossia;
938 string const par_lang = use_polyglossia ?
939 getPolyglossiaEnvName(par_language): par_language->babel();
940 string const prev_lang = use_polyglossia ?
941 getPolyglossiaEnvName(prev_language) : prev_language->babel();
942 string const outer_lang = use_polyglossia ?
943 getPolyglossiaEnvName(outer_language) : outer_language->babel();
944 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
945 getPolyglossiaEnvName(nextpar_language) :
946 nextpar_language->babel()) : string();
947 string lang_begin_command = use_polyglossia ?
948 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
949 string lang_end_command = use_polyglossia ?
950 "\\end{$$lang}" : lyxrc.language_command_end;
951 // the '%' is necessary to prevent unwanted whitespace
952 string lang_command_termination = "%\n";
953 bool const using_begin_end = use_polyglossia ||
954 !lang_end_command.empty();
956 // For InTitle commands, we need to switch the language inside the command
957 // (see #10849); thus open the command here.
958 if (intitle_command) {
959 parStartCommand(par, os, runparams, style);
960 if (style.isCommand() && style.needprotect)
961 // Due to the moving argument, some fragile
962 // commands (labels, index entries)
963 // are output after this command (#2154)
964 runparams.postpone_fragile_stuff =
965 bparams.postpone_fragile_content;
969 // In some insets (such as Arguments), we cannot use \selectlanguage.
970 // Also, if an RTL language is set via environment in polyglossia,
971 // only a nested \\text<lang> command will reset the direction for LTR
972 // languages (see # 10111).
973 bool const in_polyglossia_rtl_env =
975 && runparams.local_font != nullptr
976 && outer_language->rightToLeft()
977 && !par_language->rightToLeft();
978 bool const localswitch =
979 (runparams_in.for_searchAdv != OutputParams::NoSearch
980 || text.inset().forceLocalFontSwitch()
981 || (using_begin_end && text.inset().forcePlainLayout())
982 || in_polyglossia_rtl_env)
983 && !text.inset().forceParDirectionSwitch();
985 lang_begin_command = use_polyglossia ?
986 "\\text$$lang$$opts{" : lyxrc.language_command_local;
987 lang_end_command = "}";
988 lang_command_termination.clear();
991 bool const localswitch_needed = localswitch && par_lang != outer_lang;
993 // localswitches need to be closed and reopened at each par
994 if ((runparams_in.for_searchAdv != OutputParams::NoSearch) || ((par_lang != prev_lang || localswitch_needed)
995 // check if we already put language command in TeXEnvironment()
996 && !(style.isEnvironment()
997 && (pit == 0 || (priorpar->layout() != par.layout()
998 && priorpar->getDepth() <= par.getDepth())
999 || priorpar->getDepth() < par.getDepth())))) {
1001 && (!using_begin_end || langOpenedAtThisLevel(state))
1002 && !lang_end_command.empty()
1003 && prev_lang != outer_lang
1004 && !prev_lang.empty()
1005 && (!using_begin_end || !style.isEnvironment())) {
1006 os << from_ascii(subst(lang_end_command,
1009 << lang_command_termination;
1010 if (using_begin_end)
1014 // We need to open a new language if we couldn't close the previous
1015 // one (because there's no language_command_end); and even if we closed
1016 // the previous one, if the current language is different than the
1017 // outer_language (which is currently in effect once the previous one
1019 if ((lang_end_command.empty() || par_lang != outer_lang
1020 || (!using_begin_end
1021 || (style.isEnvironment() && par_lang != prev_lang)))
1022 && !par_lang.empty()) {
1023 // If we're inside an inset, and that inset is within an \L or \R
1024 // (or equivalents), then within the inset, too, any opposite
1025 // language paragraph should appear within an \L or \R (in addition
1026 // to, outside of, the normal language switch commands).
1027 // This behavior is not correct for ArabTeX, though.
1028 if (!using_begin_end
1030 && par_language->lang() != "arabic_arabtex"
1031 && outer_language->lang() != "arabic_arabtex"
1032 // are we in an inset?
1033 && runparams.local_font != nullptr
1034 // is the inset within an \L or \R?
1036 // FIXME: currently, we don't check this; this means that
1037 // we'll have unnnecessary \L and \R commands, but that
1038 // doesn't seem to hurt (though latex will complain)
1040 // is this paragraph in the opposite direction?
1041 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
1042 // FIXME: I don't have a working copy of the Arabi package, so
1043 // I'm not sure if the farsi and arabic_arabi stuff is correct
1045 if (par_language->lang() == "farsi")
1047 else if (outer_language->lang() == "farsi")
1049 else if (par_language->lang() == "arabic_arabi")
1051 else if (outer_language->lang() == "arabic_arabi")
1053 // remaining RTL languages currently is hebrew
1054 else if (par_language->rightToLeft())
1059 // With CJK, the CJK tag has to be closed first (see below)
1060 if ((runparams.encoding->package() != Encoding::CJK
1061 || bparams.useNonTeXFonts
1062 || (runparams.for_searchAdv != OutputParams::NoSearch))
1063 && (par_lang != openLanguageName(state) || localswitch || intitle_command)
1064 && !par_lang.empty()) {
1065 string bc = use_polyglossia ?
1066 getPolyglossiaBegin(lang_begin_command, par_lang,
1067 par_language->polyglossiaOpts(),
1069 : subst(lang_begin_command, "$$lang", par_lang);
1071 os << lang_command_termination;
1072 if (using_begin_end)
1073 pushLanguageName(par_lang, localswitch);
1078 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
1079 // encoding, since this only affects the position of the outputted
1080 // \inputencoding command; the encoding switch will occur when necessary
1081 if (bparams.inputenc == "auto-legacy"
1082 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
1083 && runparams.encoding->package() != Encoding::japanese
1084 && runparams.encoding->package() != Encoding::none) {
1085 // Look ahead for future encoding changes.
1086 // We try to output them at the beginning of the paragraph,
1087 // since the \inputencoding command is not allowed e.g. in
1088 // sections. For this reason we only set runparams.moving_arg
1089 // after checking for the encoding change, otherwise the
1090 // change would be always avoided by switchEncoding().
1091 for (pos_type i = 0; i < par.size(); ++i) {
1092 char_type const c = par.getChar(i);
1093 Encoding const * const encoding =
1094 par.getFontSettings(bparams, i).language()->encoding();
1095 if (encoding->package() != Encoding::CJK
1096 && runparams.encoding->package() == Encoding::inputenc
1101 // All characters before c are in the ASCII range, and
1102 // c is non-ASCII (but no inset), so change the
1103 // encoding to that required by the language of c.
1104 // With CJK, only add switch if we have CJK content at the beginning
1106 if (i != 0 && encoding->package() == Encoding::CJK)
1109 pair<bool, int> enc_switch = switchEncoding(os.os(),
1110 bparams, runparams, *encoding);
1111 // the following is necessary after a CJK environment in a multilingual
1112 // context (nesting issue).
1113 if (par_language->encoding()->package() == Encoding::CJK
1114 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1115 os << "\\begin{CJK}{"
1116 << from_ascii(par_language->encoding()->latexName())
1117 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1118 state->open_encoding_ = CJK;
1120 if (encoding->package() != Encoding::none && enc_switch.first) {
1121 if (enc_switch.second > 0) {
1122 // the '%' is necessary to prevent unwanted whitespace
1125 // With CJK, the CJK tag had to be closed first (see above)
1126 if (runparams.encoding->package() == Encoding::CJK
1127 && par_lang != openLanguageName(state)
1128 && !par_lang.empty()) {
1129 os << subst(lang_begin_command, "$$lang", par_lang)
1130 << lang_command_termination;
1131 if (using_begin_end)
1132 pushLanguageName(par_lang, localswitch);
1134 runparams.encoding = encoding;
1140 runparams.moving_arg |= style.needprotect;
1141 if (style.needmboxprotect)
1142 ++runparams.inulemcmd;
1143 Encoding const * const prev_encoding = runparams.encoding;
1145 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1146 if (par.allowParagraphCustomization()) {
1147 if (par.params().startOfAppendix()) {
1148 os << "\n\\appendix\n";
1151 // InTitle commands must use switches (not environments)
1152 // inside the commands (see #9332)
1153 if (style.intitle) {
1154 if (!par.params().spacing().isDefault())
1156 if (runparams.moving_arg)
1158 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1161 if (!par.params().spacing().isDefault()
1162 && (pit == 0 || !priorpar->hasSameLayout(par)))
1164 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1168 if (style.isCommand()) {
1174 // For InTitle commands, we already started the command before
1175 // the language switch
1176 if (!intitle_command) {
1177 parStartCommand(par, os, runparams, style);
1178 if (style.isCommand() && style.needprotect)
1179 // Due to the moving argument, some fragile
1180 // commands (labels, index entries)
1181 // are output after this command (#2154)
1182 runparams.postpone_fragile_stuff =
1183 bparams.postpone_fragile_content;
1186 Font const outerfont = text.outerFont(pit);
1189 os << from_utf8(everypar);
1190 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1192 Font const font = par.empty()
1193 ? par.getLayoutFont(bparams, outerfont)
1194 : par.getFont(bparams, par.size() - 1, outerfont);
1196 bool const is_command = style.isCommand();
1198 // InTitle commands need to be closed after the language has been closed.
1199 if (!intitle_command) {
1202 if (!style.postcommandargs().empty())
1203 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1204 if (!runparams.post_macro.empty()) {
1205 // Output the stored fragile commands (labels, indices etc.)
1206 // that need to be output after the command with moving argument.
1207 os << runparams.post_macro;
1208 runparams.post_macro.clear();
1210 if (par.needsCProtection(runparams.moving_arg)
1211 && contains(runparams.active_chars, '^'))
1213 if (runparams.encoding != prev_encoding) {
1214 runparams.encoding = prev_encoding;
1215 os << setEncoding(prev_encoding->iconvName());
1220 bool pending_newline = false;
1221 bool unskip_newline = false;
1222 bool close_lang_switch = false;
1223 switch (style.latextype) {
1224 case LATEX_ITEM_ENVIRONMENT:
1225 case LATEX_LIST_ENVIRONMENT:
1226 if ((nextpar && par_lang != nextpar_lang
1227 && nextpar->getDepth() == par.getDepth())
1228 || (atSameLastLangSwitchDepth(state) && nextpar
1229 && nextpar->getDepth() < par.getDepth()))
1230 close_lang_switch = using_begin_end;
1231 if (nextpar && par.params().depth() < nextpar->params().depth())
1232 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1234 case LATEX_ENVIRONMENT: {
1235 // if it's the last paragraph of the current environment
1236 // skip it otherwise fall through
1238 && ((nextpar->layout() != par.layout()
1239 || nextpar->params().depth() != par.params().depth())
1240 || (!using_begin_end || par_lang != nextpar_lang)))
1242 close_lang_switch = using_begin_end;
1249 // we don't need it for the last paragraph and in InTitle commands!!!
1250 if (nextpar && !intitle_command)
1251 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1254 // InTitle commands use switches (not environments) for space settings
1255 if (par.allowParagraphCustomization() && !style.intitle) {
1256 if (!par.params().spacing().isDefault()
1257 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1258 if (pending_newline)
1261 string const endtag =
1262 par.params().spacing().writeEnvirEnd(useSetSpace);
1263 if (prefixIs(endtag, "\\end{"))
1266 os << from_ascii(endtag);
1267 pending_newline = true;
1271 // Closing the language is needed for the last paragraph in a given language
1272 // as well as for any InTitleCommand (since these set the language locally);
1273 // it is also needed if we're within an \L or \R that we may have opened above
1274 // (not necessarily in this paragraph) and are about to close.
1275 bool closing_rtl_ltr_environment = !using_begin_end
1277 && (par_language->lang() != "arabic_arabtex"
1278 && outer_language->lang() != "arabic_arabtex")
1279 // have we opened an \L or \R environment?
1280 && runparams.local_font != nullptr
1281 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1282 // are we about to close the language?
1283 &&((nextpar && par_lang != nextpar_lang)
1284 || (runparams.isLastPar && par_lang != outer_lang));
1286 if (localswitch_needed
1287 || (intitle_command && using_begin_end)
1288 || closing_rtl_ltr_environment
1289 || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1290 && (par_lang != outer_lang || (using_begin_end
1291 && style.isEnvironment()
1292 && par_lang != nextpar_lang)))) {
1293 // Since \selectlanguage write the language to the aux file,
1294 // we need to reset the language at the end of footnote or
1297 if (!localswitch && (pending_newline || close_lang_switch))
1300 // when the paragraph uses CJK, the language has to be closed earlier
1301 if ((font.language()->encoding()->package() != Encoding::CJK)
1302 || bparams.useNonTeXFonts
1303 || (runparams_in.for_searchAdv != OutputParams::NoSearch)) {
1304 if (lang_end_command.empty()) {
1305 // If this is a child, we should restore the
1306 // master language after the last paragraph.
1307 Language const * const current_language =
1308 (runparams.isLastPar && runparams.master_language)
1309 ? runparams.master_language
1311 string const current_lang = use_polyglossia
1312 ? getPolyglossiaEnvName(current_language)
1313 : current_language->babel();
1314 if (!current_lang.empty()
1315 && current_lang != openLanguageName(state)) {
1316 string bc = use_polyglossia ?
1317 getPolyglossiaBegin(lang_begin_command, current_lang,
1318 current_language->polyglossiaOpts(),
1320 : subst(lang_begin_command, "$$lang", current_lang);
1322 pending_newline = !localswitch
1323 && !text.inset().getLayout().parbreakIgnored();
1324 unskip_newline = !localswitch;
1325 if (using_begin_end)
1326 pushLanguageName(current_lang, localswitch);
1328 } else if ((!using_begin_end ||
1329 langOpenedAtThisLevel(state)) &&
1330 !par_lang.empty()) {
1331 // If we are in an environment, we have to
1332 // close the "outer" language afterwards
1333 string const & cur_lang = openLanguageName(state);
1334 if (!style.isEnvironment()
1335 || (close_lang_switch
1336 && atSameLastLangSwitchDepth(state)
1337 && par_lang != outer_lang
1338 && (par_lang != cur_lang
1339 || (cur_lang != outer_lang
1341 && style != nextpar->layout())))
1342 || (atSameLastLangSwitchDepth(state)
1343 && !state->lang_switch_depth_.empty()
1344 && cur_lang != par_lang)
1345 || in_polyglossia_rtl_env)
1347 if (using_begin_end && !localswitch)
1349 os << from_ascii(subst(
1353 pending_newline = !localswitch
1354 && !text.inset().getLayout().parbreakIgnored();
1355 unskip_newline = !localswitch;
1356 if (using_begin_end)
1362 if (closing_rtl_ltr_environment)
1365 // InTitle commands need to be closed after the language has been closed.
1366 if (intitle_command) {
1368 if (!style.postcommandargs().empty())
1369 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1370 if (!runparams.post_macro.empty()) {
1371 // Output the stored fragile commands (labels, indices etc.)
1372 // that need to be output after the command with moving argument.
1373 os << runparams.post_macro;
1374 runparams.post_macro.clear();
1376 if (par.needsCProtection(runparams.moving_arg)
1377 && contains(runparams.active_chars, '^'))
1379 if (runparams.encoding != prev_encoding) {
1380 runparams.encoding = prev_encoding;
1381 os << setEncoding(prev_encoding->iconvName());
1385 bool const last_was_separator =
1386 !par.empty() && par.isEnvSeparator(par.size() - 1);
1388 // Signify added/deleted par break in output if show changes in output
1389 if (nextpar && !os.afterParbreak() && !last_was_separator
1390 && bparams.output_changes && par.parEndChange().changed()) {
1391 Changes::latexMarkChange(os, bparams, Change(Change::UNCHANGED),
1392 par.parEndChange(), runparams);
1393 os << bparams.encoding().latexString(docstring(1, 0x00b6)).first << "}";
1396 if (pending_newline) {
1398 // prevent unwanted whitespace
1400 if (!os.afterParbreak() && !last_was_separator)
1404 // if this is a CJK-paragraph and the next isn't, close CJK
1405 // also if the next paragraph is a multilingual environment (because of nesting)
1406 if (nextpar && state->open_encoding_ == CJK
1407 && bparams.encoding().iconvName() != "UTF-8"
1408 && bparams.encoding().package() != Encoding::CJK
1409 && ((nextpar_language &&
1410 nextpar_language->encoding()->package() != Encoding::CJK)
1411 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1412 // inbetween environments, CJK has to be closed later (nesting!)
1413 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1414 os << "\\end{CJK}\n";
1415 state->open_encoding_ = none;
1418 // If this is the last paragraph, close the CJK environment
1419 // if necessary. If it's an environment or nested in an environment,
1420 // we'll have to \end that first.
1421 if (runparams.isLastPar && !style.isEnvironment()
1422 && par.params().depth() < 1) {
1423 switch (state->open_encoding_) {
1425 // do nothing at the end of child documents
1426 if (maintext && buf.masterBuffer() != &buf)
1428 // end of main text: also insert a \clearpage (see #5386)
1430 os << "\n\\clearpage\n\\end{CJK}\n";
1434 state->open_encoding_ = none;
1438 // FIXME: If we are in an inset and the switch happened outside this inset,
1439 // do not switch back at the end of the inset (bug #8479)
1440 // The following attempt does not help with listings-caption in a CJK document:
1441 // if (runparams_in.local_font != 0
1442 // && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1445 state->open_encoding_ = none;
1455 // Information about local language is stored as a font feature.
1456 // If this is the last paragraph of the inset and a local_font was set upon entering
1457 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1458 // ensure the encoding is set back to the default encoding of the local language.
1459 if (runparams.isLastPar && runparams_in.local_font != nullptr
1460 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1461 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1462 && !runparams.isFullUnicode()
1464 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1465 os << setEncoding(runparams_in.encoding->iconvName());
1467 // Otherwise, the current encoding should be set for the next paragraph.
1469 runparams_in.encoding = runparams.encoding;
1471 // Also pass the post_macros upstream
1472 runparams_in.post_macro = runparams.post_macro;
1473 // These need to be passed upstream as well
1474 runparams_in.need_maketitle = runparams.need_maketitle;
1475 runparams_in.have_maketitle = runparams.have_maketitle;
1478 // we don't need a newline for the last paragraph!!!
1479 // Note from JMarc: we will re-add a \n explicitly in
1480 // TeXEnvironment, because it is needed in this case
1481 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1482 if (!text.inset().getLayout().parbreakIgnored() && !merged_par)
1483 // Make sure to start a new line
1485 // A newline '\n' is always output before a command,
1486 // so avoid doubling it.
1487 Layout const & next_layout = nextpar->layout();
1488 if (!next_layout.isCommand()) {
1489 // Here we now try to avoid spurious empty lines by
1490 // outputting a paragraph break only if: (case 1) the
1491 // paragraph style allows parbreaks and no \begin, \end
1492 // or \item tags are going to follow (i.e., if the next
1493 // isn't the first or the current isn't the last
1494 // paragraph of an environment or itemize) and the
1495 // depth and alignment of the following paragraph is
1496 // unchanged, or (case 2) the following is a
1497 // non-environment paragraph whose depth is increased
1498 // but whose alignment is unchanged, or (case 3) the
1499 // paragraph is not an environment and the next one is a
1500 // non-itemize-like env at lower depth, or (case 4) the
1501 // paragraph is a command not followed by an environment
1502 // and the alignment of the current and next paragraph
1503 // is unchanged, or (case 5) the current alignment is
1504 // changed and a standard paragraph follows.
1505 DocumentClass const & tclass = bparams.documentClass();
1506 if ((style == next_layout
1507 && !style.parbreak_is_newline
1508 && !text.inset().getLayout().parbreakIsNewline()
1509 && !text.inset().getLayout().parbreakIgnored()
1510 && style.latextype != LATEX_ITEM_ENVIRONMENT
1511 && style.latextype != LATEX_LIST_ENVIRONMENT
1512 && style.align == par.getAlign(bparams)
1513 && nextpar->getDepth() == par.getDepth()
1514 && nextpar->getAlign(bparams) == par.getAlign(bparams))
1515 || (!next_layout.isEnvironment()
1516 && nextpar->getDepth() > par.getDepth()
1517 && nextpar->getAlign(bparams) == next_layout.align)
1518 || (!style.isEnvironment()
1519 && next_layout.latextype == LATEX_ENVIRONMENT
1520 && nextpar->getDepth() < par.getDepth())
1521 || (style.isCommand()
1522 && !next_layout.isEnvironment()
1523 && style.align == par.getAlign(bparams)
1524 && next_layout.align == nextpar->getAlign(bparams))
1525 || (style.align != par.getAlign(bparams)
1526 && tclass.isDefaultLayout(next_layout))) {
1527 // and omit paragraph break if it has been deleted with ct
1528 // and changes are not shown in output
1530 if (runparams.isNonLong)
1531 // This is to allow parbreak in multirow
1532 // It could also be used for other non-long
1534 os << "\\endgraf\n";
1542 // Reset language nesting level after intitle command
1543 if (intitle_command)
1544 state->nest_level_ -= 1;
1546 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1547 << &par << " next " << nextpar);
1553 // LaTeX all paragraphs
1554 void latexParagraphs(Buffer const & buf,
1557 OutputParams const & runparams,
1558 string const & everypar)
1560 LASSERT(runparams.par_begin <= runparams.par_end,
1561 { os << "% LaTeX Output Error\n"; return; } );
1563 BufferParams const & bparams = buf.params();
1564 BufferParams const & mparams = buf.masterParams();
1566 bool const maintext = text.isMainText();
1567 bool const is_child = buf.masterBuffer() != &buf;
1568 bool const multibib_child = maintext && is_child
1569 && mparams.multibib == "child";
1571 if (multibib_child && mparams.useBiblatex())
1572 os << "\\newrefsection";
1573 else if (multibib_child && mparams.useBibtopic()
1574 && !buf.masterBibInfo().empty()) {
1575 os << "\\begin{btUnit}\n";
1576 runparams.openbtUnit = true;
1579 // Open a CJK environment at the beginning of the main buffer
1580 // if the document's main encoding requires the CJK package
1581 // or the document encoding is utf8 and the CJK package is required
1582 // (but not in child documents or documents using system fonts):
1583 OutputState * state = getOutputState();
1584 if (maintext && !is_child && !bparams.useNonTeXFonts
1585 && (bparams.encoding().package() == Encoding::CJK
1586 || (bparams.encoding().name() == "utf8"
1587 && runparams.use_CJK))
1589 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1590 ? from_ascii("UTF8")
1591 : from_ascii(bparams.encoding().latexName());
1592 os << "\\begin{CJK}{" << cjkenc
1593 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1594 state->open_encoding_ = CJK;
1596 // if "auto begin" is switched off, explicitly switch the
1597 // language on at start
1598 string const mainlang = runparams.use_polyglossia
1599 ? getPolyglossiaEnvName(bparams.language)
1600 : bparams.language->babel();
1601 string const lang_begin_command = runparams.use_polyglossia ?
1602 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1603 string const lang_end_command = runparams.use_polyglossia ?
1604 "\\end{$$lang}" : lyxrc.language_command_end;
1605 bool const using_begin_end = runparams.use_polyglossia ||
1606 !lang_end_command.empty();
1608 if (maintext && !lyxrc.language_auto_begin &&
1609 !mainlang.empty()) {
1611 string bc = runparams.use_polyglossia ?
1612 getPolyglossiaBegin(lang_begin_command, mainlang,
1613 bparams.language->polyglossiaOpts())
1614 : subst(lang_begin_command, "$$lang", mainlang);
1617 if (using_begin_end)
1618 pushLanguageName(mainlang);
1621 ParagraphList const & paragraphs = text.paragraphs();
1623 if (runparams.par_begin == runparams.par_end) {
1624 // The full doc will be exported but it is easier to just rely on
1625 // runparams range parameters that will be passed TeXEnvironment.
1626 runparams.par_begin = 0;
1627 runparams.par_end = static_cast<int>(paragraphs.size());
1630 pit_type pit = runparams.par_begin;
1631 // lastpit is for the language check after the loop.
1632 pit_type lastpit = pit;
1633 DocumentClass const & tclass = bparams.documentClass();
1635 // Did we already warn about inTitle layout mixing? (we only warn once)
1636 bool gave_layout_warning = false;
1637 for (; pit < runparams.par_end; ++pit) {
1639 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
1641 // FIXME This check should not be needed. We should
1642 // perhaps issue an error if it is.
1643 Layout const & layout = text.inset().forcePlainLayout() ?
1644 tclass.plainLayout() : par->layout();
1646 if (layout.intitle) {
1647 if (runparams.have_maketitle) {
1648 if (!gave_layout_warning && !runparams.dryrun) {
1649 gave_layout_warning = true;
1650 frontend::Alert::warning(_("Error in latexParagraphs"),
1651 bformat(_("You are using at least one "
1652 "layout (%1$s) intended for the title, "
1653 "after using non-title layouts. This "
1654 "could lead to missing or incorrect output."
1657 } else if (!runparams.need_maketitle) {
1658 runparams.need_maketitle = true;
1659 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1661 << from_ascii(tclass.titlename())
1665 } else if (runparams.need_maketitle && !runparams.have_maketitle
1666 && !layout.inpreamble && !text.inset().isInTitle()) {
1667 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1668 os << "\\end{" << from_ascii(tclass.titlename())
1672 os << "\\" << from_ascii(tclass.titlename())
1675 runparams.have_maketitle = true;
1676 runparams.need_maketitle = false;
1679 if (layout.isCommand() && !layout.latexname().empty()
1680 && layout.latexname() == bparams.multibib) {
1681 if (runparams.openbtUnit)
1682 os << "\\end{btUnit}\n";
1683 if (!bparams.useBiblatex()
1684 && !buf.masterBibInfo().empty()) {
1685 os << '\n' << "\\begin{btUnit}\n";
1686 runparams.openbtUnit = true;
1690 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1691 // This is a standard top level paragraph, TeX it and continue.
1692 TeXOnePar(buf, text, pit, os, runparams, everypar);
1696 // Do not output empty environments if the whole paragraph has
1697 // been deleted with ct and changes are not output.
1698 bool output_changes;
1699 if (runparams.for_searchAdv == OutputParams::NoSearch)
1700 output_changes = bparams.output_changes;
1702 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
1703 bool const lastpar = size_t(pit + 1) >= paragraphs.size();
1705 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
1706 Paragraph const & cpar = paragraphs.at(pit);
1707 if ((par->layout() != nextpar->layout()
1708 || par->params().depth() == nextpar->params().depth()
1709 || par->params().leftIndent() == nextpar->params().leftIndent())
1711 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
1712 if (!cpar.parEndChange().deleted())
1717 // This is the last par
1718 Paragraph const & cpar = paragraphs.at(pit);
1720 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
1721 if (!cpar.parEndChange().deleted())
1727 TeXEnvironmentData const data =
1728 prepareEnvironment(buf, text, par, os, runparams);
1729 // pit can be changed in TeXEnvironment.
1730 TeXEnvironment(buf, text, runparams, pit, os);
1731 finishEnvironment(os, runparams, data, maintext, lastpar);
1734 // FIXME: uncomment the content or remove this block
1735 if (pit == runparams.par_end) {
1736 // Make sure that the last paragraph is
1737 // correctly terminated (because TeXOnePar does
1738 // not add a \n in this case)
1742 // It might be that we only have a title in this document.
1743 // But if we're in an inset, this is not the end of
1744 // the document. (There may be some other checks of this
1745 // kind that are needed.)
1746 if (runparams.need_maketitle && !runparams.have_maketitle && maintext) {
1747 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1748 os << "\\end{" << from_ascii(tclass.titlename())
1751 os << "\\" << from_ascii(tclass.titlename())
1756 if (maintext && !is_child && runparams.openbtUnit)
1757 os << "\\end{btUnit}\n";
1759 // if "auto end" is switched off, explicitly close the language at the end
1760 // but only if the last par is in a babel or polyglossia language
1761 Language const * const lastpar_language =
1762 paragraphs.at(lastpit).getParLanguage(bparams);
1763 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1764 lastpar_language->encoding()->package() != Encoding::CJK) {
1765 os << from_utf8(subst(lang_end_command,
1769 // If we have language_auto_begin, the stack will
1770 // already be empty, nothing to pop()
1771 if (using_begin_end && !lyxrc.language_auto_begin)
1775 // If the last paragraph is an environment, we'll have to close
1776 // CJK at the very end to do proper nesting.
1777 if (maintext && !is_child && state->open_encoding_ == CJK) {
1778 os << "\\clearpage\n\\end{CJK}\n";
1779 state->open_encoding_ = none;
1781 // Likewise for polyglossia or when using begin/end commands
1782 // or at the very end of an active branch inset with a language switch
1783 Language const * const outer_language = (runparams.local_font != nullptr)
1784 ? runparams.local_font->language() : bparams.language;
1785 string const & prev_lang = runparams.use_polyglossia
1786 ? getPolyglossiaEnvName(outer_language)
1787 : outer_language->babel();
1788 string const lastpar_lang = runparams.use_polyglossia ?
1789 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1790 string const & cur_lang = openLanguageName(state);
1791 if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1792 || (maintext && !is_child)) && !cur_lang.empty()) {
1793 os << from_utf8(subst(lang_end_command,
1797 if (using_begin_end)
1799 } else if (runparams.inbranch && !using_begin_end
1800 && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1801 // with !using_begin_end, cur_lang is empty, so we need to
1802 // compare against the paragraph language (and we are in the
1803 // last paragraph at this point)
1804 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1807 // reset inherited encoding
1808 if (state->cjk_inherited_ > 0) {
1809 state->cjk_inherited_ -= 1;
1810 if (state->cjk_inherited_ == 0)
1811 state->open_encoding_ = CJK;
1814 if (multibib_child && mparams.useBibtopic()) {
1815 os << "\\end{btUnit}\n";
1816 runparams.openbtUnit = false;
1820 // Switch the input encoding for some part(s) of the document.
1821 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1822 OutputParams const & runparams, Encoding const & newEnc,
1823 bool force, bool noswitchmacro)
1825 // Never switch encoding with XeTeX/LuaTeX
1826 // or if we're in a moving argument or inherit the outer encoding.
1827 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1828 return make_pair(false, 0);
1830 // Only switch for auto-selected legacy encodings (inputenc setting
1831 // "auto-legacy" or "auto-legacy-plain").
1832 // The "listings" environment can force a switch also with other
1833 // encoding settings (it does not support variable width encodings
1834 // (utf8, jis, ...) under 8-bit latex engines).
1835 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1836 || runparams.moving_arg))
1837 return make_pair(false, 0);
1839 Encoding const & oldEnc = *runparams.encoding;
1840 // Do not switch, if the encoding is unchanged or switching is not supported.
1841 if (oldEnc.name() == newEnc.name()
1842 || oldEnc.package() == Encoding::japanese
1843 || oldEnc.package() == Encoding::none
1844 || newEnc.package() == Encoding::none
1845 || (runparams.for_searchAdv != OutputParams::NoSearch))
1846 return make_pair(false, 0);
1847 // FIXME We ignore encoding switches from/to encodings that do
1848 // neither support the inputenc package nor the CJK package here.
1849 // This may fail for characters not supported by "unicodesymbols"
1850 // or for non-ASCII characters in "listings"
1851 // but it is the best we can do.
1854 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1855 << oldEnc.name() << " to " << newEnc.name());
1856 os << setEncoding(newEnc.iconvName());
1857 if (bparams.inputenc == "auto-legacy-plain")
1858 return make_pair(true, 0);
1860 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1861 OutputState * state = getOutputState();
1862 switch (newEnc.package()) {
1863 case Encoding::none:
1864 case Encoding::japanese:
1865 // shouldn't ever reach here (see above) but avoids warning.
1866 return make_pair(true, 0);
1867 case Encoding::inputenc: {
1868 size_t count = inputenc_arg.length();
1869 if (oldEnc.package() == Encoding::CJK &&
1870 state->open_encoding_ == CJK) {
1872 state->open_encoding_ = none;
1875 else if (oldEnc.package() == Encoding::inputenc &&
1876 state->open_encoding_ == inputenc) {
1878 state->open_encoding_ = none;
1881 if (runparams.local_font != nullptr
1882 && oldEnc.package() == Encoding::CJK) {
1883 // within insets, \inputenc switches need
1884 // to be embraced within \bgroup...\egroup;
1888 state->open_encoding_ = inputenc;
1891 return make_pair(true, count);
1892 os << "\\inputencoding{" << inputenc_arg << '}';
1893 return make_pair(true, count + 16);
1895 case Encoding::CJK: {
1896 size_t count = inputenc_arg.length();
1897 if (oldEnc.package() == Encoding::CJK &&
1898 state->open_encoding_ == CJK) {
1902 if (oldEnc.package() == Encoding::inputenc &&
1903 state->open_encoding_ == inputenc) {
1907 os << "\\begin{CJK}{"
1908 << from_ascii(newEnc.latexName()) << "}{"
1909 << from_ascii(bparams.fonts_cjk) << "}";
1910 state->open_encoding_ = CJK;
1911 return make_pair(true, count + 15);
1914 // Dead code to avoid a warning:
1915 return make_pair(true, 0);