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.
441 if (size_t(pit + 1) < paragraphs.size()) {
442 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
443 Paragraph const & cpar = paragraphs.at(pit);
444 if ((par->layout() != nextpar->layout()
445 || par->params().depth() == nextpar->params().depth()
446 || par->params().leftIndent() == nextpar->params().leftIndent())
447 && !runparams.for_search && !cpar.empty()
448 && cpar.isDeleted(0, cpar.size()) && !buf.params().output_changes) {
449 if (!buf.params().output_changes && !cpar.parEndChange().deleted())
455 // This is a new environment.
456 TeXEnvironmentData const data =
457 prepareEnvironment(buf, text, par, os, runparams);
458 // Recursive call to TeXEnvironment!
459 TeXEnvironment(buf, text, runparams, pit, os);
460 finishEnvironment(os, runparams, data);
463 if (pit != runparams.par_end)
464 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
468 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
469 map<size_t, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
471 size_t const argnr = latexargs.size();
475 // Default and preset args are always output, so if they require
476 // other arguments, consider this.
477 for (auto const & larg : latexargs) {
478 Layout::latexarg const & arg = larg.second;
479 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.required.empty()) {
480 vector<string> req = getVectorFromString(arg.required);
481 required.insert(required.end(), req.begin(), req.end());
485 for (size_t i = 1; i <= argnr; ++i) {
486 map<size_t, InsetArgument const *>::const_iterator lit = ilist.find(i);
487 bool inserted = false;
488 if (lit != ilist.end()) {
489 InsetArgument const * ins = lit->second;
491 Layout::LaTeXArgMap::const_iterator const lait =
492 latexargs.find(ins->name());
493 if (lait != latexargs.end()) {
494 Layout::latexarg arg = lait->second;
498 ldelim = arg.mandatory ?
499 from_ascii("{") : from_ascii("[");
500 rdelim = arg.mandatory ?
501 from_ascii("}") : from_ascii("]");
503 if (!arg.ldelim.empty())
505 if (!arg.rdelim.empty())
507 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
508 if (prefix == "listpreamble:")
515 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
516 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
517 for (; lait != laend; ++lait) {
518 string const name = prefix + convert<string>(i);
519 if ((*lait).first == name) {
520 Layout::latexarg arg = (*lait).second;
521 docstring preset = arg.presetarg;
522 if (!arg.defaultarg.empty()) {
525 preset += arg.defaultarg;
528 docstring ldelim = arg.ldelim.empty() ?
529 from_ascii("{") : arg.ldelim;
530 docstring rdelim = arg.rdelim.empty() ?
531 from_ascii("}") : arg.rdelim;
532 os << ldelim << preset << rdelim;
533 } else if (!preset.empty()) {
534 docstring ldelim = arg.ldelim.empty() ?
535 from_ascii("[") : arg.ldelim;
536 docstring rdelim = arg.rdelim.empty() ?
537 from_ascii("]") : arg.rdelim;
538 os << ldelim << preset << rdelim;
539 } else if (find(required.begin(), required.end(),
540 (*lait).first) != required.end()) {
541 docstring ldelim = arg.ldelim.empty() ?
542 from_ascii("[") : arg.ldelim;
543 docstring rdelim = arg.rdelim.empty() ?
544 from_ascii("]") : arg.rdelim;
545 os << ldelim << rdelim;
552 if (runparams.for_search) {
553 // Mark end of arguments for findadv() only
554 os << "\\endarguments{}";
562 void pushLanguageName(string const & lang_name, bool localswitch)
564 OutputState * state = getOutputState();
566 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
567 state->lang_switch_depth_.push(nest_level);
568 state->open_polyglossia_lang_.push(lang_name);
572 void popLanguageName()
574 OutputState * state = getOutputState();
576 state->lang_switch_depth_.pop();
577 state->open_polyglossia_lang_.pop();
581 string const & openLanguageName()
583 OutputState * state = getOutputState();
585 return openLanguageName(state);
591 void addArgInsets(Paragraph const & par, string const & prefix,
592 Layout::LaTeXArgMap const & latexargs,
593 map<size_t, InsetArgument const *> & ilist,
594 vector<string> & required)
596 for (auto const & table : par.insetList()) {
597 InsetArgument const * arg = table.inset->asInsetArgument();
600 if (arg->name().empty()) {
601 LYXERR0("Error: Unnamed argument inset!");
604 string const name = prefix.empty() ?
605 arg->name() : split(arg->name(), ':');
606 size_t const nr = convert<size_t>(name);
607 ilist.insert({nr, arg});
608 Layout::LaTeXArgMap::const_iterator const lit =
609 latexargs.find(arg->name());
610 if (lit != latexargs.end()) {
611 Layout::latexarg const & larg = lit->second;
612 vector<string> req = getVectorFromString(larg.required);
613 move(req.begin(), req.end(), back_inserter(required));
621 void latexArgInsets(Paragraph const & par, otexstream & os,
622 OutputParams const & runparams,
623 Layout::LaTeXArgMap const & latexargs,
624 string const & prefix)
626 map<size_t, InsetArgument const *> ilist;
627 vector<string> required;
628 addArgInsets(par, prefix, latexargs, ilist, required);
629 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
633 void latexArgInsets(ParagraphList const & pars,
634 ParagraphList::const_iterator pit,
635 otexstream & os, OutputParams const & runparams,
636 Layout::LaTeXArgMap const & latexargs,
637 string const & prefix)
639 map<size_t, InsetArgument const *> ilist;
640 vector<string> required;
642 depth_type const current_depth = pit->params().depth();
643 Layout const current_layout = pit->layout();
645 // get the first paragraph in sequence with this layout and depth
646 ptrdiff_t offset = 0;
648 if (prev(pit, offset) == pars.begin())
650 ParagraphList::const_iterator priorpit = prev(pit, offset + 1);
651 if (priorpit->layout() == current_layout
652 && priorpit->params().depth() == current_depth)
658 ParagraphList::const_iterator spit = prev(pit, offset);
659 for (; spit != pars.end(); ++spit) {
660 if (spit->layout() != current_layout ||
661 spit->params().depth() < current_depth)
663 if (spit->params().depth() > current_depth)
665 addArgInsets(*spit, prefix, latexargs, ilist, required);
667 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
671 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
672 OutputParams const & runparams,
673 Layout::LaTeXArgMap const & latexargs,
674 string const & prefix)
676 map<size_t, InsetArgument const *> ilist;
677 vector<string> required;
679 for (Paragraph const & par : pars) {
680 if (par.layout().hasArgs())
681 // The InsetArguments inside this paragraph refer to this paragraph
683 addArgInsets(par, prefix, latexargs, ilist, required);
685 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
691 // output the proper paragraph start according to latextype.
692 void parStartCommand(Paragraph const & par, otexstream & os,
693 OutputParams const & runparams, Layout const & style)
695 switch (style.latextype) {
697 if (par.needsCProtection(runparams.moving_arg)) {
698 if (contains(runparams.active_chars, '^'))
699 // cprotect relies on ^ being on catcode 7
700 os << "\\begingroup\\catcode`\\^=7";
703 os << '\\' << from_ascii(style.latexname());
706 if (!style.latexargs().empty())
707 latexArgInsets(par, os, runparams, style.latexargs());
708 os << from_ascii(style.latexparam());
710 case LATEX_ITEM_ENVIRONMENT:
711 case LATEX_LIST_ENVIRONMENT:
712 if (runparams.for_search) {
713 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
716 os << "\\" + style.itemcommand();
718 if (!style.itemargs().empty())
719 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
723 case LATEX_ENVIRONMENT:
724 if (runparams.for_search) {
725 os << "\\latexenvironment{" << style.latexname() << "}{";
728 case LATEX_BIB_ENVIRONMENT:
729 // ignore this, the inset will write itself
738 // FIXME: this should be anonymous
739 void TeXOnePar(Buffer const & buf,
743 OutputParams const & runparams_in,
744 string const & everypar,
745 int start_pos, int end_pos,
748 BufferParams const & bparams = runparams_in.is_child
749 ? buf.masterParams() : buf.params();
750 ParagraphList const & paragraphs = text.paragraphs();
751 Paragraph const & par = paragraphs.at(pit);
752 // FIXME This check should not really be needed.
753 // Perhaps we should issue an error if it is.
754 Layout const & style = text.inset().forcePlainLayout() ?
755 bparams.documentClass().plainLayout() : par.layout();
757 if (style.inpreamble && !force)
760 // Do not output empty commands if the whole paragraph has
761 // been deleted with ct and changes are not output.
762 if (!runparams_in.for_search && style.latextype != LATEX_ENVIRONMENT
763 && !par.empty() && par.isDeleted(0, par.size()) && !bparams.output_changes)
766 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
769 OutputParams runparams = runparams_in;
770 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
771 // We reinitialize par begin and end to be on the safe side
772 // with embedded inset as we don't know if they set those
774 runparams.par_begin = 0;
775 runparams.par_end = 0;
777 bool const maintext = text.isMainText();
778 // we are at the beginning of an inset and CJK is already open;
779 // we count inheritation levels to get the inset nesting right.
780 OutputState * state = getOutputState();
781 if (pit == 0 && !maintext
782 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
783 state->cjk_inherited_ += 1;
784 state->open_encoding_ = none;
787 // This paragraph is merged and we do not show changes in the output
788 bool const merged_par = !bparams.output_changes && par.parEndChange().deleted();
790 if (text.inset().isPassThru()) {
791 Font const outerfont = text.outerFont(pit);
793 // No newline before first paragraph in this lyxtext
794 if (pit > 0 && !text.inset().getLayout().parbreakIgnored() && !merged_par) {
796 if (!text.inset().getLayout().parbreakIsNewline())
800 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
804 Paragraph const * nextpar = runparams.isLastPar
805 ? nullptr : ¶graphs.at(pit + 1);
807 bool const intitle_command = style.intitle && style.isCommand();
808 // Intitle commands switch languages locally, thus increase
809 // language nesting level
811 state->nest_level_ += 1;
813 if (style.pass_thru) {
814 Font const outerfont = text.outerFont(pit);
815 parStartCommand(par, os, runparams, style);
816 if (style.isCommand() && style.needprotect)
817 // Due to the moving argument, some fragile
818 // commands (labels, index entries)
819 // are output after this command (#2154)
820 runparams.postpone_fragile_stuff =
821 bparams.postpone_fragile_content;
825 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
827 // I did not create a parEndCommand for this minuscule
828 // task because in the other user of parStartCommand
829 // the code is different (JMarc)
830 if (style.isCommand()) {
832 if (par.needsCProtection(runparams.moving_arg)
833 && contains(runparams.active_chars, '^'))
840 else if (!merged_par)
842 if (!style.parbreak_is_newline && !merged_par) {
844 } else if (nextpar && !style.isEnvironment()) {
845 Layout const nextstyle = text.inset().forcePlainLayout()
846 ? bparams.documentClass().plainLayout()
848 if (nextstyle.name() != style.name() && !merged_par)
855 // This paragraph's language
856 Language const * const par_language = par.getParLanguage(bparams);
857 Language const * const nextpar_language = nextpar ?
858 nextpar->getParLanguage(bparams) : nullptr;
859 // The document's language
860 Language const * const doc_language = bparams.language;
861 // The language that was in effect when the environment this paragraph is
862 // inside of was opened
863 Language const * const outer_language =
864 (runparams.local_font != nullptr) ?
865 runparams.local_font->language() : doc_language;
867 Paragraph const * priorpar = (pit == 0) ? nullptr : ¶graphs.at(pit - 1);
869 // The previous language that was in effect is the language of the
870 // previous paragraph, unless the previous paragraph is inside an
871 // environment with nesting depth greater than (or equal to, but with
872 // a different layout) the current one. If there is no previous
873 // paragraph, the previous language is the outer language.
874 // Note further that we take the outer language also if the prior par
875 // is PassThru, since in that case it has latex_language, and all secondary
876 // languages have been closed (#10793).
877 bool const use_prev_env_language = state->prev_env_language_ != nullptr
879 && priorpar->layout().isEnvironment()
880 && (priorpar->getDepth() > par.getDepth()
881 || (priorpar->getDepth() == par.getDepth()
882 && priorpar->layout() != par.layout()));
884 // We need to ignore previous intitle commands since languages
885 // are switched locally there (# 11514)
886 // There might be paragraphs before the title, so we check this.
887 Paragraph * prior_nontitle_par = nullptr;
888 if (!intitle_command) {
892 Paragraph const * tmppar = ¶graphs.at(ppit);
893 if (tmppar->layout().intitle && tmppar->layout().isCommand())
895 prior_nontitle_par = const_cast<Paragraph*>(tmppar);
899 Language const * const prev_language =
900 runparams_in.for_search
901 ? languages.getLanguage("ignore")
902 : (prior_nontitle_par && !prior_nontitle_par->isPassThru())
903 ? (use_prev_env_language
904 ? state->prev_env_language_
905 : prior_nontitle_par->getParLanguage(bparams))
908 bool const use_polyglossia = runparams.use_polyglossia;
909 string const par_lang = use_polyglossia ?
910 getPolyglossiaEnvName(par_language): par_language->babel();
911 string const prev_lang = use_polyglossia ?
912 getPolyglossiaEnvName(prev_language) : prev_language->babel();
913 string const outer_lang = use_polyglossia ?
914 getPolyglossiaEnvName(outer_language) : outer_language->babel();
915 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
916 getPolyglossiaEnvName(nextpar_language) :
917 nextpar_language->babel()) : string();
918 string lang_begin_command = use_polyglossia ?
919 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
920 string lang_end_command = use_polyglossia ?
921 "\\end{$$lang}" : lyxrc.language_command_end;
922 // the '%' is necessary to prevent unwanted whitespace
923 string lang_command_termination = "%\n";
924 bool const using_begin_end = use_polyglossia ||
925 !lang_end_command.empty();
927 // For InTitle commands, we need to switch the language inside the command
928 // (see #10849); thus open the command here.
929 if (intitle_command) {
930 parStartCommand(par, os, runparams, style);
931 if (style.isCommand() && style.needprotect)
932 // Due to the moving argument, some fragile
933 // commands (labels, index entries)
934 // are output after this command (#2154)
935 runparams.postpone_fragile_stuff =
936 bparams.postpone_fragile_content;
940 // In some insets (such as Arguments), we cannot use \selectlanguage.
941 // Also, if an RTL language is set via environment in polyglossia,
942 // only a nested \\text<lang> command will reset the direction for LTR
943 // languages (see # 10111).
944 bool const in_polyglossia_rtl_env =
946 && runparams.local_font != nullptr
947 && outer_language->rightToLeft()
948 && !par_language->rightToLeft();
949 bool const localswitch =
950 (runparams_in.for_search
951 || text.inset().forceLocalFontSwitch()
952 || (using_begin_end && text.inset().forcePlainLayout())
953 || in_polyglossia_rtl_env)
954 && !text.inset().forceParDirectionSwitch();
956 lang_begin_command = use_polyglossia ?
957 "\\text$$lang$$opts{" : lyxrc.language_command_local;
958 lang_end_command = "}";
959 lang_command_termination.clear();
962 bool const localswitch_needed = localswitch && par_lang != outer_lang;
964 // localswitches need to be closed and reopened at each par
965 if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
966 // check if we already put language command in TeXEnvironment()
967 && !(style.isEnvironment()
968 && (pit == 0 || (priorpar->layout() != par.layout()
969 && priorpar->getDepth() <= par.getDepth())
970 || priorpar->getDepth() < par.getDepth())))) {
972 && (!using_begin_end || langOpenedAtThisLevel(state))
973 && !lang_end_command.empty()
974 && prev_lang != outer_lang
975 && !prev_lang.empty()
976 && (!using_begin_end || !style.isEnvironment())) {
977 os << from_ascii(subst(lang_end_command,
980 << lang_command_termination;
985 // We need to open a new language if we couldn't close the previous
986 // one (because there's no language_command_end); and even if we closed
987 // the previous one, if the current language is different than the
988 // outer_language (which is currently in effect once the previous one
990 if ((lang_end_command.empty() || par_lang != outer_lang
992 || (style.isEnvironment() && par_lang != prev_lang)))
993 && !par_lang.empty()) {
994 // If we're inside an inset, and that inset is within an \L or \R
995 // (or equivalents), then within the inset, too, any opposite
996 // language paragraph should appear within an \L or \R (in addition
997 // to, outside of, the normal language switch commands).
998 // This behavior is not correct for ArabTeX, though.
1001 && par_language->lang() != "arabic_arabtex"
1002 && outer_language->lang() != "arabic_arabtex"
1003 // are we in an inset?
1004 && runparams.local_font != nullptr
1005 // is the inset within an \L or \R?
1007 // FIXME: currently, we don't check this; this means that
1008 // we'll have unnnecessary \L and \R commands, but that
1009 // doesn't seem to hurt (though latex will complain)
1011 // is this paragraph in the opposite direction?
1012 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
1013 // FIXME: I don't have a working copy of the Arabi package, so
1014 // I'm not sure if the farsi and arabic_arabi stuff is correct
1016 if (par_language->lang() == "farsi")
1018 else if (outer_language->lang() == "farsi")
1020 else if (par_language->lang() == "arabic_arabi")
1022 else if (outer_language->lang() == "arabic_arabi")
1024 // remaining RTL languages currently is hebrew
1025 else if (par_language->rightToLeft())
1030 // With CJK, the CJK tag has to be closed first (see below)
1031 if ((runparams.encoding->package() != Encoding::CJK
1032 || bparams.useNonTeXFonts
1033 || runparams.for_search)
1034 && (par_lang != openLanguageName(state) || localswitch || intitle_command)
1035 && !par_lang.empty()) {
1036 string bc = use_polyglossia ?
1037 getPolyglossiaBegin(lang_begin_command, par_lang,
1038 par_language->polyglossiaOpts(),
1040 : subst(lang_begin_command, "$$lang", par_lang);
1042 os << lang_command_termination;
1043 if (using_begin_end)
1044 pushLanguageName(par_lang, localswitch);
1049 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
1050 // encoding, since this only affects the position of the outputted
1051 // \inputencoding command; the encoding switch will occur when necessary
1052 if (bparams.inputenc == "auto-legacy"
1053 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
1054 && runparams.encoding->package() != Encoding::japanese
1055 && runparams.encoding->package() != Encoding::none) {
1056 // Look ahead for future encoding changes.
1057 // We try to output them at the beginning of the paragraph,
1058 // since the \inputencoding command is not allowed e.g. in
1059 // sections. For this reason we only set runparams.moving_arg
1060 // after checking for the encoding change, otherwise the
1061 // change would be always avoided by switchEncoding().
1062 for (pos_type i = 0; i < par.size(); ++i) {
1063 char_type const c = par.getChar(i);
1064 Encoding const * const encoding =
1065 par.getFontSettings(bparams, i).language()->encoding();
1066 if (encoding->package() != Encoding::CJK
1067 && runparams.encoding->package() == Encoding::inputenc
1072 // All characters before c are in the ASCII range, and
1073 // c is non-ASCII (but no inset), so change the
1074 // encoding to that required by the language of c.
1075 // With CJK, only add switch if we have CJK content at the beginning
1077 if (i != 0 && encoding->package() == Encoding::CJK)
1080 pair<bool, int> enc_switch = switchEncoding(os.os(),
1081 bparams, runparams, *encoding);
1082 // the following is necessary after a CJK environment in a multilingual
1083 // context (nesting issue).
1084 if (par_language->encoding()->package() == Encoding::CJK
1085 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1086 os << "\\begin{CJK}{"
1087 << from_ascii(par_language->encoding()->latexName())
1088 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1089 state->open_encoding_ = CJK;
1091 if (encoding->package() != Encoding::none && enc_switch.first) {
1092 if (enc_switch.second > 0) {
1093 // the '%' is necessary to prevent unwanted whitespace
1096 // With CJK, the CJK tag had to be closed first (see above)
1097 if (runparams.encoding->package() == Encoding::CJK
1098 && par_lang != openLanguageName(state)
1099 && !par_lang.empty()) {
1100 os << subst(lang_begin_command, "$$lang", par_lang)
1101 << lang_command_termination;
1102 if (using_begin_end)
1103 pushLanguageName(par_lang, localswitch);
1105 runparams.encoding = encoding;
1111 runparams.moving_arg |= style.needprotect;
1112 if (style.needmboxprotect)
1113 ++runparams.inulemcmd;
1114 Encoding const * const prev_encoding = runparams.encoding;
1116 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1117 if (par.allowParagraphCustomization()) {
1118 if (par.params().startOfAppendix()) {
1119 os << "\n\\appendix\n";
1122 // InTitle commands must use switches (not environments)
1123 // inside the commands (see #9332)
1124 if (style.intitle) {
1125 if (!par.params().spacing().isDefault())
1127 if (runparams.moving_arg)
1129 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1132 if (!par.params().spacing().isDefault()
1133 && (pit == 0 || !priorpar->hasSameLayout(par)))
1135 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1139 if (style.isCommand()) {
1145 // For InTitle commands, we already started the command before
1146 // the language switch
1147 if (!intitle_command) {
1148 parStartCommand(par, os, runparams, style);
1149 if (style.isCommand() && style.needprotect)
1150 // Due to the moving argument, some fragile
1151 // commands (labels, index entries)
1152 // are output after this command (#2154)
1153 runparams.postpone_fragile_stuff =
1154 bparams.postpone_fragile_content;
1157 Font const outerfont = text.outerFont(pit);
1160 os << from_utf8(everypar);
1161 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1163 Font const font = par.empty()
1164 ? par.getLayoutFont(bparams, outerfont)
1165 : par.getFont(bparams, par.size() - 1, outerfont);
1167 bool const is_command = style.isCommand();
1169 // InTitle commands need to be closed after the language has been closed.
1170 if (!intitle_command) {
1173 if (!style.postcommandargs().empty())
1174 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1175 if (!runparams.post_macro.empty()) {
1176 // Output the stored fragile commands (labels, indices etc.)
1177 // that need to be output after the command with moving argument.
1178 os << runparams.post_macro;
1179 runparams.post_macro.clear();
1181 if (par.needsCProtection(runparams.moving_arg)
1182 && contains(runparams.active_chars, '^'))
1184 if (runparams.encoding != prev_encoding) {
1185 runparams.encoding = prev_encoding;
1186 os << setEncoding(prev_encoding->iconvName());
1191 bool pending_newline = false;
1192 bool unskip_newline = false;
1193 bool close_lang_switch = false;
1194 switch (style.latextype) {
1195 case LATEX_ITEM_ENVIRONMENT:
1196 case LATEX_LIST_ENVIRONMENT:
1197 if ((nextpar && par_lang != nextpar_lang
1198 && nextpar->getDepth() == par.getDepth())
1199 || (atSameLastLangSwitchDepth(state) && nextpar
1200 && nextpar->getDepth() < par.getDepth()))
1201 close_lang_switch = using_begin_end;
1202 if (nextpar && par.params().depth() < nextpar->params().depth())
1203 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1205 case LATEX_ENVIRONMENT: {
1206 // if it's the last paragraph of the current environment
1207 // skip it otherwise fall through
1209 && ((nextpar->layout() != par.layout()
1210 || nextpar->params().depth() != par.params().depth())
1211 || (!using_begin_end || par_lang != nextpar_lang)))
1213 close_lang_switch = using_begin_end;
1220 // we don't need it for the last paragraph and in InTitle commands!!!
1221 if (nextpar && !intitle_command)
1222 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1225 // InTitle commands use switches (not environments) for space settings
1226 if (par.allowParagraphCustomization() && !style.intitle) {
1227 if (!par.params().spacing().isDefault()
1228 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1229 if (pending_newline)
1232 string const endtag =
1233 par.params().spacing().writeEnvirEnd(useSetSpace);
1234 if (prefixIs(endtag, "\\end{"))
1237 os << from_ascii(endtag);
1238 pending_newline = true;
1242 // Closing the language is needed for the last paragraph in a given language
1243 // as well as for any InTitleCommand (since these set the language locally);
1244 // it is also needed if we're within an \L or \R that we may have opened above
1245 // (not necessarily in this paragraph) and are about to close.
1246 bool closing_rtl_ltr_environment = !using_begin_end
1248 && (par_language->lang() != "arabic_arabtex"
1249 && outer_language->lang() != "arabic_arabtex")
1250 // have we opened an \L or \R environment?
1251 && runparams.local_font != nullptr
1252 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1253 // are we about to close the language?
1254 &&((nextpar && par_lang != nextpar_lang)
1255 || (runparams.isLastPar && par_lang != outer_lang));
1257 if (localswitch_needed
1258 || (intitle_command && using_begin_end)
1259 || closing_rtl_ltr_environment
1260 || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1261 && (par_lang != outer_lang || (using_begin_end
1262 && style.isEnvironment()
1263 && par_lang != nextpar_lang)))) {
1264 // Since \selectlanguage write the language to the aux file,
1265 // we need to reset the language at the end of footnote or
1268 if (!localswitch && (pending_newline || close_lang_switch))
1271 // when the paragraph uses CJK, the language has to be closed earlier
1272 if ((font.language()->encoding()->package() != Encoding::CJK)
1273 || bparams.useNonTeXFonts
1274 || runparams_in.for_search) {
1275 if (lang_end_command.empty()) {
1276 // If this is a child, we should restore the
1277 // master language after the last paragraph.
1278 Language const * const current_language =
1279 (runparams.isLastPar && runparams.master_language)
1280 ? runparams.master_language
1282 string const current_lang = use_polyglossia
1283 ? getPolyglossiaEnvName(current_language)
1284 : current_language->babel();
1285 if (!current_lang.empty()
1286 && current_lang != openLanguageName(state)) {
1287 string bc = use_polyglossia ?
1288 getPolyglossiaBegin(lang_begin_command, current_lang,
1289 current_language->polyglossiaOpts(),
1291 : subst(lang_begin_command, "$$lang", current_lang);
1293 pending_newline = !localswitch
1294 && !text.inset().getLayout().parbreakIgnored();
1295 unskip_newline = !localswitch;
1296 if (using_begin_end)
1297 pushLanguageName(current_lang, localswitch);
1299 } else if ((!using_begin_end ||
1300 langOpenedAtThisLevel(state)) &&
1301 !par_lang.empty()) {
1302 // If we are in an environment, we have to
1303 // close the "outer" language afterwards
1304 string const & cur_lang = openLanguageName(state);
1305 if (!style.isEnvironment()
1306 || (close_lang_switch
1307 && atSameLastLangSwitchDepth(state)
1308 && par_lang != outer_lang
1309 && (par_lang != cur_lang
1310 || (cur_lang != outer_lang
1312 && style != nextpar->layout())))
1313 || (atSameLastLangSwitchDepth(state)
1314 && !state->lang_switch_depth_.empty()
1315 && cur_lang != par_lang)
1316 || in_polyglossia_rtl_env)
1318 if (using_begin_end && !localswitch)
1320 os << from_ascii(subst(
1324 pending_newline = !localswitch
1325 && !text.inset().getLayout().parbreakIgnored();
1326 unskip_newline = !localswitch;
1327 if (using_begin_end)
1333 if (closing_rtl_ltr_environment)
1336 // InTitle commands need to be closed after the language has been closed.
1337 if (intitle_command) {
1339 if (!style.postcommandargs().empty())
1340 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1341 if (!runparams.post_macro.empty()) {
1342 // Output the stored fragile commands (labels, indices etc.)
1343 // that need to be output after the command with moving argument.
1344 os << runparams.post_macro;
1345 runparams.post_macro.clear();
1347 if (par.needsCProtection(runparams.moving_arg)
1348 && contains(runparams.active_chars, '^'))
1350 if (runparams.encoding != prev_encoding) {
1351 runparams.encoding = prev_encoding;
1352 os << setEncoding(prev_encoding->iconvName());
1356 bool const last_was_separator =
1357 !par.empty() && par.isEnvSeparator(par.size() - 1);
1359 // Signify added/deleted par break in output if show changes in output
1360 if (nextpar && !os.afterParbreak() && !last_was_separator
1361 && bparams.output_changes && par.parEndChange().changed()) {
1362 Changes::latexMarkChange(os, bparams, Change(Change::UNCHANGED),
1363 par.parEndChange(), runparams);
1364 os << bparams.encoding().latexString(docstring(1, 0x00b6)).first << "}";
1367 if (pending_newline) {
1369 // prevent unwanted whitespace
1371 if (!os.afterParbreak() && !last_was_separator)
1375 // if this is a CJK-paragraph and the next isn't, close CJK
1376 // also if the next paragraph is a multilingual environment (because of nesting)
1377 if (nextpar && state->open_encoding_ == CJK
1378 && bparams.encoding().iconvName() != "UTF-8"
1379 && bparams.encoding().package() != Encoding::CJK
1380 && ((nextpar_language &&
1381 nextpar_language->encoding()->package() != Encoding::CJK)
1382 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1383 // inbetween environments, CJK has to be closed later (nesting!)
1384 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1385 os << "\\end{CJK}\n";
1386 state->open_encoding_ = none;
1389 // If this is the last paragraph, close the CJK environment
1390 // if necessary. If it's an environment or nested in an environment,
1391 // we'll have to \end that first.
1392 if (runparams.isLastPar && !style.isEnvironment()
1393 && par.params().depth() < 1) {
1394 switch (state->open_encoding_) {
1396 // do nothing at the end of child documents
1397 if (maintext && buf.masterBuffer() != &buf)
1399 // end of main text: also insert a \clearpage (see #5386)
1401 os << "\n\\clearpage\n\\end{CJK}\n";
1405 state->open_encoding_ = none;
1409 // FIXME: If we are in an inset and the switch happened outside this inset,
1410 // do not switch back at the end of the inset (bug #8479)
1411 // The following attempt does not help with listings-caption in a CJK document:
1412 // if (runparams_in.local_font != 0
1413 // && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1416 state->open_encoding_ = none;
1426 // Information about local language is stored as a font feature.
1427 // If this is the last paragraph of the inset and a local_font was set upon entering
1428 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1429 // ensure the encoding is set back to the default encoding of the local language.
1430 if (runparams.isLastPar && runparams_in.local_font != nullptr
1431 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1432 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1433 && !runparams.isFullUnicode()
1435 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1436 os << setEncoding(runparams_in.encoding->iconvName());
1438 // Otherwise, the current encoding should be set for the next paragraph.
1440 runparams_in.encoding = runparams.encoding;
1442 // Also pass the post_macros upstream
1443 runparams_in.post_macro = runparams.post_macro;
1444 // These need to be passed upstream as well
1445 runparams_in.need_maketitle = runparams.need_maketitle;
1446 runparams_in.have_maketitle = runparams.have_maketitle;
1449 // we don't need a newline for the last paragraph!!!
1450 // Note from JMarc: we will re-add a \n explicitly in
1451 // TeXEnvironment, because it is needed in this case
1452 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1453 Layout const & next_layout = nextpar->layout();
1454 if (!text.inset().getLayout().parbreakIgnored() && !merged_par)
1455 // Make sure to start a new line
1457 // A newline '\n' is always output before a command,
1458 // so avoid doubling it.
1459 if (!next_layout.isCommand()) {
1460 // Here we now try to avoid spurious empty lines by
1461 // outputting a paragraph break only if: (case 1) the
1462 // paragraph style allows parbreaks and no \begin, \end
1463 // or \item tags are going to follow (i.e., if the next
1464 // isn't the first or the current isn't the last
1465 // paragraph of an environment or itemize) and the
1466 // depth and alignment of the following paragraph is
1467 // unchanged, or (case 2) the following is a
1468 // non-environment paragraph whose depth is increased
1469 // but whose alignment is unchanged, or (case 3) the
1470 // paragraph is not an environment and the next one is a
1471 // non-itemize-like env at lower depth, or (case 4) the
1472 // paragraph is a command not followed by an environment
1473 // and the alignment of the current and next paragraph
1474 // is unchanged, or (case 5) the current alignment is
1475 // changed and a standard paragraph follows.
1476 DocumentClass const & tclass = bparams.documentClass();
1477 if ((style == next_layout
1478 && !style.parbreak_is_newline
1479 && !text.inset().getLayout().parbreakIsNewline()
1480 && !text.inset().getLayout().parbreakIgnored()
1481 && style.latextype != LATEX_ITEM_ENVIRONMENT
1482 && style.latextype != LATEX_LIST_ENVIRONMENT
1483 && style.align == par.getAlign(bparams)
1484 && nextpar->getDepth() == par.getDepth()
1485 && nextpar->getAlign(bparams) == par.getAlign(bparams))
1486 || (!next_layout.isEnvironment()
1487 && nextpar->getDepth() > par.getDepth()
1488 && nextpar->getAlign(bparams) == next_layout.align)
1489 || (!style.isEnvironment()
1490 && next_layout.latextype == LATEX_ENVIRONMENT
1491 && nextpar->getDepth() < par.getDepth())
1492 || (style.isCommand()
1493 && !next_layout.isEnvironment()
1494 && style.align == par.getAlign(bparams)
1495 && next_layout.align == nextpar->getAlign(bparams))
1496 || (style.align != par.getAlign(bparams)
1497 && tclass.isDefaultLayout(next_layout))) {
1498 // and omit paragraph break if it has been deleted with ct
1499 // and changes are not shown in output
1506 // Reset language nesting level after intitle command
1507 if (intitle_command)
1508 state->nest_level_ -= 1;
1510 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1511 << &par << " next " << nextpar);
1517 // LaTeX all paragraphs
1518 void latexParagraphs(Buffer const & buf,
1521 OutputParams const & runparams,
1522 string const & everypar)
1524 LASSERT(runparams.par_begin <= runparams.par_end,
1525 { os << "% LaTeX Output Error\n"; return; } );
1527 BufferParams const & bparams = buf.params();
1528 BufferParams const & mparams = buf.masterParams();
1530 bool const maintext = text.isMainText();
1531 bool const is_child = buf.masterBuffer() != &buf;
1532 bool const multibib_child = maintext && is_child
1533 && mparams.multibib == "child";
1535 if (multibib_child && mparams.useBiblatex())
1536 os << "\\newrefsection";
1537 else if (multibib_child && mparams.useBibtopic()
1538 && !buf.masterBibInfo().empty()) {
1539 os << "\\begin{btUnit}\n";
1540 runparams.openbtUnit = true;
1543 // Open a CJK environment at the beginning of the main buffer
1544 // if the document's main encoding requires the CJK package
1545 // or the document encoding is utf8 and the CJK package is required
1546 // (but not in child documents or documents using system fonts):
1547 OutputState * state = getOutputState();
1548 if (maintext && !is_child && !bparams.useNonTeXFonts
1549 && (bparams.encoding().package() == Encoding::CJK
1550 || (bparams.encoding().name() == "utf8"
1551 && runparams.use_CJK))
1553 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1554 ? from_ascii("UTF8")
1555 : from_ascii(bparams.encoding().latexName());
1556 os << "\\begin{CJK}{" << cjkenc
1557 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1558 state->open_encoding_ = CJK;
1560 // if "auto begin" is switched off, explicitly switch the
1561 // language on at start
1562 string const mainlang = runparams.use_polyglossia
1563 ? getPolyglossiaEnvName(bparams.language)
1564 : bparams.language->babel();
1565 string const lang_begin_command = runparams.use_polyglossia ?
1566 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1567 string const lang_end_command = runparams.use_polyglossia ?
1568 "\\end{$$lang}" : lyxrc.language_command_end;
1569 bool const using_begin_end = runparams.use_polyglossia ||
1570 !lang_end_command.empty();
1572 if (maintext && !lyxrc.language_auto_begin &&
1573 !mainlang.empty()) {
1575 string bc = runparams.use_polyglossia ?
1576 getPolyglossiaBegin(lang_begin_command, mainlang,
1577 bparams.language->polyglossiaOpts())
1578 : subst(lang_begin_command, "$$lang", mainlang);
1581 if (using_begin_end)
1582 pushLanguageName(mainlang);
1585 ParagraphList const & paragraphs = text.paragraphs();
1587 if (runparams.par_begin == runparams.par_end) {
1588 // The full doc will be exported but it is easier to just rely on
1589 // runparams range parameters that will be passed TeXEnvironment.
1590 runparams.par_begin = 0;
1591 runparams.par_end = static_cast<int>(paragraphs.size());
1594 pit_type pit = runparams.par_begin;
1595 // lastpit is for the language check after the loop.
1596 pit_type lastpit = pit;
1597 DocumentClass const & tclass = bparams.documentClass();
1599 // Did we already warn about inTitle layout mixing? (we only warn once)
1600 bool gave_layout_warning = false;
1601 for (; pit < runparams.par_end; ++pit) {
1603 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
1605 // FIXME This check should not be needed. We should
1606 // perhaps issue an error if it is.
1607 Layout const & layout = text.inset().forcePlainLayout() ?
1608 tclass.plainLayout() : par->layout();
1610 if (layout.intitle) {
1611 if (runparams.have_maketitle) {
1612 if (!gave_layout_warning && !runparams.dryrun) {
1613 gave_layout_warning = true;
1614 frontend::Alert::warning(_("Error in latexParagraphs"),
1615 bformat(_("You are using at least one "
1616 "layout (%1$s) intended for the title, "
1617 "after using non-title layouts. This "
1618 "could lead to missing or incorrect output."
1621 } else if (!runparams.need_maketitle) {
1622 runparams.need_maketitle = true;
1623 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1625 << from_ascii(tclass.titlename())
1629 } else if (runparams.need_maketitle && !runparams.have_maketitle
1630 && !layout.inpreamble && !text.inset().isInTitle()) {
1631 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1632 os << "\\end{" << from_ascii(tclass.titlename())
1636 os << "\\" << from_ascii(tclass.titlename())
1639 runparams.have_maketitle = true;
1640 runparams.need_maketitle = false;
1643 if (layout.isCommand() && !layout.latexname().empty()
1644 && layout.latexname() == bparams.multibib) {
1645 if (runparams.openbtUnit)
1646 os << "\\end{btUnit}\n";
1647 if (!bparams.useBiblatex()
1648 && !buf.masterBibInfo().empty()) {
1649 os << '\n' << "\\begin{btUnit}\n";
1650 runparams.openbtUnit = true;
1654 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1655 // This is a standard top level paragraph, TeX it and continue.
1656 TeXOnePar(buf, text, pit, os, runparams, everypar);
1660 // Do not output empty environments if the whole paragraph has
1661 // been deleted with ct and changes are not output.
1662 if (size_t(pit + 1) < paragraphs.size()) {
1663 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
1664 Paragraph const & cpar = paragraphs.at(pit);
1665 if ((par->layout() != nextpar->layout()
1666 || par->params().depth() == nextpar->params().depth()
1667 || par->params().leftIndent() == nextpar->params().leftIndent())
1668 && !runparams.for_search && !cpar.empty()
1669 && cpar.isDeleted(0, cpar.size()) && !bparams.output_changes) {
1670 if (!cpar.parEndChange().deleted())
1675 // This is the last par
1676 Paragraph const & cpar = paragraphs.at(pit);
1677 if (!runparams.for_search && !cpar.empty()
1678 && cpar.isDeleted(0, cpar.size()) && !bparams.output_changes) {
1679 if (!cpar.parEndChange().deleted())
1685 TeXEnvironmentData const data =
1686 prepareEnvironment(buf, text, par, os, runparams);
1687 // pit can be changed in TeXEnvironment.
1688 TeXEnvironment(buf, text, runparams, pit, os);
1689 finishEnvironment(os, runparams, data);
1692 // FIXME: uncomment the content or remove this block
1693 if (pit == runparams.par_end) {
1694 // Make sure that the last paragraph is
1695 // correctly terminated (because TeXOnePar does
1696 // not add a \n in this case)
1700 // It might be that we only have a title in this document.
1701 // But if we're in an inset, this is not the end of
1702 // the document. (There may be some other checks of this
1703 // kind that are needed.)
1704 if (runparams.need_maketitle && !runparams.have_maketitle && maintext) {
1705 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1706 os << "\\end{" << from_ascii(tclass.titlename())
1709 os << "\\" << from_ascii(tclass.titlename())
1714 if (maintext && !is_child && runparams.openbtUnit)
1715 os << "\\end{btUnit}\n";
1717 // if "auto end" is switched off, explicitly close the language at the end
1718 // but only if the last par is in a babel or polyglossia language
1719 Language const * const lastpar_language =
1720 paragraphs.at(lastpit).getParLanguage(bparams);
1721 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1722 lastpar_language->encoding()->package() != Encoding::CJK) {
1723 os << from_utf8(subst(lang_end_command,
1727 // If we have language_auto_begin, the stack will
1728 // already be empty, nothing to pop()
1729 if (using_begin_end && !lyxrc.language_auto_begin)
1733 // If the last paragraph is an environment, we'll have to close
1734 // CJK at the very end to do proper nesting.
1735 if (maintext && !is_child && state->open_encoding_ == CJK) {
1736 os << "\\clearpage\n\\end{CJK}\n";
1737 state->open_encoding_ = none;
1739 // Likewise for polyglossia or when using begin/end commands
1740 // or at the very end of an active branch inset with a language switch
1741 Language const * const outer_language = (runparams.local_font != nullptr)
1742 ? runparams.local_font->language() : bparams.language;
1743 string const & prev_lang = runparams.use_polyglossia
1744 ? getPolyglossiaEnvName(outer_language)
1745 : outer_language->babel();
1746 string const lastpar_lang = runparams.use_polyglossia ?
1747 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1748 string const & cur_lang = openLanguageName(state);
1749 if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1750 || (maintext && !is_child)) && !cur_lang.empty()) {
1751 os << from_utf8(subst(lang_end_command,
1755 if (using_begin_end)
1757 } else if (runparams.inbranch && !using_begin_end
1758 && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1759 // with !using_begin_end, cur_lang is empty, so we need to
1760 // compare against the paragraph language (and we are in the
1761 // last paragraph at this point)
1762 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1765 // reset inherited encoding
1766 if (state->cjk_inherited_ > 0) {
1767 state->cjk_inherited_ -= 1;
1768 if (state->cjk_inherited_ == 0)
1769 state->open_encoding_ = CJK;
1772 if (multibib_child && mparams.useBibtopic()) {
1773 os << "\\end{btUnit}\n";
1774 runparams.openbtUnit = false;
1778 // Switch the input encoding for some part(s) of the document.
1779 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1780 OutputParams const & runparams, Encoding const & newEnc,
1781 bool force, bool noswitchmacro)
1783 // Never switch encoding with XeTeX/LuaTeX
1784 // or if we're in a moving argument or inherit the outer encoding.
1785 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1786 return make_pair(false, 0);
1788 // Only switch for auto-selected legacy encodings (inputenc setting
1789 // "auto-legacy" or "auto-legacy-plain").
1790 // The "listings" environment can force a switch also with other
1791 // encoding settings (it does not support variable width encodings
1792 // (utf8, jis, ...) under 8-bit latex engines).
1793 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1794 || runparams.moving_arg))
1795 return make_pair(false, 0);
1797 Encoding const & oldEnc = *runparams.encoding;
1798 // Do not switch, if the encoding is unchanged or switching is not supported.
1799 if (oldEnc.name() == newEnc.name()
1800 || oldEnc.package() == Encoding::japanese
1801 || oldEnc.package() == Encoding::none
1802 || newEnc.package() == Encoding::none
1803 || runparams.for_search)
1804 return make_pair(false, 0);
1805 // FIXME We ignore encoding switches from/to encodings that do
1806 // neither support the inputenc package nor the CJK package here.
1807 // This may fail for characters not supported by "unicodesymbols"
1808 // or for non-ASCII characters in "listings"
1809 // but it is the best we can do.
1812 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1813 << oldEnc.name() << " to " << newEnc.name());
1814 os << setEncoding(newEnc.iconvName());
1815 if (bparams.inputenc == "auto-legacy-plain")
1816 return make_pair(true, 0);
1818 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1819 OutputState * state = getOutputState();
1820 switch (newEnc.package()) {
1821 case Encoding::none:
1822 case Encoding::japanese:
1823 // shouldn't ever reach here (see above) but avoids warning.
1824 return make_pair(true, 0);
1825 case Encoding::inputenc: {
1826 size_t count = inputenc_arg.length();
1827 if (oldEnc.package() == Encoding::CJK &&
1828 state->open_encoding_ == CJK) {
1830 state->open_encoding_ = none;
1833 else if (oldEnc.package() == Encoding::inputenc &&
1834 state->open_encoding_ == inputenc) {
1836 state->open_encoding_ = none;
1839 if (runparams.local_font != nullptr
1840 && oldEnc.package() == Encoding::CJK) {
1841 // within insets, \inputenc switches need
1842 // to be embraced within \bgroup...\egroup;
1846 state->open_encoding_ = inputenc;
1849 return make_pair(true, count);
1850 os << "\\inputencoding{" << inputenc_arg << '}';
1851 return make_pair(true, count + 16);
1853 case Encoding::CJK: {
1854 size_t count = inputenc_arg.length();
1855 if (oldEnc.package() == Encoding::CJK &&
1856 state->open_encoding_ == CJK) {
1860 if (oldEnc.package() == Encoding::inputenc &&
1861 state->open_encoding_ == inputenc) {
1865 os << "\\begin{CJK}{"
1866 << from_ascii(newEnc.latexName()) << "}{"
1867 << from_ascii(bparams.fonts_cjk) << "}";
1868 state->open_encoding_ = CJK;
1869 return make_pair(true, count + 15);
1872 // Dead code to avoid a warning:
1873 return make_pair(true, 0);