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 ParagraphList::const_iterator const priorpit =
189 pit == paragraphs.begin() ? pit : prev(pit, 1);
191 OutputState * state = getOutputState();
192 bool const use_prev_env_language = state->prev_env_language_ != nullptr
193 && priorpit->layout().isEnvironment()
194 && (priorpit->getDepth() > pit->getDepth()
195 || (priorpit->getDepth() == pit->getDepth()
196 && priorpit->layout() != pit->layout()));
198 data.prev_encoding = runparams.encoding;
199 data.par_language = pit->getParLanguage(bparams);
200 Language const * const doc_language = bparams.language;
201 Language const * const prev_par_language =
202 (pit != paragraphs.begin())
203 ? (use_prev_env_language ? state->prev_env_language_
204 : priorpit->getParLanguage(bparams))
207 bool const use_polyglossia = runparams.use_polyglossia;
208 string const par_lang = use_polyglossia ?
209 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
210 string const prev_par_lang = use_polyglossia ?
211 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
212 string const doc_lang = use_polyglossia ?
213 getPolyglossiaEnvName(doc_language) : doc_language->babel();
214 string const lang_begin_command = use_polyglossia ?
215 "\\begin{$$lang}" : lyxrc.language_command_begin;
216 string const lang_end_command = use_polyglossia ?
217 "\\end{$$lang}" : lyxrc.language_command_end;
218 bool const using_begin_end = use_polyglossia ||
219 !lang_end_command.empty();
221 // For polyglossia, switch language outside of environment, if possible.
222 if (par_lang != prev_par_lang) {
223 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
224 !lang_end_command.empty() &&
225 prev_par_lang != doc_lang &&
226 !prev_par_lang.empty()) {
227 os << from_ascii(subst(
231 // the '%' is necessary to prevent unwanted whitespace
237 // If no language was explicitly opened and we are using
238 // polyglossia or begin/end commands, then the current
239 // language is the document language.
240 string const & cur_lang = using_begin_end
241 && !state->lang_switch_depth_.empty()
242 ? openLanguageName(state)
245 if ((lang_end_command.empty() ||
246 par_lang != doc_lang ||
247 par_lang != cur_lang) &&
249 string bc = use_polyglossia ?
250 getPolyglossiaBegin(lang_begin_command, par_lang,
251 data.par_language->polyglossiaOpts())
252 : subst(lang_begin_command, "$$lang", par_lang);
254 // the '%' is necessary to prevent unwanted whitespace
257 pushLanguageName(par_lang);
261 data.leftindent_open = false;
262 if (!pit->params().leftIndent().zero()) {
263 os << "\\begin{LyXParagraphLeftIndent}{"
264 << from_ascii(pit->params().leftIndent().asLatexString())
266 data.leftindent_open = true;
269 if (style.isEnvironment())
270 state->nest_level_ += 1;
272 if (style.isEnvironment() && !style.latexname().empty()) {
273 os << "\\begin{" << from_ascii(style.latexname()) << '}';
274 if (!style.latexargs().empty()) {
275 OutputParams rp = runparams;
276 rp.local_font = &pit->getFirstFontSettings(bparams);
277 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
279 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
281 << pit->params().labelWidthString()
283 } else if (style.labeltype == LABEL_BIBLIO) {
284 if (pit->params().labelWidthString().empty())
285 os << '{' << bibitemWidest(buf, runparams) << "}\n";
288 << pit->params().labelWidthString()
291 os << from_ascii(style.latexparam()) << '\n';
292 if (style.latextype == LATEX_BIB_ENVIRONMENT
293 || style.latextype == LATEX_ITEM_ENVIRONMENT
294 || style.latextype == LATEX_LIST_ENVIRONMENT) {
295 OutputParams rp = runparams;
296 rp.local_font = &pit->getFirstFontSettings(bparams);
297 latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
303 // in multilingual environments, the CJK tags have to be nested properly
304 data.cjk_nested = false;
305 if (!bparams.useNonTeXFonts
306 && (bparams.inputenc == "auto-legacy"
307 || bparams.inputenc == "auto-legacy-plain")
308 && data.par_language->encoding()->package() == Encoding::CJK
309 && state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
310 if (prev_par_language->encoding()->package() == Encoding::CJK) {
311 os << "\\begin{CJK}{"
312 << from_ascii(data.par_language->encoding()->latexName())
313 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
315 state->open_encoding_ = CJK;
316 data.cjk_nested = true;
322 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
323 TeXEnvironmentData const & data)
325 OutputState * state = getOutputState();
326 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
327 if (state->open_encoding_ == CJK && data.cjk_nested) {
328 // We need to close the encoding even if it does not change
329 // to do correct environment nesting
330 os << "\\end{CJK}\n";
331 state->open_encoding_ = none;
334 if (data.style->isEnvironment()) {
336 bool const using_begin_end =
337 runparams.use_polyglossia ||
338 !lyxrc.language_command_end.empty();
339 // Close any language opened at this nest level
340 if (using_begin_end) {
341 while (langOpenedAtThisLevel(state)) {
342 if (isLocalSwitch(state)) {
346 << openLanguageName(state)
352 if (data.style->latextype == LATEX_BIB_ENVIRONMENT)
353 // bibliography needs a blank line after
354 // each item for backref to function properly
357 state->nest_level_ -= 1;
358 string const & name = data.style->latexname();
360 os << "\\end{" << from_ascii(name) << "}\n";
361 state->prev_env_language_ = data.par_language;
362 if (runparams.encoding != data.prev_encoding) {
363 runparams.encoding = data.prev_encoding;
364 os << setEncoding(data.prev_encoding->iconvName());
368 if (data.leftindent_open) {
369 os << breakln << "\\end{LyXParagraphLeftIndent}\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());
377 // Check whether we should output a blank line after the environment
378 if (!data.style->nextnoindent)
383 void TeXEnvironment(Buffer const & buf, Text const & text,
384 OutputParams const & runparams,
385 pit_type & pit, otexstream & os)
387 ParagraphList const & paragraphs = text.paragraphs();
388 ParagraphList::const_iterator ipar = paragraphs.iterator_at(pit);
389 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
391 Layout const & current_layout = ipar->layout();
392 depth_type const current_depth = ipar->params().depth();
393 Length const & current_left_indent = ipar->params().leftIndent();
395 // This is for debugging purpose at the end.
396 pit_type const par_begin = pit;
397 for (; pit < runparams.par_end; ++pit) {
398 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
400 // check first if this is an higher depth paragraph.
401 bool go_out = (par->params().depth() < current_depth);
402 if (par->params().depth() == current_depth) {
403 // This environment is finished.
404 go_out |= (par->layout() != current_layout);
405 go_out |= (par->params().leftIndent() != current_left_indent);
408 // nothing to do here, restore pit and go out.
413 if (par->layout() == current_layout
414 && par->params().depth() == current_depth
415 && par->params().leftIndent() == current_left_indent) {
416 // We are still in the same environment so TeXOnePar and continue;
417 TeXOnePar(buf, text, pit, os, runparams);
421 // We are now in a deeper environment.
422 // Either par->layout() != current_layout
423 // Or par->params().depth() > current_depth
424 // Or par->params().leftIndent() != current_left_indent)
426 // FIXME This test should not be necessary.
427 // We should perhaps issue an error if it is.
428 bool const force_plain_layout = text.inset().forcePlainLayout();
429 Layout const & style = force_plain_layout
430 ? buf.params().documentClass().plainLayout()
433 if (!style.isEnvironment()) {
434 // This is a standard paragraph, no need to call TeXEnvironment.
435 TeXOnePar(buf, text, pit, os, runparams);
439 // Do not output empty environments if the whole paragraph has
440 // been deleted with ct and changes are not output.
442 if (runparams.for_searchAdv == OutputParams::NoSearch)
443 output_changes = buf.params().output_changes;
445 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
446 if (size_t(pit + 1) < paragraphs.size()) {
447 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
448 Paragraph const & cpar = paragraphs.at(pit);
449 if ((par->layout() != nextpar->layout()
450 || par->params().depth() == nextpar->params().depth()
451 || par->params().leftIndent() == nextpar->params().leftIndent())
453 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
454 if (!output_changes && !cpar.parEndChange().deleted())
460 // This is a new environment.
461 TeXEnvironmentData const data =
462 prepareEnvironment(buf, text, par, os, runparams);
463 // Recursive call to TeXEnvironment!
464 TeXEnvironment(buf, text, runparams, pit, os);
465 finishEnvironment(os, runparams, data);
468 if (pit != runparams.par_end)
469 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
473 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
474 map<size_t, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
476 size_t const argnr = latexargs.size();
480 // Default and preset args are always output, so if they require
481 // other arguments, consider this.
482 for (auto const & larg : latexargs) {
483 Layout::latexarg const & arg = larg.second;
484 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.required.empty()) {
485 vector<string> req = getVectorFromString(arg.required);
486 required.insert(required.end(), req.begin(), req.end());
490 for (size_t i = 1; i <= argnr; ++i) {
491 map<size_t, InsetArgument const *>::const_iterator lit = ilist.find(i);
492 bool inserted = false;
493 if (lit != ilist.end()) {
494 InsetArgument const * ins = lit->second;
496 Layout::LaTeXArgMap::const_iterator const lait =
497 latexargs.find(ins->name());
498 if (lait != latexargs.end()) {
499 Layout::latexarg arg = lait->second;
503 ldelim = arg.mandatory ?
504 from_ascii("{") : from_ascii("[");
505 rdelim = arg.mandatory ?
506 from_ascii("}") : from_ascii("]");
508 if (!arg.ldelim.empty())
510 if (!arg.rdelim.empty())
512 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
513 if (prefix == "listpreamble:")
520 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
521 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
522 for (; lait != laend; ++lait) {
523 string const name = prefix + convert<string>(i);
524 if ((*lait).first == name) {
525 Layout::latexarg arg = (*lait).second;
526 docstring preset = arg.presetarg;
527 if (!arg.defaultarg.empty()) {
530 preset += arg.defaultarg;
533 docstring ldelim = arg.ldelim.empty() ?
534 from_ascii("{") : arg.ldelim;
535 docstring rdelim = arg.rdelim.empty() ?
536 from_ascii("}") : arg.rdelim;
537 os << ldelim << preset << rdelim;
538 } else if (!preset.empty()) {
539 docstring ldelim = arg.ldelim.empty() ?
540 from_ascii("[") : arg.ldelim;
541 docstring rdelim = arg.rdelim.empty() ?
542 from_ascii("]") : arg.rdelim;
543 os << ldelim << preset << rdelim;
544 } else if (find(required.begin(), required.end(),
545 (*lait).first) != required.end()) {
546 docstring ldelim = arg.ldelim.empty() ?
547 from_ascii("[") : arg.ldelim;
548 docstring rdelim = arg.rdelim.empty() ?
549 from_ascii("]") : arg.rdelim;
550 os << ldelim << rdelim;
557 if ((runparams.for_searchAdv != OutputParams::NoSearch) && argnr > 1) {
558 // Mark end of arguments for findadv() only
559 os << "\\endarguments{}";
567 void pushLanguageName(string const & lang_name, bool localswitch)
569 OutputState * state = getOutputState();
571 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
572 state->lang_switch_depth_.push(nest_level);
573 state->open_polyglossia_lang_.push(lang_name);
577 void popLanguageName()
579 OutputState * state = getOutputState();
581 state->lang_switch_depth_.pop();
582 state->open_polyglossia_lang_.pop();
586 string const & openLanguageName()
588 OutputState * state = getOutputState();
590 return openLanguageName(state);
596 void addArgInsets(Paragraph const & par, string const & prefix,
597 Layout::LaTeXArgMap const & latexargs,
598 map<size_t, InsetArgument const *> & ilist,
599 vector<string> & required)
601 for (auto const & table : par.insetList()) {
602 InsetArgument const * arg = table.inset->asInsetArgument();
605 if (arg->name().empty()) {
606 LYXERR0("Error: Unnamed argument inset!");
609 string const name = prefix.empty() ?
610 arg->name() : split(arg->name(), ':');
611 size_t const nr = convert<size_t>(name);
612 ilist.insert({nr, arg});
613 Layout::LaTeXArgMap::const_iterator const lit =
614 latexargs.find(arg->name());
615 if (lit != latexargs.end()) {
616 Layout::latexarg const & larg = lit->second;
617 vector<string> req = getVectorFromString(larg.required);
618 move(req.begin(), req.end(), back_inserter(required));
626 void latexArgInsets(Paragraph const & par, otexstream & os,
627 OutputParams const & runparams,
628 Layout::LaTeXArgMap const & latexargs,
629 string const & prefix)
631 map<size_t, InsetArgument const *> ilist;
632 vector<string> required;
633 addArgInsets(par, prefix, latexargs, ilist, required);
634 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
638 void latexArgInsets(ParagraphList const & pars,
639 ParagraphList::const_iterator pit,
640 otexstream & os, OutputParams const & runparams,
641 Layout::LaTeXArgMap const & latexargs,
642 string const & prefix)
644 map<size_t, InsetArgument const *> ilist;
645 vector<string> required;
647 depth_type const current_depth = pit->params().depth();
648 Layout const current_layout = pit->layout();
650 // get the first paragraph in sequence with this layout and depth
651 ptrdiff_t offset = 0;
653 if (prev(pit, offset) == pars.begin())
655 ParagraphList::const_iterator priorpit = prev(pit, offset + 1);
656 if (priorpit->layout() == current_layout
657 && priorpit->params().depth() == current_depth)
663 ParagraphList::const_iterator spit = prev(pit, offset);
664 for (; spit != pars.end(); ++spit) {
665 if (spit->layout() != current_layout ||
666 spit->params().depth() < current_depth)
668 if (spit->params().depth() > current_depth)
670 addArgInsets(*spit, prefix, latexargs, ilist, required);
672 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
676 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
677 OutputParams const & runparams,
678 Layout::LaTeXArgMap const & latexargs,
679 string const & prefix)
681 map<size_t, InsetArgument const *> ilist;
682 vector<string> required;
684 for (Paragraph const & par : pars) {
685 if (par.layout().hasArgs())
686 // The InsetArguments inside this paragraph refer to this paragraph
688 addArgInsets(par, prefix, latexargs, ilist, required);
690 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
696 // output the proper paragraph start according to latextype.
697 void parStartCommand(Paragraph const & par, otexstream & os,
698 OutputParams const & runparams, Layout const & style)
700 switch (style.latextype) {
702 if (par.needsCProtection(runparams.moving_arg)) {
703 if (contains(runparams.active_chars, '^'))
704 // cprotect relies on ^ being on catcode 7
705 os << "\\begingroup\\catcode`\\^=7";
708 os << '\\' << from_ascii(style.latexname());
711 if (!style.latexargs().empty())
712 latexArgInsets(par, os, runparams, style.latexargs());
713 os << from_ascii(style.latexparam());
715 case LATEX_ITEM_ENVIRONMENT:
716 case LATEX_LIST_ENVIRONMENT:
717 if (runparams.for_searchAdv != OutputParams::NoSearch) {
718 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
721 os << "\\" + style.itemcommand();
723 if (!style.itemargs().empty())
724 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
728 case LATEX_ENVIRONMENT:
729 if (runparams.for_searchAdv != OutputParams::NoSearch) {
730 os << "\\latexenvironment{" << style.latexname() << "}{";
733 case LATEX_BIB_ENVIRONMENT:
734 // ignore this, the inset will write itself
743 // FIXME: this should be anonymous
744 void TeXOnePar(Buffer const & buf,
748 OutputParams const & runparams_in,
749 string const & everypar,
750 int start_pos, int end_pos,
753 BufferParams const & bparams = runparams_in.is_child
754 ? buf.masterParams() : buf.params();
755 ParagraphList const & paragraphs = text.paragraphs();
756 Paragraph const & par = paragraphs.at(pit);
757 // FIXME This check should not really be needed.
758 // Perhaps we should issue an error if it is.
759 Layout const & style = text.inset().forcePlainLayout() ?
760 bparams.documentClass().plainLayout() : par.layout();
762 if (style.inpreamble && !force)
765 // Do not output empty commands if the whole paragraph has
766 // been deleted with ct and changes are not output.
767 if ((runparams_in.for_searchAdv != OutputParams::SearchWithDeleted) && style.latextype != LATEX_ENVIRONMENT
768 && !par.empty() && par.isDeleted(0, par.size()) && !bparams.output_changes)
771 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
774 OutputParams runparams = runparams_in;
775 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
776 // We reinitialize par begin and end to be on the safe side
777 // with embedded inset as we don't know if they set those
779 runparams.par_begin = 0;
780 runparams.par_end = 0;
782 bool const maintext = text.isMainText();
783 // we are at the beginning of an inset and CJK is already open;
784 // we count inheritation levels to get the inset nesting right.
785 OutputState * state = getOutputState();
786 if (pit == 0 && !maintext
787 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
788 state->cjk_inherited_ += 1;
789 state->open_encoding_ = none;
792 // This paragraph is merged and we do not show changes in the output
793 bool const merged_par = !bparams.output_changes && par.parEndChange().deleted();
795 if (text.inset().isPassThru()) {
796 Font const outerfont = text.outerFont(pit);
798 // No newline before first paragraph in this lyxtext
799 if (pit > 0 && !text.inset().getLayout().parbreakIgnored() && !merged_par) {
801 if (!text.inset().getLayout().parbreakIsNewline())
805 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
809 Paragraph const * nextpar = runparams.isLastPar
810 ? nullptr : ¶graphs.at(pit + 1);
812 bool const intitle_command = style.intitle && style.isCommand();
813 // Intitle commands switch languages locally, thus increase
814 // language nesting level
816 state->nest_level_ += 1;
818 if (style.pass_thru) {
819 Font const outerfont = text.outerFont(pit);
820 parStartCommand(par, os, runparams, style);
821 if (style.isCommand() && style.needprotect)
822 // Due to the moving argument, some fragile
823 // commands (labels, index entries)
824 // are output after this command (#2154)
825 runparams.postpone_fragile_stuff =
826 bparams.postpone_fragile_content;
830 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
832 // I did not create a parEndCommand for this minuscule
833 // task because in the other user of parStartCommand
834 // the code is different (JMarc)
835 if (style.isCommand()) {
837 if (par.needsCProtection(runparams.moving_arg)
838 && contains(runparams.active_chars, '^'))
845 else if (!merged_par)
847 if (!style.parbreak_is_newline && !merged_par) {
849 } else if (nextpar && !style.isEnvironment()) {
850 Layout const nextstyle = text.inset().forcePlainLayout()
851 ? bparams.documentClass().plainLayout()
853 if (nextstyle.name() != style.name() && !merged_par)
860 // This paragraph's language
861 Language const * const par_language = par.getParLanguage(bparams);
862 Language const * const nextpar_language = nextpar ?
863 nextpar->getParLanguage(bparams) : nullptr;
864 // The document's language
865 Language const * const doc_language = bparams.language;
866 // The language that was in effect when the environment this paragraph is
867 // inside of was opened
868 Language const * const outer_language =
869 (runparams.local_font != nullptr) ?
870 runparams.local_font->language() : doc_language;
872 Paragraph const * priorpar = (pit == 0) ? nullptr : ¶graphs.at(pit - 1);
874 // The previous language that was in effect is the language of the
875 // previous paragraph, unless the previous paragraph is inside an
876 // environment with nesting depth greater than (or equal to, but with
877 // a different layout) the current one. If there is no previous
878 // paragraph, the previous language is the outer language.
879 // Note further that we take the outer language also if the prior par
880 // is PassThru, since in that case it has latex_language, and all secondary
881 // languages have been closed (#10793).
882 bool const use_prev_env_language = state->prev_env_language_ != nullptr
884 && priorpar->layout().isEnvironment()
885 && (priorpar->getDepth() > par.getDepth()
886 || (priorpar->getDepth() == par.getDepth()
887 && priorpar->layout() != par.layout()));
889 // We need to ignore previous intitle commands since languages
890 // are switched locally there (# 11514)
891 // There might be paragraphs before the title, so we check this.
892 Paragraph * prior_nontitle_par = nullptr;
893 if (!intitle_command) {
897 Paragraph const * tmppar = ¶graphs.at(ppit);
898 if (tmppar->layout().intitle && tmppar->layout().isCommand())
900 prior_nontitle_par = const_cast<Paragraph*>(tmppar);
904 Language const * const prev_language =
905 runparams_in.for_searchAdv != OutputParams::NoSearch
906 ? languages.getLanguage("ignore")
907 : (prior_nontitle_par && !prior_nontitle_par->isPassThru())
908 ? (use_prev_env_language
909 ? state->prev_env_language_
910 : prior_nontitle_par->getParLanguage(bparams))
913 bool const use_polyglossia = runparams.use_polyglossia;
914 string const par_lang = use_polyglossia ?
915 getPolyglossiaEnvName(par_language): par_language->babel();
916 string const prev_lang = use_polyglossia ?
917 getPolyglossiaEnvName(prev_language) : prev_language->babel();
918 string const outer_lang = use_polyglossia ?
919 getPolyglossiaEnvName(outer_language) : outer_language->babel();
920 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
921 getPolyglossiaEnvName(nextpar_language) :
922 nextpar_language->babel()) : string();
923 string lang_begin_command = use_polyglossia ?
924 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
925 string lang_end_command = use_polyglossia ?
926 "\\end{$$lang}" : lyxrc.language_command_end;
927 // the '%' is necessary to prevent unwanted whitespace
928 string lang_command_termination = "%\n";
929 bool const using_begin_end = use_polyglossia ||
930 !lang_end_command.empty();
932 // For InTitle commands, we need to switch the language inside the command
933 // (see #10849); thus open the command here.
934 if (intitle_command) {
935 parStartCommand(par, os, runparams, style);
936 if (style.isCommand() && style.needprotect)
937 // Due to the moving argument, some fragile
938 // commands (labels, index entries)
939 // are output after this command (#2154)
940 runparams.postpone_fragile_stuff =
941 bparams.postpone_fragile_content;
945 // In some insets (such as Arguments), we cannot use \selectlanguage.
946 // Also, if an RTL language is set via environment in polyglossia,
947 // only a nested \\text<lang> command will reset the direction for LTR
948 // languages (see # 10111).
949 bool const in_polyglossia_rtl_env =
951 && runparams.local_font != nullptr
952 && outer_language->rightToLeft()
953 && !par_language->rightToLeft();
954 bool const localswitch =
955 (runparams_in.for_searchAdv != OutputParams::NoSearch
956 || text.inset().forceLocalFontSwitch()
957 || (using_begin_end && text.inset().forcePlainLayout())
958 || in_polyglossia_rtl_env)
959 && !text.inset().forceParDirectionSwitch();
961 lang_begin_command = use_polyglossia ?
962 "\\text$$lang$$opts{" : lyxrc.language_command_local;
963 lang_end_command = "}";
964 lang_command_termination.clear();
967 bool const localswitch_needed = localswitch && par_lang != outer_lang;
969 // localswitches need to be closed and reopened at each par
970 if ((runparams_in.for_searchAdv != OutputParams::NoSearch) || ((par_lang != prev_lang || localswitch_needed)
971 // check if we already put language command in TeXEnvironment()
972 && !(style.isEnvironment()
973 && (pit == 0 || (priorpar->layout() != par.layout()
974 && priorpar->getDepth() <= par.getDepth())
975 || priorpar->getDepth() < par.getDepth())))) {
977 && (!using_begin_end || langOpenedAtThisLevel(state))
978 && !lang_end_command.empty()
979 && prev_lang != outer_lang
980 && !prev_lang.empty()
981 && (!using_begin_end || !style.isEnvironment())) {
982 os << from_ascii(subst(lang_end_command,
985 << lang_command_termination;
990 // We need to open a new language if we couldn't close the previous
991 // one (because there's no language_command_end); and even if we closed
992 // the previous one, if the current language is different than the
993 // outer_language (which is currently in effect once the previous one
995 if ((lang_end_command.empty() || par_lang != outer_lang
997 || (style.isEnvironment() && par_lang != prev_lang)))
998 && !par_lang.empty()) {
999 // If we're inside an inset, and that inset is within an \L or \R
1000 // (or equivalents), then within the inset, too, any opposite
1001 // language paragraph should appear within an \L or \R (in addition
1002 // to, outside of, the normal language switch commands).
1003 // This behavior is not correct for ArabTeX, though.
1004 if (!using_begin_end
1006 && par_language->lang() != "arabic_arabtex"
1007 && outer_language->lang() != "arabic_arabtex"
1008 // are we in an inset?
1009 && runparams.local_font != nullptr
1010 // is the inset within an \L or \R?
1012 // FIXME: currently, we don't check this; this means that
1013 // we'll have unnnecessary \L and \R commands, but that
1014 // doesn't seem to hurt (though latex will complain)
1016 // is this paragraph in the opposite direction?
1017 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
1018 // FIXME: I don't have a working copy of the Arabi package, so
1019 // I'm not sure if the farsi and arabic_arabi stuff is correct
1021 if (par_language->lang() == "farsi")
1023 else if (outer_language->lang() == "farsi")
1025 else if (par_language->lang() == "arabic_arabi")
1027 else if (outer_language->lang() == "arabic_arabi")
1029 // remaining RTL languages currently is hebrew
1030 else if (par_language->rightToLeft())
1035 // With CJK, the CJK tag has to be closed first (see below)
1036 if ((runparams.encoding->package() != Encoding::CJK
1037 || bparams.useNonTeXFonts
1038 || (runparams.for_searchAdv != OutputParams::NoSearch))
1039 && (par_lang != openLanguageName(state) || localswitch || intitle_command)
1040 && !par_lang.empty()) {
1041 string bc = use_polyglossia ?
1042 getPolyglossiaBegin(lang_begin_command, par_lang,
1043 par_language->polyglossiaOpts(),
1045 : subst(lang_begin_command, "$$lang", par_lang);
1047 os << lang_command_termination;
1048 if (using_begin_end)
1049 pushLanguageName(par_lang, localswitch);
1054 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
1055 // encoding, since this only affects the position of the outputted
1056 // \inputencoding command; the encoding switch will occur when necessary
1057 if (bparams.inputenc == "auto-legacy"
1058 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
1059 && runparams.encoding->package() != Encoding::japanese
1060 && runparams.encoding->package() != Encoding::none) {
1061 // Look ahead for future encoding changes.
1062 // We try to output them at the beginning of the paragraph,
1063 // since the \inputencoding command is not allowed e.g. in
1064 // sections. For this reason we only set runparams.moving_arg
1065 // after checking for the encoding change, otherwise the
1066 // change would be always avoided by switchEncoding().
1067 for (pos_type i = 0; i < par.size(); ++i) {
1068 char_type const c = par.getChar(i);
1069 Encoding const * const encoding =
1070 par.getFontSettings(bparams, i).language()->encoding();
1071 if (encoding->package() != Encoding::CJK
1072 && runparams.encoding->package() == Encoding::inputenc
1077 // All characters before c are in the ASCII range, and
1078 // c is non-ASCII (but no inset), so change the
1079 // encoding to that required by the language of c.
1080 // With CJK, only add switch if we have CJK content at the beginning
1082 if (i != 0 && encoding->package() == Encoding::CJK)
1085 pair<bool, int> enc_switch = switchEncoding(os.os(),
1086 bparams, runparams, *encoding);
1087 // the following is necessary after a CJK environment in a multilingual
1088 // context (nesting issue).
1089 if (par_language->encoding()->package() == Encoding::CJK
1090 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1091 os << "\\begin{CJK}{"
1092 << from_ascii(par_language->encoding()->latexName())
1093 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1094 state->open_encoding_ = CJK;
1096 if (encoding->package() != Encoding::none && enc_switch.first) {
1097 if (enc_switch.second > 0) {
1098 // the '%' is necessary to prevent unwanted whitespace
1101 // With CJK, the CJK tag had to be closed first (see above)
1102 if (runparams.encoding->package() == Encoding::CJK
1103 && par_lang != openLanguageName(state)
1104 && !par_lang.empty()) {
1105 os << subst(lang_begin_command, "$$lang", par_lang)
1106 << lang_command_termination;
1107 if (using_begin_end)
1108 pushLanguageName(par_lang, localswitch);
1110 runparams.encoding = encoding;
1116 runparams.moving_arg |= style.needprotect;
1117 if (style.needmboxprotect)
1118 ++runparams.inulemcmd;
1119 Encoding const * const prev_encoding = runparams.encoding;
1121 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1122 if (par.allowParagraphCustomization()) {
1123 if (par.params().startOfAppendix()) {
1124 os << "\n\\appendix\n";
1127 // InTitle commands must use switches (not environments)
1128 // inside the commands (see #9332)
1129 if (style.intitle) {
1130 if (!par.params().spacing().isDefault())
1132 if (runparams.moving_arg)
1134 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1137 if (!par.params().spacing().isDefault()
1138 && (pit == 0 || !priorpar->hasSameLayout(par)))
1140 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1144 if (style.isCommand()) {
1150 // For InTitle commands, we already started the command before
1151 // the language switch
1152 if (!intitle_command) {
1153 parStartCommand(par, os, runparams, style);
1154 if (style.isCommand() && style.needprotect)
1155 // Due to the moving argument, some fragile
1156 // commands (labels, index entries)
1157 // are output after this command (#2154)
1158 runparams.postpone_fragile_stuff =
1159 bparams.postpone_fragile_content;
1162 Font const outerfont = text.outerFont(pit);
1165 os << from_utf8(everypar);
1166 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1168 Font const font = par.empty()
1169 ? par.getLayoutFont(bparams, outerfont)
1170 : par.getFont(bparams, par.size() - 1, outerfont);
1172 bool const is_command = style.isCommand();
1174 // InTitle commands need to be closed after the language has been closed.
1175 if (!intitle_command) {
1178 if (!style.postcommandargs().empty())
1179 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1180 if (!runparams.post_macro.empty()) {
1181 // Output the stored fragile commands (labels, indices etc.)
1182 // that need to be output after the command with moving argument.
1183 os << runparams.post_macro;
1184 runparams.post_macro.clear();
1186 if (par.needsCProtection(runparams.moving_arg)
1187 && contains(runparams.active_chars, '^'))
1189 if (runparams.encoding != prev_encoding) {
1190 runparams.encoding = prev_encoding;
1191 os << setEncoding(prev_encoding->iconvName());
1196 bool pending_newline = false;
1197 bool unskip_newline = false;
1198 bool close_lang_switch = false;
1199 switch (style.latextype) {
1200 case LATEX_ITEM_ENVIRONMENT:
1201 case LATEX_LIST_ENVIRONMENT:
1202 if ((nextpar && par_lang != nextpar_lang
1203 && nextpar->getDepth() == par.getDepth())
1204 || (atSameLastLangSwitchDepth(state) && nextpar
1205 && nextpar->getDepth() < par.getDepth()))
1206 close_lang_switch = using_begin_end;
1207 if (nextpar && par.params().depth() < nextpar->params().depth())
1208 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1210 case LATEX_ENVIRONMENT: {
1211 // if it's the last paragraph of the current environment
1212 // skip it otherwise fall through
1214 && ((nextpar->layout() != par.layout()
1215 || nextpar->params().depth() != par.params().depth())
1216 || (!using_begin_end || par_lang != nextpar_lang)))
1218 close_lang_switch = using_begin_end;
1225 // we don't need it for the last paragraph and in InTitle commands!!!
1226 if (nextpar && !intitle_command)
1227 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1230 // InTitle commands use switches (not environments) for space settings
1231 if (par.allowParagraphCustomization() && !style.intitle) {
1232 if (!par.params().spacing().isDefault()
1233 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1234 if (pending_newline)
1237 string const endtag =
1238 par.params().spacing().writeEnvirEnd(useSetSpace);
1239 if (prefixIs(endtag, "\\end{"))
1242 os << from_ascii(endtag);
1243 pending_newline = true;
1247 // Closing the language is needed for the last paragraph in a given language
1248 // as well as for any InTitleCommand (since these set the language locally);
1249 // it is also needed if we're within an \L or \R that we may have opened above
1250 // (not necessarily in this paragraph) and are about to close.
1251 bool closing_rtl_ltr_environment = !using_begin_end
1253 && (par_language->lang() != "arabic_arabtex"
1254 && outer_language->lang() != "arabic_arabtex")
1255 // have we opened an \L or \R environment?
1256 && runparams.local_font != nullptr
1257 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1258 // are we about to close the language?
1259 &&((nextpar && par_lang != nextpar_lang)
1260 || (runparams.isLastPar && par_lang != outer_lang));
1262 if (localswitch_needed
1263 || (intitle_command && using_begin_end)
1264 || closing_rtl_ltr_environment
1265 || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1266 && (par_lang != outer_lang || (using_begin_end
1267 && style.isEnvironment()
1268 && par_lang != nextpar_lang)))) {
1269 // Since \selectlanguage write the language to the aux file,
1270 // we need to reset the language at the end of footnote or
1273 if (!localswitch && (pending_newline || close_lang_switch))
1276 // when the paragraph uses CJK, the language has to be closed earlier
1277 if ((font.language()->encoding()->package() != Encoding::CJK)
1278 || bparams.useNonTeXFonts
1279 || (runparams_in.for_searchAdv != OutputParams::NoSearch)) {
1280 if (lang_end_command.empty()) {
1281 // If this is a child, we should restore the
1282 // master language after the last paragraph.
1283 Language const * const current_language =
1284 (runparams.isLastPar && runparams.master_language)
1285 ? runparams.master_language
1287 string const current_lang = use_polyglossia
1288 ? getPolyglossiaEnvName(current_language)
1289 : current_language->babel();
1290 if (!current_lang.empty()
1291 && current_lang != openLanguageName(state)) {
1292 string bc = use_polyglossia ?
1293 getPolyglossiaBegin(lang_begin_command, current_lang,
1294 current_language->polyglossiaOpts(),
1296 : subst(lang_begin_command, "$$lang", current_lang);
1298 pending_newline = !localswitch
1299 && !text.inset().getLayout().parbreakIgnored();
1300 unskip_newline = !localswitch;
1301 if (using_begin_end)
1302 pushLanguageName(current_lang, localswitch);
1304 } else if ((!using_begin_end ||
1305 langOpenedAtThisLevel(state)) &&
1306 !par_lang.empty()) {
1307 // If we are in an environment, we have to
1308 // close the "outer" language afterwards
1309 string const & cur_lang = openLanguageName(state);
1310 if (!style.isEnvironment()
1311 || (close_lang_switch
1312 && atSameLastLangSwitchDepth(state)
1313 && par_lang != outer_lang
1314 && (par_lang != cur_lang
1315 || (cur_lang != outer_lang
1317 && style != nextpar->layout())))
1318 || (atSameLastLangSwitchDepth(state)
1319 && !state->lang_switch_depth_.empty()
1320 && cur_lang != par_lang)
1321 || in_polyglossia_rtl_env)
1323 if (using_begin_end && !localswitch)
1325 os << from_ascii(subst(
1329 pending_newline = !localswitch
1330 && !text.inset().getLayout().parbreakIgnored();
1331 unskip_newline = !localswitch;
1332 if (using_begin_end)
1338 if (closing_rtl_ltr_environment)
1341 // InTitle commands need to be closed after the language has been closed.
1342 if (intitle_command) {
1344 if (!style.postcommandargs().empty())
1345 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1346 if (!runparams.post_macro.empty()) {
1347 // Output the stored fragile commands (labels, indices etc.)
1348 // that need to be output after the command with moving argument.
1349 os << runparams.post_macro;
1350 runparams.post_macro.clear();
1352 if (par.needsCProtection(runparams.moving_arg)
1353 && contains(runparams.active_chars, '^'))
1355 if (runparams.encoding != prev_encoding) {
1356 runparams.encoding = prev_encoding;
1357 os << setEncoding(prev_encoding->iconvName());
1361 bool const last_was_separator =
1362 !par.empty() && par.isEnvSeparator(par.size() - 1);
1364 // Signify added/deleted par break in output if show changes in output
1365 if (nextpar && !os.afterParbreak() && !last_was_separator
1366 && bparams.output_changes && par.parEndChange().changed()) {
1367 Changes::latexMarkChange(os, bparams, Change(Change::UNCHANGED),
1368 par.parEndChange(), runparams);
1369 os << bparams.encoding().latexString(docstring(1, 0x00b6)).first << "}";
1372 if (pending_newline) {
1374 // prevent unwanted whitespace
1376 if (!os.afterParbreak() && !last_was_separator)
1380 // if this is a CJK-paragraph and the next isn't, close CJK
1381 // also if the next paragraph is a multilingual environment (because of nesting)
1382 if (nextpar && state->open_encoding_ == CJK
1383 && bparams.encoding().iconvName() != "UTF-8"
1384 && bparams.encoding().package() != Encoding::CJK
1385 && ((nextpar_language &&
1386 nextpar_language->encoding()->package() != Encoding::CJK)
1387 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1388 // inbetween environments, CJK has to be closed later (nesting!)
1389 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1390 os << "\\end{CJK}\n";
1391 state->open_encoding_ = none;
1394 // If this is the last paragraph, close the CJK environment
1395 // if necessary. If it's an environment or nested in an environment,
1396 // we'll have to \end that first.
1397 if (runparams.isLastPar && !style.isEnvironment()
1398 && par.params().depth() < 1) {
1399 switch (state->open_encoding_) {
1401 // do nothing at the end of child documents
1402 if (maintext && buf.masterBuffer() != &buf)
1404 // end of main text: also insert a \clearpage (see #5386)
1406 os << "\n\\clearpage\n\\end{CJK}\n";
1410 state->open_encoding_ = none;
1414 // FIXME: If we are in an inset and the switch happened outside this inset,
1415 // do not switch back at the end of the inset (bug #8479)
1416 // The following attempt does not help with listings-caption in a CJK document:
1417 // if (runparams_in.local_font != 0
1418 // && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1421 state->open_encoding_ = none;
1431 // Information about local language is stored as a font feature.
1432 // If this is the last paragraph of the inset and a local_font was set upon entering
1433 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1434 // ensure the encoding is set back to the default encoding of the local language.
1435 if (runparams.isLastPar && runparams_in.local_font != nullptr
1436 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1437 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1438 && !runparams.isFullUnicode()
1440 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1441 os << setEncoding(runparams_in.encoding->iconvName());
1443 // Otherwise, the current encoding should be set for the next paragraph.
1445 runparams_in.encoding = runparams.encoding;
1447 // Also pass the post_macros upstream
1448 runparams_in.post_macro = runparams.post_macro;
1449 // These need to be passed upstream as well
1450 runparams_in.need_maketitle = runparams.need_maketitle;
1451 runparams_in.have_maketitle = runparams.have_maketitle;
1454 // we don't need a newline for the last paragraph!!!
1455 // Note from JMarc: we will re-add a \n explicitly in
1456 // TeXEnvironment, because it is needed in this case
1457 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1458 if (!text.inset().getLayout().parbreakIgnored() && !merged_par)
1459 // Make sure to start a new line
1461 // A newline '\n' is always output before a command,
1462 // so avoid doubling it.
1463 Layout const & next_layout = nextpar->layout();
1464 if (!next_layout.isCommand()) {
1465 // Here we now try to avoid spurious empty lines by
1466 // outputting a paragraph break only if: (case 1) the
1467 // paragraph style allows parbreaks and no \begin, \end
1468 // or \item tags are going to follow (i.e., if the next
1469 // isn't the first or the current isn't the last
1470 // paragraph of an environment or itemize) and the
1471 // depth and alignment of the following paragraph is
1472 // unchanged, or (case 2) the following is a
1473 // non-environment paragraph whose depth is increased
1474 // but whose alignment is unchanged, or (case 3) the
1475 // paragraph is not an environment and the next one is a
1476 // non-itemize-like env at lower depth, or (case 4) the
1477 // paragraph is a command not followed by an environment
1478 // and the alignment of the current and next paragraph
1479 // is unchanged, or (case 5) the current alignment is
1480 // changed and a standard paragraph follows.
1481 DocumentClass const & tclass = bparams.documentClass();
1482 if ((style == next_layout
1483 && !style.parbreak_is_newline
1484 && !text.inset().getLayout().parbreakIsNewline()
1485 && !text.inset().getLayout().parbreakIgnored()
1486 && style.latextype != LATEX_ITEM_ENVIRONMENT
1487 && style.latextype != LATEX_LIST_ENVIRONMENT
1488 && style.align == par.getAlign(bparams)
1489 && nextpar->getDepth() == par.getDepth()
1490 && nextpar->getAlign(bparams) == par.getAlign(bparams))
1491 || (!next_layout.isEnvironment()
1492 && nextpar->getDepth() > par.getDepth()
1493 && nextpar->getAlign(bparams) == next_layout.align)
1494 || (!style.isEnvironment()
1495 && next_layout.latextype == LATEX_ENVIRONMENT
1496 && nextpar->getDepth() < par.getDepth())
1497 || (style.isCommand()
1498 && !next_layout.isEnvironment()
1499 && style.align == par.getAlign(bparams)
1500 && next_layout.align == nextpar->getAlign(bparams))
1501 || (style.align != par.getAlign(bparams)
1502 && tclass.isDefaultLayout(next_layout))) {
1503 // and omit paragraph break if it has been deleted with ct
1504 // and changes are not shown in output
1506 if (runparams.isNonLong)
1507 // This is to allow parbreak in multirow
1508 // It could also be used for other non-long
1510 os << "\\endgraf\n";
1518 // Reset language nesting level after intitle command
1519 if (intitle_command)
1520 state->nest_level_ -= 1;
1522 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1523 << &par << " next " << nextpar);
1529 // LaTeX all paragraphs
1530 void latexParagraphs(Buffer const & buf,
1533 OutputParams const & runparams,
1534 string const & everypar)
1536 LASSERT(runparams.par_begin <= runparams.par_end,
1537 { os << "% LaTeX Output Error\n"; return; } );
1539 BufferParams const & bparams = buf.params();
1540 BufferParams const & mparams = buf.masterParams();
1542 bool const maintext = text.isMainText();
1543 bool const is_child = buf.masterBuffer() != &buf;
1544 bool const multibib_child = maintext && is_child
1545 && mparams.multibib == "child";
1547 if (multibib_child && mparams.useBiblatex())
1548 os << "\\newrefsection";
1549 else if (multibib_child && mparams.useBibtopic()
1550 && !buf.masterBibInfo().empty()) {
1551 os << "\\begin{btUnit}\n";
1552 runparams.openbtUnit = true;
1555 // Open a CJK environment at the beginning of the main buffer
1556 // if the document's main encoding requires the CJK package
1557 // or the document encoding is utf8 and the CJK package is required
1558 // (but not in child documents or documents using system fonts):
1559 OutputState * state = getOutputState();
1560 if (maintext && !is_child && !bparams.useNonTeXFonts
1561 && (bparams.encoding().package() == Encoding::CJK
1562 || (bparams.encoding().name() == "utf8"
1563 && runparams.use_CJK))
1565 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1566 ? from_ascii("UTF8")
1567 : from_ascii(bparams.encoding().latexName());
1568 os << "\\begin{CJK}{" << cjkenc
1569 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1570 state->open_encoding_ = CJK;
1572 // if "auto begin" is switched off, explicitly switch the
1573 // language on at start
1574 string const mainlang = runparams.use_polyglossia
1575 ? getPolyglossiaEnvName(bparams.language)
1576 : bparams.language->babel();
1577 string const lang_begin_command = runparams.use_polyglossia ?
1578 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1579 string const lang_end_command = runparams.use_polyglossia ?
1580 "\\end{$$lang}" : lyxrc.language_command_end;
1581 bool const using_begin_end = runparams.use_polyglossia ||
1582 !lang_end_command.empty();
1584 if (maintext && !lyxrc.language_auto_begin &&
1585 !mainlang.empty()) {
1587 string bc = runparams.use_polyglossia ?
1588 getPolyglossiaBegin(lang_begin_command, mainlang,
1589 bparams.language->polyglossiaOpts())
1590 : subst(lang_begin_command, "$$lang", mainlang);
1593 if (using_begin_end)
1594 pushLanguageName(mainlang);
1597 ParagraphList const & paragraphs = text.paragraphs();
1599 if (runparams.par_begin == runparams.par_end) {
1600 // The full doc will be exported but it is easier to just rely on
1601 // runparams range parameters that will be passed TeXEnvironment.
1602 runparams.par_begin = 0;
1603 runparams.par_end = static_cast<int>(paragraphs.size());
1606 pit_type pit = runparams.par_begin;
1607 // lastpit is for the language check after the loop.
1608 pit_type lastpit = pit;
1609 DocumentClass const & tclass = bparams.documentClass();
1611 // Did we already warn about inTitle layout mixing? (we only warn once)
1612 bool gave_layout_warning = false;
1613 for (; pit < runparams.par_end; ++pit) {
1615 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
1617 // FIXME This check should not be needed. We should
1618 // perhaps issue an error if it is.
1619 Layout const & layout = text.inset().forcePlainLayout() ?
1620 tclass.plainLayout() : par->layout();
1622 if (layout.intitle) {
1623 if (runparams.have_maketitle) {
1624 if (!gave_layout_warning && !runparams.dryrun) {
1625 gave_layout_warning = true;
1626 frontend::Alert::warning(_("Error in latexParagraphs"),
1627 bformat(_("You are using at least one "
1628 "layout (%1$s) intended for the title, "
1629 "after using non-title layouts. This "
1630 "could lead to missing or incorrect output."
1633 } else if (!runparams.need_maketitle) {
1634 runparams.need_maketitle = true;
1635 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1637 << from_ascii(tclass.titlename())
1641 } else if (runparams.need_maketitle && !runparams.have_maketitle
1642 && !layout.inpreamble && !text.inset().isInTitle()) {
1643 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1644 os << "\\end{" << from_ascii(tclass.titlename())
1648 os << "\\" << from_ascii(tclass.titlename())
1651 runparams.have_maketitle = true;
1652 runparams.need_maketitle = false;
1655 if (layout.isCommand() && !layout.latexname().empty()
1656 && layout.latexname() == bparams.multibib) {
1657 if (runparams.openbtUnit)
1658 os << "\\end{btUnit}\n";
1659 if (!bparams.useBiblatex()
1660 && !buf.masterBibInfo().empty()) {
1661 os << '\n' << "\\begin{btUnit}\n";
1662 runparams.openbtUnit = true;
1666 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1667 // This is a standard top level paragraph, TeX it and continue.
1668 TeXOnePar(buf, text, pit, os, runparams, everypar);
1672 // Do not output empty environments if the whole paragraph has
1673 // been deleted with ct and changes are not output.
1674 bool output_changes;
1675 if (runparams.for_searchAdv == OutputParams::NoSearch)
1676 output_changes = bparams.output_changes;
1678 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
1679 if (size_t(pit + 1) < paragraphs.size()) {
1680 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
1681 Paragraph const & cpar = paragraphs.at(pit);
1682 if ((par->layout() != nextpar->layout()
1683 || par->params().depth() == nextpar->params().depth()
1684 || par->params().leftIndent() == nextpar->params().leftIndent())
1686 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
1687 if (!cpar.parEndChange().deleted())
1692 // This is the last par
1693 Paragraph const & cpar = paragraphs.at(pit);
1695 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
1696 if (!cpar.parEndChange().deleted())
1702 TeXEnvironmentData const data =
1703 prepareEnvironment(buf, text, par, os, runparams);
1704 // pit can be changed in TeXEnvironment.
1705 TeXEnvironment(buf, text, runparams, pit, os);
1706 finishEnvironment(os, runparams, data);
1709 // FIXME: uncomment the content or remove this block
1710 if (pit == runparams.par_end) {
1711 // Make sure that the last paragraph is
1712 // correctly terminated (because TeXOnePar does
1713 // not add a \n in this case)
1717 // It might be that we only have a title in this document.
1718 // But if we're in an inset, this is not the end of
1719 // the document. (There may be some other checks of this
1720 // kind that are needed.)
1721 if (runparams.need_maketitle && !runparams.have_maketitle && maintext) {
1722 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1723 os << "\\end{" << from_ascii(tclass.titlename())
1726 os << "\\" << from_ascii(tclass.titlename())
1731 if (maintext && !is_child && runparams.openbtUnit)
1732 os << "\\end{btUnit}\n";
1734 // if "auto end" is switched off, explicitly close the language at the end
1735 // but only if the last par is in a babel or polyglossia language
1736 Language const * const lastpar_language =
1737 paragraphs.at(lastpit).getParLanguage(bparams);
1738 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1739 lastpar_language->encoding()->package() != Encoding::CJK) {
1740 os << from_utf8(subst(lang_end_command,
1744 // If we have language_auto_begin, the stack will
1745 // already be empty, nothing to pop()
1746 if (using_begin_end && !lyxrc.language_auto_begin)
1750 // If the last paragraph is an environment, we'll have to close
1751 // CJK at the very end to do proper nesting.
1752 if (maintext && !is_child && state->open_encoding_ == CJK) {
1753 os << "\\clearpage\n\\end{CJK}\n";
1754 state->open_encoding_ = none;
1756 // Likewise for polyglossia or when using begin/end commands
1757 // or at the very end of an active branch inset with a language switch
1758 Language const * const outer_language = (runparams.local_font != nullptr)
1759 ? runparams.local_font->language() : bparams.language;
1760 string const & prev_lang = runparams.use_polyglossia
1761 ? getPolyglossiaEnvName(outer_language)
1762 : outer_language->babel();
1763 string const lastpar_lang = runparams.use_polyglossia ?
1764 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1765 string const & cur_lang = openLanguageName(state);
1766 if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1767 || (maintext && !is_child)) && !cur_lang.empty()) {
1768 os << from_utf8(subst(lang_end_command,
1772 if (using_begin_end)
1774 } else if (runparams.inbranch && !using_begin_end
1775 && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1776 // with !using_begin_end, cur_lang is empty, so we need to
1777 // compare against the paragraph language (and we are in the
1778 // last paragraph at this point)
1779 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1782 // reset inherited encoding
1783 if (state->cjk_inherited_ > 0) {
1784 state->cjk_inherited_ -= 1;
1785 if (state->cjk_inherited_ == 0)
1786 state->open_encoding_ = CJK;
1789 if (multibib_child && mparams.useBibtopic()) {
1790 os << "\\end{btUnit}\n";
1791 runparams.openbtUnit = false;
1795 // Switch the input encoding for some part(s) of the document.
1796 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1797 OutputParams const & runparams, Encoding const & newEnc,
1798 bool force, bool noswitchmacro)
1800 // Never switch encoding with XeTeX/LuaTeX
1801 // or if we're in a moving argument or inherit the outer encoding.
1802 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1803 return make_pair(false, 0);
1805 // Only switch for auto-selected legacy encodings (inputenc setting
1806 // "auto-legacy" or "auto-legacy-plain").
1807 // The "listings" environment can force a switch also with other
1808 // encoding settings (it does not support variable width encodings
1809 // (utf8, jis, ...) under 8-bit latex engines).
1810 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1811 || runparams.moving_arg))
1812 return make_pair(false, 0);
1814 Encoding const & oldEnc = *runparams.encoding;
1815 // Do not switch, if the encoding is unchanged or switching is not supported.
1816 if (oldEnc.name() == newEnc.name()
1817 || oldEnc.package() == Encoding::japanese
1818 || oldEnc.package() == Encoding::none
1819 || newEnc.package() == Encoding::none
1820 || (runparams.for_searchAdv != OutputParams::NoSearch))
1821 return make_pair(false, 0);
1822 // FIXME We ignore encoding switches from/to encodings that do
1823 // neither support the inputenc package nor the CJK package here.
1824 // This may fail for characters not supported by "unicodesymbols"
1825 // or for non-ASCII characters in "listings"
1826 // but it is the best we can do.
1829 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1830 << oldEnc.name() << " to " << newEnc.name());
1831 os << setEncoding(newEnc.iconvName());
1832 if (bparams.inputenc == "auto-legacy-plain")
1833 return make_pair(true, 0);
1835 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1836 OutputState * state = getOutputState();
1837 switch (newEnc.package()) {
1838 case Encoding::none:
1839 case Encoding::japanese:
1840 // shouldn't ever reach here (see above) but avoids warning.
1841 return make_pair(true, 0);
1842 case Encoding::inputenc: {
1843 size_t count = inputenc_arg.length();
1844 if (oldEnc.package() == Encoding::CJK &&
1845 state->open_encoding_ == CJK) {
1847 state->open_encoding_ = none;
1850 else if (oldEnc.package() == Encoding::inputenc &&
1851 state->open_encoding_ == inputenc) {
1853 state->open_encoding_ = none;
1856 if (runparams.local_font != nullptr
1857 && oldEnc.package() == Encoding::CJK) {
1858 // within insets, \inputenc switches need
1859 // to be embraced within \bgroup...\egroup;
1863 state->open_encoding_ = inputenc;
1866 return make_pair(true, count);
1867 os << "\\inputencoding{" << inputenc_arg << '}';
1868 return make_pair(true, count + 16);
1870 case Encoding::CJK: {
1871 size_t count = inputenc_arg.length();
1872 if (oldEnc.package() == Encoding::CJK &&
1873 state->open_encoding_ == CJK) {
1877 if (oldEnc.package() == Encoding::inputenc &&
1878 state->open_encoding_ == inputenc) {
1882 os << "\\begin{CJK}{"
1883 << from_ascii(newEnc.latexName()) << "}{"
1884 << from_ascii(bparams.fonts_cjk) << "}";
1885 state->open_encoding_ = CJK;
1886 return make_pair(true, count + 15);
1889 // Dead code to avoid a warning:
1890 return make_pair(true, 0);