2 * \file output_latex.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
13 #include "output_latex.h"
15 #include "BiblioInfo.h"
17 #include "BufferParams.h"
20 #include "InsetList.h"
22 #include "LaTeXFeatures.h"
25 #include "OutputParams.h"
26 #include "Paragraph.h"
27 #include "ParagraphParameters.h"
28 #include "texstream.h"
29 #include "TextClass.h"
31 #include "insets/InsetBibitem.h"
32 #include "insets/InsetArgument.h"
34 #include "frontends/alert.h"
36 #include "support/lassert.h"
37 #include "support/convert.h"
38 #include "support/debug.h"
39 #include "support/lstrings.h"
40 #include "support/lyxalgo.h"
41 #include "support/textutils.h"
42 #include "support/gettext.h"
44 #include <QThreadStorage>
50 using namespace lyx::support;
66 OutputState() : open_encoding_(none), cjk_inherited_(0),
67 prev_env_language_(nullptr), nest_level_(0)
70 OpenEncoding open_encoding_;
72 Language const * prev_env_language_;
74 stack<int> lang_switch_depth_; // Both are always empty when
75 stack<string> open_polyglossia_lang_; // not using polyglossia
79 OutputState * getOutputState()
81 // FIXME An instance of OutputState should be kept around for each export
82 // instead of using local thread storage
83 static QThreadStorage<OutputState *> outputstate;
84 if (!outputstate.hasLocalData())
85 outputstate.setLocalData(new OutputState);
86 return outputstate.localData();
90 string const & openLanguageName(OutputState const * state)
92 // Return a reference to the last active language opened with
93 // polyglossia or when using begin/end commands. If none or when
94 // using babel with only a begin command, return a reference to
97 static string const empty;
99 return state->open_polyglossia_lang_.empty()
101 : state->open_polyglossia_lang_.top();
105 bool atSameLastLangSwitchDepth(OutputState const * state)
107 // Return true if the actual nest level is the same at which the
108 // language was switched when using polyglossia or begin/end
109 // commands. Instead, return always true when using babel with
110 // only a begin command.
112 return state->lang_switch_depth_.size() == 0
114 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
118 bool isLocalSwitch(OutputState const * state)
120 // Return true if the language was opened by a local command switch.
122 return state->lang_switch_depth_.size()
123 && state->lang_switch_depth_.top() < 0;
127 bool langOpenedAtThisLevel(OutputState const * state)
129 // Return true if the language was opened at the current nesting level.
131 return state->lang_switch_depth_.size()
132 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
136 string const getPolyglossiaEnvName(Language const * lang)
138 string result = lang->polyglossia();
139 if (result == "arabic")
140 // exceptional spelling; see polyglossia docs.
146 string const getPolyglossiaBegin(string const & lang_begin_command,
147 string const & lang, string const & opts,
148 bool const localswitch = false)
152 // we need to revert the upcasing done in getPolyglossiaEnvName()
153 // in case we have a local polyglossia command (\textarabic).
154 string language = localswitch ? ascii_lowercase(lang) : lang;
155 result = subst(lang_begin_command, "$$lang", language);
157 string options = opts.empty() ?
158 string() : "[" + opts + "]";
159 result = subst(result, "$$opts", options);
165 struct TeXEnvironmentData
168 Layout const * style;
169 Language const * par_language;
170 Encoding const * prev_encoding;
171 bool leftindent_open;
175 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
177 ParagraphList::const_iterator pit,
179 OutputParams const & runparams)
181 TeXEnvironmentData data;
183 BufferParams const & bparams = buf.params();
185 // FIXME This test should not be necessary.
186 // We should perhaps issue an error if it is.
187 Layout const & style = text.inset().forcePlainLayout() ?
188 bparams.documentClass().plainLayout() : pit->layout();
190 ParagraphList const & paragraphs = text.paragraphs();
191 ParagraphList::const_iterator const priorpit =
192 pit == paragraphs.begin() ? pit : prev(pit, 1);
194 OutputState * state = getOutputState();
195 bool const use_prev_env_language = state->prev_env_language_ != nullptr
196 && priorpit->layout().isEnvironment()
197 && (priorpit->getDepth() > pit->getDepth()
198 || (priorpit->getDepth() == pit->getDepth()
199 && priorpit->layout() != pit->layout()));
201 data.prev_encoding = runparams.encoding;
202 data.par_language = pit->getParLanguage(bparams);
203 Language const * const doc_language = bparams.language;
204 Language const * const prev_par_language =
205 (pit != paragraphs.begin())
206 ? (use_prev_env_language ? state->prev_env_language_
207 : priorpit->getParLanguage(bparams))
210 bool const use_polyglossia = runparams.use_polyglossia;
211 string const par_lang = use_polyglossia ?
212 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
213 string const prev_par_lang = use_polyglossia ?
214 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
215 string const doc_lang = use_polyglossia ?
216 getPolyglossiaEnvName(doc_language) : doc_language->babel();
217 string const lang_begin_command = use_polyglossia ?
218 "\\begin{$$lang}" : lyxrc.language_command_begin;
219 string const lang_end_command = use_polyglossia ?
220 "\\end{$$lang}" : lyxrc.language_command_end;
221 bool const using_begin_end = use_polyglossia ||
222 !lang_end_command.empty();
224 // For polyglossia, switch language outside of environment, if possible.
225 if (par_lang != prev_par_lang) {
226 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
227 !lang_end_command.empty() &&
228 prev_par_lang != doc_lang &&
229 !prev_par_lang.empty()) {
230 os << from_ascii(subst(
234 // the '%' is necessary to prevent unwanted whitespace
240 // If no language was explicitly opened and we are using
241 // polyglossia or begin/end commands, then the current
242 // language is the document language.
243 string const & cur_lang = using_begin_end
244 && state->lang_switch_depth_.size()
245 ? openLanguageName(state)
248 if ((lang_end_command.empty() ||
249 par_lang != doc_lang ||
250 par_lang != cur_lang) &&
252 string bc = use_polyglossia ?
253 getPolyglossiaBegin(lang_begin_command, par_lang,
254 data.par_language->polyglossiaOpts())
255 : subst(lang_begin_command, "$$lang", par_lang);
257 // the '%' is necessary to prevent unwanted whitespace
260 pushLanguageName(par_lang);
264 data.leftindent_open = false;
265 if (!pit->params().leftIndent().zero()) {
266 os << "\\begin{LyXParagraphLeftIndent}{"
267 << from_ascii(pit->params().leftIndent().asLatexString())
269 data.leftindent_open = true;
272 if (style.isEnvironment())
273 state->nest_level_ += 1;
275 if (style.isEnvironment() && !style.latexname().empty()) {
276 os << "\\begin{" << from_ascii(style.latexname()) << '}';
277 if (!style.latexargs().empty()) {
278 OutputParams rp = runparams;
279 rp.local_font = &pit->getFirstFontSettings(bparams);
280 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
282 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
284 << pit->params().labelWidthString()
286 } else if (style.labeltype == LABEL_BIBLIO) {
287 if (pit->params().labelWidthString().empty())
288 os << '{' << bibitemWidest(buf, runparams) << "}\n";
291 << pit->params().labelWidthString()
294 os << from_ascii(style.latexparam()) << '\n';
295 if (style.latextype == LATEX_BIB_ENVIRONMENT
296 || style.latextype == LATEX_ITEM_ENVIRONMENT
297 || style.latextype == LATEX_LIST_ENVIRONMENT) {
298 OutputParams rp = runparams;
299 rp.local_font = &pit->getFirstFontSettings(bparams);
300 latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
306 // in multilingual environments, the CJK tags have to be nested properly
307 data.cjk_nested = false;
308 if (!bparams.useNonTeXFonts
309 && (bparams.inputenc == "auto-legacy"
310 || bparams.inputenc == "auto-legacy-plain")
311 && data.par_language->encoding()->package() == Encoding::CJK
312 && state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
313 if (prev_par_language->encoding()->package() == Encoding::CJK) {
314 os << "\\begin{CJK}{"
315 << from_ascii(data.par_language->encoding()->latexName())
316 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
318 state->open_encoding_ = CJK;
319 data.cjk_nested = true;
325 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
326 TeXEnvironmentData const & data)
328 OutputState * state = getOutputState();
329 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
330 if (state->open_encoding_ == CJK && data.cjk_nested) {
331 // We need to close the encoding even if it does not change
332 // to do correct environment nesting
333 os << "\\end{CJK}\n";
334 state->open_encoding_ = none;
337 if (data.style->isEnvironment()) {
339 bool const using_begin_end =
340 runparams.use_polyglossia ||
341 !lyxrc.language_command_end.empty();
342 // Close any language opened at this nest level
343 if (using_begin_end) {
344 while (langOpenedAtThisLevel(state)) {
345 if (isLocalSwitch(state)) {
349 << openLanguageName(state)
355 state->nest_level_ -= 1;
356 string const & name = data.style->latexname();
358 os << "\\end{" << from_ascii(name) << "}\n";
359 state->prev_env_language_ = data.par_language;
360 if (runparams.encoding != data.prev_encoding) {
361 runparams.encoding = data.prev_encoding;
362 os << setEncoding(data.prev_encoding->iconvName());
366 if (data.leftindent_open) {
367 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
368 state->prev_env_language_ = data.par_language;
369 if (runparams.encoding != data.prev_encoding) {
370 runparams.encoding = data.prev_encoding;
371 os << setEncoding(data.prev_encoding->iconvName());
375 // Check whether we should output a blank line after the environment
376 if (!data.style->nextnoindent)
381 void TeXEnvironment(Buffer const & buf, Text const & text,
382 OutputParams const & runparams,
383 pit_type & pit, otexstream & os)
385 ParagraphList const & paragraphs = text.paragraphs();
386 ParagraphList::const_iterator ipar = paragraphs.constIterator(pit);
387 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
389 Layout const & current_layout = ipar->layout();
390 depth_type const current_depth = ipar->params().depth();
391 Length const & current_left_indent = ipar->params().leftIndent();
393 // This is for debugging purpose at the end.
394 pit_type const par_begin = pit;
395 for (; pit < runparams.par_end; ++pit) {
396 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
398 // check first if this is an higher depth paragraph.
399 bool go_out = (par->params().depth() < current_depth);
400 if (par->params().depth() == current_depth) {
401 // This environment is finished.
402 go_out |= (par->layout() != current_layout);
403 go_out |= (par->params().leftIndent() != current_left_indent);
406 // nothing to do here, restore pit and go out.
411 if (par->layout() == current_layout
412 && par->params().depth() == current_depth
413 && par->params().leftIndent() == current_left_indent) {
414 // We are still in the same environment so TeXOnePar and continue;
415 TeXOnePar(buf, text, pit, os, runparams);
419 // We are now in a deeper environment.
420 // Either par->layout() != current_layout
421 // Or par->params().depth() > current_depth
422 // Or par->params().leftIndent() != current_left_indent)
424 // FIXME This test should not be necessary.
425 // We should perhaps issue an error if it is.
426 bool const force_plain_layout = text.inset().forcePlainLayout();
427 Layout const & style = force_plain_layout
428 ? buf.params().documentClass().plainLayout()
431 if (!style.isEnvironment()) {
432 // This is a standard paragraph, no need to call TeXEnvironment.
433 TeXOnePar(buf, text, pit, os, runparams);
437 // Do not output empty environments if the whole paragraph has
438 // been deleted with ct and changes are not output.
439 if (size_t(pit + 1) < paragraphs.size()) {
440 ParagraphList::const_iterator nextpar = paragraphs.constIterator(pit + 1);
441 Paragraph const & cpar = paragraphs.at(pit);
442 if ((par->layout() != nextpar->layout()
443 || par->params().depth() == nextpar->params().depth()
444 || par->params().leftIndent() == nextpar->params().leftIndent())
445 && !runparams.for_search && cpar.size() > 0
446 && cpar.isDeleted(0, cpar.size()) && !buf.params().output_changes) {
447 if (!buf.params().output_changes && !cpar.parEndChange().deleted())
453 // This is a new environment.
454 TeXEnvironmentData const data =
455 prepareEnvironment(buf, text, par, os, runparams);
456 // Recursive call to TeXEnvironment!
457 TeXEnvironment(buf, text, runparams, pit, os);
458 finishEnvironment(os, runparams, data);
461 if (pit != runparams.par_end)
462 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
466 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
467 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
469 unsigned int const argnr = latexargs.size();
473 // Default and preset args are always output, so if they require
474 // other arguments, consider this.
475 for (auto const & larg : latexargs) {
476 Layout::latexarg const & arg = larg.second;
477 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
478 vector<string> req = getVectorFromString(arg.requires);
479 required.insert(required.end(), req.begin(), req.end());
483 for (unsigned int i = 1; i <= argnr; ++i) {
484 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
485 bool inserted = false;
486 if (lit != ilist.end()) {
487 InsetArgument const * ins = (*lit).second;
489 Layout::LaTeXArgMap::const_iterator const lait =
490 latexargs.find(ins->name());
491 if (lait != latexargs.end()) {
492 Layout::latexarg arg = (*lait).second;
496 ldelim = arg.mandatory ?
497 from_ascii("{") : from_ascii("[");
498 rdelim = arg.mandatory ?
499 from_ascii("}") : from_ascii("]");
501 if (!arg.ldelim.empty())
503 if (!arg.rdelim.empty())
505 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
506 if (prefix == "listpreamble:")
513 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
514 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
515 for (; lait != laend; ++lait) {
516 string const name = prefix + convert<string>(i);
517 if ((*lait).first == name) {
518 Layout::latexarg arg = (*lait).second;
519 docstring preset = arg.presetarg;
520 if (!arg.defaultarg.empty()) {
523 preset += arg.defaultarg;
526 docstring ldelim = arg.ldelim.empty() ?
527 from_ascii("{") : arg.ldelim;
528 docstring rdelim = arg.rdelim.empty() ?
529 from_ascii("}") : arg.rdelim;
530 os << ldelim << preset << rdelim;
531 } else if (!preset.empty()) {
532 docstring ldelim = arg.ldelim.empty() ?
533 from_ascii("[") : arg.ldelim;
534 docstring rdelim = arg.rdelim.empty() ?
535 from_ascii("]") : arg.rdelim;
536 os << ldelim << preset << rdelim;
537 } else if (find(required.begin(), required.end(),
538 (*lait).first) != required.end()) {
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 << rdelim;
550 if (runparams.for_search) {
551 // Mark end of arguments for findadv() only
552 os << "\\endarguments{}";
560 void pushLanguageName(string const & lang_name, bool localswitch)
562 OutputState * state = getOutputState();
564 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
565 state->lang_switch_depth_.push(nest_level);
566 state->open_polyglossia_lang_.push(lang_name);
570 void popLanguageName()
572 OutputState * state = getOutputState();
574 state->lang_switch_depth_.pop();
575 state->open_polyglossia_lang_.pop();
579 string const & openLanguageName()
581 OutputState * state = getOutputState();
583 return openLanguageName(state);
589 void addArgInsets(Paragraph const & par, string const & prefix,
590 Layout::LaTeXArgMap const & latexargs,
591 map<int, InsetArgument const *> & ilist,
592 vector<string> & required)
594 for (auto const & table : par.insetList()) {
595 InsetArgument const * arg = table.inset->asInsetArgument();
598 if (arg->name().empty()) {
599 LYXERR0("Error: Unnamed argument inset!");
602 string const name = prefix.empty() ?
603 arg->name() : split(arg->name(), ':');
604 // why converting into an integer?
605 unsigned int const nr = convert<unsigned int>(name);
606 if (ilist.find(nr) == ilist.end())
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.requires);
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<int, 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<int, 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
648 if (lyx::prev(pit, offset) == pars.begin())
650 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
651 if (priorpit->layout() == current_layout
652 && priorpit->params().depth() == current_depth)
658 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
660 for (; spit != pars.end(); ++spit) {
661 if (spit->layout() != current_layout ||
662 spit->params().depth() < current_depth)
664 if (spit->params().depth() > current_depth)
666 addArgInsets(*spit, prefix, latexargs, ilist, required);
668 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
672 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
673 OutputParams const & runparams,
674 Layout::LaTeXArgMap const & latexargs,
675 string const & prefix)
677 map<int, InsetArgument const *> ilist;
678 vector<string> required;
680 for (Paragraph const & par : pars) {
681 if (par.layout().hasArgs())
682 // The InsetArguments inside this paragraph refer to this paragraph
684 addArgInsets(par, prefix, latexargs, ilist, required);
686 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
692 // output the proper paragraph start according to latextype.
693 void parStartCommand(Paragraph const & par, otexstream & os,
694 OutputParams const & runparams, Layout const & style)
696 switch (style.latextype) {
698 if (par.needsCProtection(runparams.moving_arg)) {
699 if (contains(runparams.active_chars, '^'))
700 // cprotect relies on ^ being on catcode 7
701 os << "\\begingroup\\catcode`\\^=7";
704 os << '\\' << from_ascii(style.latexname());
707 if (!style.latexargs().empty())
708 latexArgInsets(par, os, runparams, style.latexargs());
709 os << from_ascii(style.latexparam());
711 case LATEX_ITEM_ENVIRONMENT:
712 case LATEX_LIST_ENVIRONMENT:
713 if (runparams.for_search) {
714 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
717 os << "\\" + style.itemcommand();
719 if (!style.itemargs().empty())
720 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
724 case LATEX_ENVIRONMENT:
725 if (runparams.for_search) {
726 os << "\\latexenvironment{" << style.latexname() << "}{";
729 case LATEX_BIB_ENVIRONMENT:
730 // ignore this, the inset will write itself
739 // FIXME: this should be anonymous
740 void TeXOnePar(Buffer const & buf,
744 OutputParams const & runparams_in,
745 string const & everypar,
746 int start_pos, int end_pos,
749 BufferParams const & bparams = runparams_in.is_child
750 ? buf.masterParams() : buf.params();
751 ParagraphList const & paragraphs = text.paragraphs();
752 Paragraph const & par = paragraphs.at(pit);
753 // FIXME This check should not really be needed.
754 // Perhaps we should issue an error if it is.
755 Layout const & style = text.inset().forcePlainLayout() ?
756 bparams.documentClass().plainLayout() : par.layout();
758 if (style.inpreamble && !force)
761 // Do not output empty commands if the whole paragraph has
762 // been deleted with ct and changes are not output.
763 if (!runparams_in.for_search && style.latextype != LATEX_ENVIRONMENT
764 && par.size() > 0 && par.isDeleted(0, par.size()) && !bparams.output_changes)
767 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
770 OutputParams runparams = runparams_in;
771 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
772 // We reinitialize par begin and end to be on the safe side
773 // with embedded inset as we don't know if they set those
775 runparams.par_begin = 0;
776 runparams.par_end = 0;
778 bool const maintext = text.isMainText();
779 // we are at the beginning of an inset and CJK is already open;
780 // we count inheritation levels to get the inset nesting right.
781 OutputState * state = getOutputState();
782 if (pit == 0 && !maintext
783 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
784 state->cjk_inherited_ += 1;
785 state->open_encoding_ = none;
788 // This paragraph is merged and we do not show changes in the output
789 bool const merged_par = !bparams.output_changes && par.parEndChange().deleted();
791 if (text.inset().isPassThru()) {
792 Font const outerfont = text.outerFont(pit);
794 // No newline before first paragraph in this lyxtext
795 if (pit > 0 && !text.inset().getLayout().parbreakIgnored() && !merged_par) {
797 if (!text.inset().getLayout().parbreakIsNewline())
801 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
805 Paragraph const * nextpar = runparams.isLastPar
806 ? nullptr : ¶graphs.at(pit + 1);
808 bool const intitle_command = style.intitle && style.isCommand();
809 // Intitle commands switch languages locally, thus increase
810 // language nesting level
812 state->nest_level_ += 1;
814 if (style.pass_thru) {
815 Font const outerfont = text.outerFont(pit);
816 parStartCommand(par, os, runparams, style);
817 if (style.isCommand() && style.needprotect)
818 // Due to the moving argument, some fragile
819 // commands (labels, index entries)
820 // are output after this command (#2154)
821 runparams.postpone_fragile_stuff = true;
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 = true;
939 // In some insets (such as Arguments), we cannot use \selectlanguage.
940 // Also, if an RTL language is set via environment in polyglossia,
941 // only a nested \\text<lang> command will reset the direction for LTR
942 // languages (see # 10111).
943 bool const in_polyglossia_rtl_env =
945 && runparams.local_font != nullptr
946 && outer_language->rightToLeft()
947 && !par_language->rightToLeft();
948 bool const localswitch =
949 (runparams_in.for_search
950 || text.inset().forceLocalFontSwitch()
951 || (using_begin_end && text.inset().forcePlainLayout())
952 || in_polyglossia_rtl_env)
953 && !text.inset().forceParDirectionSwitch();
955 lang_begin_command = use_polyglossia ?
956 "\\text$$lang$$opts{" : lyxrc.language_command_local;
957 lang_end_command = "}";
958 lang_command_termination.clear();
961 bool const localswitch_needed = localswitch && par_lang != outer_lang;
963 // localswitches need to be closed and reopened at each par
964 if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
965 // check if we already put language command in TeXEnvironment()
966 && !(style.isEnvironment()
967 && (pit == 0 || (priorpar->layout() != par.layout()
968 && priorpar->getDepth() <= par.getDepth())
969 || priorpar->getDepth() < par.getDepth())))) {
971 && (!using_begin_end || langOpenedAtThisLevel(state))
972 && !lang_end_command.empty()
973 && prev_lang != outer_lang
974 && !prev_lang.empty()
975 && (!using_begin_end || !style.isEnvironment())) {
976 os << from_ascii(subst(lang_end_command,
979 << lang_command_termination;
984 // We need to open a new language if we couldn't close the previous
985 // one (because there's no language_command_end); and even if we closed
986 // the previous one, if the current language is different than the
987 // outer_language (which is currently in effect once the previous one
989 if ((lang_end_command.empty() || par_lang != outer_lang
991 || (style.isEnvironment() && par_lang != prev_lang)))
992 && !par_lang.empty()) {
993 // If we're inside an inset, and that inset is within an \L or \R
994 // (or equivalents), then within the inset, too, any opposite
995 // language paragraph should appear within an \L or \R (in addition
996 // to, outside of, the normal language switch commands).
997 // This behavior is not correct for ArabTeX, though.
1000 && par_language->lang() != "arabic_arabtex"
1001 && outer_language->lang() != "arabic_arabtex"
1002 // are we in an inset?
1003 && runparams.local_font != nullptr
1004 // is the inset within an \L or \R?
1006 // FIXME: currently, we don't check this; this means that
1007 // we'll have unnnecessary \L and \R commands, but that
1008 // doesn't seem to hurt (though latex will complain)
1010 // is this paragraph in the opposite direction?
1011 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
1012 // FIXME: I don't have a working copy of the Arabi package, so
1013 // I'm not sure if the farsi and arabic_arabi stuff is correct
1015 if (par_language->lang() == "farsi")
1017 else if (outer_language->lang() == "farsi")
1019 else if (par_language->lang() == "arabic_arabi")
1021 else if (outer_language->lang() == "arabic_arabi")
1023 // remaining RTL languages currently is hebrew
1024 else if (par_language->rightToLeft())
1029 // With CJK, the CJK tag has to be closed first (see below)
1030 if ((runparams.encoding->package() != Encoding::CJK
1031 || bparams.useNonTeXFonts
1032 || runparams.for_search)
1033 && (par_lang != openLanguageName(state) || localswitch || intitle_command)
1034 && !par_lang.empty()) {
1035 string bc = use_polyglossia ?
1036 getPolyglossiaBegin(lang_begin_command, par_lang,
1037 par_language->polyglossiaOpts(),
1039 : subst(lang_begin_command, "$$lang", par_lang);
1041 os << lang_command_termination;
1042 if (using_begin_end)
1043 pushLanguageName(par_lang, localswitch);
1048 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
1049 // encoding, since this only affects the position of the outputted
1050 // \inputencoding command; the encoding switch will occur when necessary
1051 if (bparams.inputenc == "auto-legacy"
1052 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
1053 && runparams.encoding->package() != Encoding::japanese
1054 && runparams.encoding->package() != Encoding::none) {
1055 // Look ahead for future encoding changes.
1056 // We try to output them at the beginning of the paragraph,
1057 // since the \inputencoding command is not allowed e.g. in
1058 // sections. For this reason we only set runparams.moving_arg
1059 // after checking for the encoding change, otherwise the
1060 // change would be always avoided by switchEncoding().
1061 for (pos_type i = 0; i < par.size(); ++i) {
1062 char_type const c = par.getChar(i);
1063 Encoding const * const encoding =
1064 par.getFontSettings(bparams, i).language()->encoding();
1065 if (encoding->package() != Encoding::CJK
1066 && runparams.encoding->package() == Encoding::inputenc
1071 // All characters before c are in the ASCII range, and
1072 // c is non-ASCII (but no inset), so change the
1073 // encoding to that required by the language of c.
1074 // With CJK, only add switch if we have CJK content at the beginning
1076 if (i != 0 && encoding->package() == Encoding::CJK)
1079 pair<bool, int> enc_switch = switchEncoding(os.os(),
1080 bparams, runparams, *encoding);
1081 // the following is necessary after a CJK environment in a multilingual
1082 // context (nesting issue).
1083 if (par_language->encoding()->package() == Encoding::CJK
1084 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1085 os << "\\begin{CJK}{"
1086 << from_ascii(par_language->encoding()->latexName())
1087 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1088 state->open_encoding_ = CJK;
1090 if (encoding->package() != Encoding::none && enc_switch.first) {
1091 if (enc_switch.second > 0) {
1092 // the '%' is necessary to prevent unwanted whitespace
1095 // With CJK, the CJK tag had to be closed first (see above)
1096 if (runparams.encoding->package() == Encoding::CJK
1097 && par_lang != openLanguageName(state)
1098 && !par_lang.empty()) {
1099 os << subst(lang_begin_command, "$$lang", par_lang)
1100 << lang_command_termination;
1101 if (using_begin_end)
1102 pushLanguageName(par_lang, localswitch);
1104 runparams.encoding = encoding;
1110 runparams.moving_arg |= style.needprotect;
1111 if (style.needmboxprotect)
1112 ++runparams.inulemcmd;
1113 Encoding const * const prev_encoding = runparams.encoding;
1115 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1116 if (par.allowParagraphCustomization()) {
1117 if (par.params().startOfAppendix()) {
1118 os << "\n\\appendix\n";
1121 // InTitle commands must use switches (not environments)
1122 // inside the commands (see #9332)
1123 if (style.intitle) {
1124 if (!par.params().spacing().isDefault())
1126 if (runparams.moving_arg)
1128 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1131 if (!par.params().spacing().isDefault()
1132 && (pit == 0 || !priorpar->hasSameLayout(par)))
1134 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1138 if (style.isCommand()) {
1144 // For InTitle commands, we already started the command before
1145 // the language switch
1146 if (!intitle_command) {
1147 parStartCommand(par, os, runparams, style);
1148 if (style.isCommand() && style.needprotect)
1149 // Due to the moving argument, some fragile
1150 // commands (labels, index entries)
1151 // are output after this command (#2154)
1152 runparams.postpone_fragile_stuff = true;
1155 Font const outerfont = text.outerFont(pit);
1158 os << from_utf8(everypar);
1159 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1161 Font const font = par.empty()
1162 ? par.getLayoutFont(bparams, outerfont)
1163 : par.getFont(bparams, par.size() - 1, outerfont);
1165 bool const is_command = style.isCommand();
1167 // InTitle commands need to be closed after the language has been closed.
1168 if (!intitle_command) {
1171 if (!style.postcommandargs().empty())
1172 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1173 if (!runparams.post_macro.empty()) {
1174 // Output the stored fragile commands (labels, indices etc.)
1175 // that need to be output after the command with moving argument.
1176 os << runparams.post_macro;
1177 runparams.post_macro.clear();
1179 if (par.needsCProtection(runparams.moving_arg)
1180 && contains(runparams.active_chars, '^'))
1182 if (runparams.encoding != prev_encoding) {
1183 runparams.encoding = prev_encoding;
1184 os << setEncoding(prev_encoding->iconvName());
1189 bool pending_newline = false;
1190 bool unskip_newline = false;
1191 bool close_lang_switch = false;
1192 switch (style.latextype) {
1193 case LATEX_ITEM_ENVIRONMENT:
1194 case LATEX_LIST_ENVIRONMENT:
1195 if ((nextpar && par_lang != nextpar_lang
1196 && nextpar->getDepth() == par.getDepth())
1197 || (atSameLastLangSwitchDepth(state) && nextpar
1198 && nextpar->getDepth() < par.getDepth()))
1199 close_lang_switch = using_begin_end;
1200 if (nextpar && par.params().depth() < nextpar->params().depth())
1201 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1203 case LATEX_ENVIRONMENT: {
1204 // if it's the last paragraph of the current environment
1205 // skip it otherwise fall through
1207 && ((nextpar->layout() != par.layout()
1208 || nextpar->params().depth() != par.params().depth())
1209 || (!using_begin_end || par_lang != nextpar_lang)))
1211 close_lang_switch = using_begin_end;
1218 // we don't need it for the last paragraph and in InTitle commands!!!
1219 if (nextpar && !intitle_command)
1220 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1223 // InTitle commands use switches (not environments) for space settings
1224 if (par.allowParagraphCustomization() && !style.intitle) {
1225 if (!par.params().spacing().isDefault()
1226 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1227 if (pending_newline)
1230 string const endtag =
1231 par.params().spacing().writeEnvirEnd(useSetSpace);
1232 if (prefixIs(endtag, "\\end{"))
1235 os << from_ascii(endtag);
1236 pending_newline = true;
1240 // Closing the language is needed for the last paragraph in a given language
1241 // as well as for any InTitleCommand (since these set the language locally);
1242 // it is also needed if we're within an \L or \R that we may have opened above
1243 // (not necessarily in this paragraph) and are about to close.
1244 bool closing_rtl_ltr_environment = !using_begin_end
1246 && (par_language->lang() != "arabic_arabtex"
1247 && outer_language->lang() != "arabic_arabtex")
1248 // have we opened an \L or \R environment?
1249 && runparams.local_font != nullptr
1250 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1251 // are we about to close the language?
1252 &&((nextpar && par_lang != nextpar_lang)
1253 || (runparams.isLastPar && par_lang != outer_lang));
1255 if (localswitch_needed
1256 || (intitle_command && using_begin_end)
1257 || closing_rtl_ltr_environment
1258 || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1259 && (par_lang != outer_lang || (using_begin_end
1260 && style.isEnvironment()
1261 && par_lang != nextpar_lang)))) {
1262 // Since \selectlanguage write the language to the aux file,
1263 // we need to reset the language at the end of footnote or
1266 if (!localswitch && (pending_newline || close_lang_switch))
1269 // when the paragraph uses CJK, the language has to be closed earlier
1270 if ((font.language()->encoding()->package() != Encoding::CJK)
1271 || bparams.useNonTeXFonts
1272 || runparams_in.for_search) {
1273 if (lang_end_command.empty()) {
1274 // If this is a child, we should restore the
1275 // master language after the last paragraph.
1276 Language const * const current_language =
1277 (runparams.isLastPar && runparams.master_language)
1278 ? runparams.master_language
1280 string const current_lang = use_polyglossia
1281 ? getPolyglossiaEnvName(current_language)
1282 : current_language->babel();
1283 if (!current_lang.empty()
1284 && current_lang != openLanguageName(state)) {
1285 string bc = use_polyglossia ?
1286 getPolyglossiaBegin(lang_begin_command, current_lang,
1287 current_language->polyglossiaOpts(),
1289 : subst(lang_begin_command, "$$lang", current_lang);
1291 pending_newline = !localswitch
1292 && !text.inset().getLayout().parbreakIgnored();
1293 unskip_newline = !localswitch;
1294 if (using_begin_end)
1295 pushLanguageName(current_lang, localswitch);
1297 } else if ((!using_begin_end ||
1298 langOpenedAtThisLevel(state)) &&
1299 !par_lang.empty()) {
1300 // If we are in an environment, we have to
1301 // close the "outer" language afterwards
1302 string const & cur_lang = openLanguageName(state);
1303 if (!style.isEnvironment()
1304 || (close_lang_switch
1305 && atSameLastLangSwitchDepth(state)
1306 && par_lang != outer_lang
1307 && (par_lang != cur_lang
1308 || (cur_lang != outer_lang
1310 && style != nextpar->layout())))
1311 || (atSameLastLangSwitchDepth(state)
1312 && state->lang_switch_depth_.size()
1313 && cur_lang != par_lang)
1314 || in_polyglossia_rtl_env)
1316 if (using_begin_end && !localswitch)
1318 os << from_ascii(subst(
1322 pending_newline = !localswitch
1323 && !text.inset().getLayout().parbreakIgnored();
1324 unskip_newline = !localswitch;
1325 if (using_begin_end)
1331 if (closing_rtl_ltr_environment)
1334 // InTitle commands need to be closed after the language has been closed.
1335 if (intitle_command) {
1337 if (!style.postcommandargs().empty())
1338 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1339 if (!runparams.post_macro.empty()) {
1340 // Output the stored fragile commands (labels, indices etc.)
1341 // that need to be output after the command with moving argument.
1342 os << runparams.post_macro;
1343 runparams.post_macro.clear();
1345 if (par.needsCProtection(runparams.moving_arg)
1346 && contains(runparams.active_chars, '^'))
1348 if (runparams.encoding != prev_encoding) {
1349 runparams.encoding = prev_encoding;
1350 os << setEncoding(prev_encoding->iconvName());
1354 bool const last_was_separator =
1355 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1357 // Signify added/deleted par break in output if show changes in output
1358 if (nextpar && !os.afterParbreak() && !last_was_separator
1359 && bparams.output_changes && par.parEndChange().changed()) {
1360 Changes::latexMarkChange(os, bparams, Change(Change::UNCHANGED),
1361 par.parEndChange(), runparams);
1362 os << bparams.encoding().latexString(docstring(1, 0x00b6)).first << "}";
1365 if (pending_newline) {
1367 // prevent unwanted whitespace
1369 if (!os.afterParbreak() && !last_was_separator)
1373 // if this is a CJK-paragraph and the next isn't, close CJK
1374 // also if the next paragraph is a multilingual environment (because of nesting)
1375 if (nextpar && state->open_encoding_ == CJK
1376 && bparams.encoding().iconvName() != "UTF-8"
1377 && bparams.encoding().package() != Encoding::CJK
1378 && (nextpar_language->encoding()->package() != Encoding::CJK
1379 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1380 // inbetween environments, CJK has to be closed later (nesting!)
1381 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1382 os << "\\end{CJK}\n";
1383 state->open_encoding_ = none;
1386 // If this is the last paragraph, close the CJK environment
1387 // if necessary. If it's an environment or nested in an environment,
1388 // we'll have to \end that first.
1389 if (runparams.isLastPar && !style.isEnvironment()
1390 && par.params().depth() < 1) {
1391 switch (state->open_encoding_) {
1393 // do nothing at the end of child documents
1394 if (maintext && buf.masterBuffer() != &buf)
1396 // end of main text: also insert a \clearpage (see #5386)
1398 os << "\n\\clearpage\n\\end{CJK}\n";
1402 state->open_encoding_ = none;
1406 // FIXME: If we are in an inset and the switch happened outside this inset,
1407 // do not switch back at the end of the inset (bug #8479)
1408 // The following attempt does not help with listings-caption in a CJK document:
1409 // if (runparams_in.local_font != 0
1410 // && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1413 state->open_encoding_ = none;
1423 // Information about local language is stored as a font feature.
1424 // If this is the last paragraph of the inset and a local_font was set upon entering
1425 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1426 // ensure the encoding is set back to the default encoding of the local language.
1427 if (runparams.isLastPar && runparams_in.local_font != nullptr
1428 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1429 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1430 && !runparams.isFullUnicode()
1432 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1433 os << setEncoding(runparams_in.encoding->iconvName());
1435 // Otherwise, the current encoding should be set for the next paragraph.
1437 runparams_in.encoding = runparams.encoding;
1439 // Also pass the post_macros upstream
1440 runparams_in.post_macro = runparams.post_macro;
1443 // we don't need a newline for the last paragraph!!!
1444 // Note from JMarc: we will re-add a \n explicitly in
1445 // TeXEnvironment, because it is needed in this case
1446 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1447 Layout const & next_layout = nextpar->layout();
1448 if (!text.inset().getLayout().parbreakIgnored() && !merged_par)
1449 // Make sure to start a new line
1451 // A newline '\n' is always output before a command,
1452 // so avoid doubling it.
1453 if (!next_layout.isCommand()) {
1454 // Here we now try to avoid spurious empty lines by
1455 // outputting a paragraph break only if: (case 1) the
1456 // paragraph style allows parbreaks and no \begin, \end
1457 // or \item tags are going to follow (i.e., if the next
1458 // isn't the first or the current isn't the last
1459 // paragraph of an environment or itemize) and the
1460 // depth and alignment of the following paragraph is
1461 // unchanged, or (case 2) the following is a
1462 // non-environment paragraph whose depth is increased
1463 // but whose alignment is unchanged, or (case 3) the
1464 // paragraph is not an environment and the next one is a
1465 // non-itemize-like env at lower depth, or (case 4) the
1466 // paragraph is a command not followed by an environment
1467 // and the alignment of the current and next paragraph
1468 // is unchanged, or (case 5) the current alignment is
1469 // changed and a standard paragraph follows.
1470 DocumentClass const & tclass = bparams.documentClass();
1471 if ((style == next_layout
1472 && !style.parbreak_is_newline
1473 && !text.inset().getLayout().parbreakIsNewline()
1474 && !text.inset().getLayout().parbreakIgnored()
1475 && style.latextype != LATEX_ITEM_ENVIRONMENT
1476 && style.latextype != LATEX_LIST_ENVIRONMENT
1477 && style.align == par.getAlign(bparams)
1478 && nextpar->getDepth() == par.getDepth()
1479 && nextpar->getAlign(bparams) == par.getAlign(bparams))
1480 || (!next_layout.isEnvironment()
1481 && nextpar->getDepth() > par.getDepth()
1482 && nextpar->getAlign(bparams) == next_layout.align)
1483 || (!style.isEnvironment()
1484 && next_layout.latextype == LATEX_ENVIRONMENT
1485 && nextpar->getDepth() < par.getDepth())
1486 || (style.isCommand()
1487 && !next_layout.isEnvironment()
1488 && style.align == par.getAlign(bparams)
1489 && next_layout.align == nextpar->getAlign(bparams))
1490 || (style.align != par.getAlign(bparams)
1491 && tclass.isDefaultLayout(next_layout))) {
1492 // and omit paragraph break if it has been deleted with ct
1493 // and changes are not shown in output
1500 // Reset language nesting level after intitle command
1501 if (intitle_command)
1502 state->nest_level_ -= 1;
1504 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1505 << &par << " next " << nextpar);
1511 // LaTeX all paragraphs
1512 void latexParagraphs(Buffer const & buf,
1515 OutputParams const & runparams,
1516 string const & everypar)
1518 LASSERT(runparams.par_begin <= runparams.par_end,
1519 { os << "% LaTeX Output Error\n"; return; } );
1521 BufferParams const & bparams = buf.params();
1522 BufferParams const & mparams = buf.masterParams();
1524 bool const maintext = text.isMainText();
1525 bool const is_child = buf.masterBuffer() != &buf;
1526 bool const multibib_child = maintext && is_child
1527 && mparams.multibib == "child";
1529 if (multibib_child && mparams.useBiblatex())
1530 os << "\\newrefsection";
1531 else if (multibib_child && mparams.useBibtopic()
1532 && !buf.masterBibInfo().empty()) {
1533 os << "\\begin{btUnit}\n";
1534 runparams.openbtUnit = true;
1537 // Open a CJK environment at the beginning of the main buffer
1538 // if the document's main encoding requires the CJK package
1539 // or the document encoding is utf8 and the CJK package is required
1540 // (but not in child documents or documents using system fonts):
1541 OutputState * state = getOutputState();
1542 if (maintext && !is_child && !bparams.useNonTeXFonts
1543 && (bparams.encoding().package() == Encoding::CJK
1544 || (bparams.encoding().name() == "utf8"
1545 && runparams.use_CJK))
1547 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1548 ? from_ascii("UTF8")
1549 : from_ascii(bparams.encoding().latexName());
1550 os << "\\begin{CJK}{" << cjkenc
1551 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1552 state->open_encoding_ = CJK;
1554 // if "auto begin" is switched off, explicitly switch the
1555 // language on at start
1556 string const mainlang = runparams.use_polyglossia
1557 ? getPolyglossiaEnvName(bparams.language)
1558 : bparams.language->babel();
1559 string const lang_begin_command = runparams.use_polyglossia ?
1560 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1561 string const lang_end_command = runparams.use_polyglossia ?
1562 "\\end{$$lang}" : lyxrc.language_command_end;
1563 bool const using_begin_end = runparams.use_polyglossia ||
1564 !lang_end_command.empty();
1566 if (maintext && !lyxrc.language_auto_begin &&
1567 !mainlang.empty()) {
1569 string bc = runparams.use_polyglossia ?
1570 getPolyglossiaBegin(lang_begin_command, mainlang,
1571 bparams.language->polyglossiaOpts())
1572 : subst(lang_begin_command, "$$lang", mainlang);
1575 if (using_begin_end)
1576 pushLanguageName(mainlang);
1579 ParagraphList const & paragraphs = text.paragraphs();
1581 if (runparams.par_begin == runparams.par_end) {
1582 // The full doc will be exported but it is easier to just rely on
1583 // runparams range parameters that will be passed TeXEnvironment.
1584 runparams.par_begin = 0;
1585 runparams.par_end = paragraphs.size();
1588 pit_type pit = runparams.par_begin;
1589 // lastpit is for the language check after the loop.
1590 pit_type lastpit = pit;
1591 // variables used in the loop:
1592 bool was_title = false;
1593 bool already_title = false;
1594 DocumentClass const & tclass = bparams.documentClass();
1596 // Did we already warn about inTitle layout mixing? (we only warn once)
1597 bool gave_layout_warning = false;
1598 for (; pit < runparams.par_end; ++pit) {
1600 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1602 // FIXME This check should not be needed. We should
1603 // perhaps issue an error if it is.
1604 Layout const & layout = text.inset().forcePlainLayout() ?
1605 tclass.plainLayout() : par->layout();
1607 if (layout.intitle) {
1608 if (already_title) {
1609 if (!gave_layout_warning && !runparams.dryrun) {
1610 gave_layout_warning = true;
1611 frontend::Alert::warning(_("Error in latexParagraphs"),
1612 bformat(_("You are using at least one "
1613 "layout (%1$s) intended for the title, "
1614 "after using non-title layouts. This "
1615 "could lead to missing or incorrect output."
1618 } else if (!was_title) {
1620 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1622 << from_ascii(tclass.titlename())
1626 } else if (was_title && !already_title && !layout.inpreamble) {
1627 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1628 os << "\\end{" << from_ascii(tclass.titlename())
1632 os << "\\" << from_ascii(tclass.titlename())
1635 already_title = true;
1639 if (layout.isCommand() && !layout.latexname().empty()
1640 && layout.latexname() == bparams.multibib) {
1641 if (runparams.openbtUnit)
1642 os << "\\end{btUnit}\n";
1643 if (!bparams.useBiblatex()
1644 && !buf.masterBibInfo().empty()) {
1645 os << '\n' << "\\begin{btUnit}\n";
1646 runparams.openbtUnit = true;
1650 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1651 // This is a standard top level paragraph, TeX it and continue.
1652 TeXOnePar(buf, text, pit, os, runparams, everypar);
1656 // Do not output empty environments if the whole paragraph has
1657 // been deleted with ct and changes are not output.
1658 if (size_t(pit + 1) < paragraphs.size()) {
1659 ParagraphList::const_iterator nextpar = paragraphs.constIterator(pit + 1);
1660 Paragraph const & cpar = paragraphs.at(pit);
1661 if ((par->layout() != nextpar->layout()
1662 || par->params().depth() == nextpar->params().depth()
1663 || par->params().leftIndent() == nextpar->params().leftIndent())
1664 && !runparams.for_search && cpar.size() > 0
1665 && cpar.isDeleted(0, cpar.size()) && !bparams.output_changes) {
1666 if (!bparams.output_changes && !cpar.parEndChange().deleted())
1672 TeXEnvironmentData const data =
1673 prepareEnvironment(buf, text, par, os, runparams);
1674 // pit can be changed in TeXEnvironment.
1675 TeXEnvironment(buf, text, runparams, pit, os);
1676 finishEnvironment(os, runparams, data);
1679 // FIXME: uncomment the content or remove this block
1680 if (pit == runparams.par_end) {
1681 // Make sure that the last paragraph is
1682 // correctly terminated (because TeXOnePar does
1683 // not add a \n in this case)
1687 // It might be that we only have a title in this document
1688 if (was_title && !already_title) {
1689 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1690 os << "\\end{" << from_ascii(tclass.titlename())
1693 os << "\\" << from_ascii(tclass.titlename())
1698 if (maintext && !is_child && runparams.openbtUnit)
1699 os << "\\end{btUnit}\n";
1701 // if "auto end" is switched off, explicitly close the language at the end
1702 // but only if the last par is in a babel or polyglossia language
1703 Language const * const lastpar_language =
1704 paragraphs.at(lastpit).getParLanguage(bparams);
1705 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1706 lastpar_language->encoding()->package() != Encoding::CJK) {
1707 os << from_utf8(subst(lang_end_command,
1711 // If we have language_auto_begin, the stack will
1712 // already be empty, nothing to pop()
1713 if (using_begin_end && !lyxrc.language_auto_begin)
1717 // If the last paragraph is an environment, we'll have to close
1718 // CJK at the very end to do proper nesting.
1719 if (maintext && !is_child && state->open_encoding_ == CJK) {
1720 os << "\\clearpage\n\\end{CJK}\n";
1721 state->open_encoding_ = none;
1723 // Likewise for polyglossia or when using begin/end commands
1724 // or at the very end of an active branch inset with a language switch
1725 Language const * const outer_language = (runparams.local_font != nullptr)
1726 ? runparams.local_font->language() : bparams.language;
1727 string const & prev_lang = runparams.use_polyglossia
1728 ? getPolyglossiaEnvName(outer_language)
1729 : outer_language->babel();
1730 string const lastpar_lang = runparams.use_polyglossia ?
1731 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1732 string const & cur_lang = openLanguageName(state);
1733 if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1734 || (maintext && !is_child)) && !cur_lang.empty()) {
1735 os << from_utf8(subst(lang_end_command,
1739 if (using_begin_end)
1741 } else if (runparams.inbranch && !using_begin_end
1742 && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1743 // with !using_begin_end, cur_lang is empty, so we need to
1744 // compare against the paragraph language (and we are in the
1745 // last paragraph at this point)
1746 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1749 // reset inherited encoding
1750 if (state->cjk_inherited_ > 0) {
1751 state->cjk_inherited_ -= 1;
1752 if (state->cjk_inherited_ == 0)
1753 state->open_encoding_ = CJK;
1756 if (multibib_child && mparams.useBibtopic()) {
1757 os << "\\end{btUnit}\n";
1758 runparams.openbtUnit = false;
1762 // Switch the input encoding for some part(s) of the document.
1763 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1764 OutputParams const & runparams, Encoding const & newEnc,
1765 bool force, bool noswitchmacro)
1767 // Never switch encoding with XeTeX/LuaTeX
1768 // or if we're in a moving argument or inherit the outer encoding.
1769 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1770 return make_pair(false, 0);
1772 // Only switch for auto-selected legacy encodings (inputenc setting
1773 // "auto-legacy" or "auto-legacy-plain").
1774 // The "listings" environment can force a switch also with other
1775 // encoding settings (it does not support variable width encodings
1776 // (utf8, jis, ...) under 8-bit latex engines).
1777 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1778 || runparams.moving_arg))
1779 return make_pair(false, 0);
1781 Encoding const & oldEnc = *runparams.encoding;
1782 // Do not switch, if the encoding is unchanged or switching is not supported.
1783 if (oldEnc.name() == newEnc.name()
1784 || oldEnc.package() == Encoding::japanese
1785 || oldEnc.package() == Encoding::none
1786 || newEnc.package() == Encoding::none
1787 || runparams.for_search)
1788 return make_pair(false, 0);
1789 // FIXME We ignore encoding switches from/to encodings that do
1790 // neither support the inputenc package nor the CJK package here.
1791 // This may fail for characters not supported by "unicodesymbols"
1792 // or for non-ASCII characters in "listings"
1793 // but it is the best we can do.
1796 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1797 << oldEnc.name() << " to " << newEnc.name());
1798 os << setEncoding(newEnc.iconvName());
1799 if (bparams.inputenc == "auto-legacy-plain")
1800 return make_pair(true, 0);
1802 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1803 OutputState * state = getOutputState();
1804 switch (newEnc.package()) {
1805 case Encoding::none:
1806 case Encoding::japanese:
1807 // shouldn't ever reach here (see above) but avoids warning.
1808 return make_pair(true, 0);
1809 case Encoding::inputenc: {
1810 int count = inputenc_arg.length();
1811 if (oldEnc.package() == Encoding::CJK &&
1812 state->open_encoding_ == CJK) {
1814 state->open_encoding_ = none;
1817 else if (oldEnc.package() == Encoding::inputenc &&
1818 state->open_encoding_ == inputenc) {
1820 state->open_encoding_ = none;
1823 if (runparams.local_font != nullptr
1824 && oldEnc.package() == Encoding::CJK) {
1825 // within insets, \inputenc switches need
1826 // to be embraced within \bgroup...\egroup;
1830 state->open_encoding_ = inputenc;
1833 return make_pair(true, count);
1834 os << "\\inputencoding{" << inputenc_arg << '}';
1835 return make_pair(true, count + 16);
1837 case Encoding::CJK: {
1838 int count = inputenc_arg.length();
1839 if (oldEnc.package() == Encoding::CJK &&
1840 state->open_encoding_ == CJK) {
1844 if (oldEnc.package() == Encoding::inputenc &&
1845 state->open_encoding_ == inputenc) {
1849 os << "\\begin{CJK}{"
1850 << from_ascii(newEnc.latexName()) << "}{"
1851 << from_ascii(bparams.fonts_cjk) << "}";
1852 state->open_encoding_ = CJK;
1853 return make_pair(true, count + 15);
1856 // Dead code to avoid a warning:
1857 return make_pair(true, 0);