2 * \file output_latex.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
13 #include "output_latex.h"
15 #include "BiblioInfo.h"
17 #include "BufferParams.h"
20 #include "InsetList.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "texstream.h"
27 #include "TextClass.h"
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetArgument.h"
32 #include "frontends/alert.h"
34 #include "support/lassert.h"
35 #include "support/convert.h"
36 #include "support/debug.h"
37 #include "support/lstrings.h"
38 #include "support/textutils.h"
39 #include "support/gettext.h"
41 #include <QThreadStorage>
47 using namespace lyx::support;
63 OutputState() : prev_env_language_(nullptr), open_encoding_(none),
64 cjk_inherited_(0), nest_level_(0)
67 Language const * prev_env_language_;
68 stack<int> lang_switch_depth_; // Both are always empty when
69 stack<string> open_polyglossia_lang_; // not using polyglossia
70 OpenEncoding open_encoding_;
76 OutputState * getOutputState()
78 // FIXME An instance of OutputState should be kept around for each export
79 // instead of using local thread storage
80 static QThreadStorage<OutputState *> outputstate;
81 if (!outputstate.hasLocalData())
82 outputstate.setLocalData(new OutputState);
83 return outputstate.localData();
87 string const & openLanguageName(OutputState const * state)
89 // Return a reference to the last active language opened with
90 // polyglossia or when using begin/end commands. If none or when
91 // using babel with only a begin command, return a reference to
94 static string const empty;
96 return state->open_polyglossia_lang_.empty()
98 : state->open_polyglossia_lang_.top();
102 bool atSameLastLangSwitchDepth(OutputState const * state)
104 // Return true if the actual nest level is the same at which the
105 // language was switched when using polyglossia or begin/end
106 // commands. Instead, return always true when using babel with
107 // only a begin command.
109 return state->lang_switch_depth_.empty()
111 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
115 bool isLocalSwitch(OutputState const * state)
117 // Return true if the language was opened by a local command switch.
119 return !state->lang_switch_depth_.empty()
120 && state->lang_switch_depth_.top() < 0;
124 bool langOpenedAtThisLevel(OutputState const * state)
126 // Return true if the language was opened at the current nesting level.
128 return !state->lang_switch_depth_.empty()
129 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
133 string const getPolyglossiaEnvName(Language const * lang)
135 string result = lang->polyglossia();
136 if (result == "arabic")
137 // exceptional spelling; see polyglossia docs.
143 string const getPolyglossiaBegin(string const & lang_begin_command,
144 string const & lang, string const & opts,
145 bool const localswitch = false)
149 // we need to revert the upcasing done in getPolyglossiaEnvName()
150 // in case we have a local polyglossia command (\textarabic).
151 string language = localswitch ? ascii_lowercase(lang) : lang;
152 result = subst(lang_begin_command, "$$lang", language);
154 string options = opts.empty() ?
155 string() : "[" + opts + "]";
156 result = subst(result, "$$opts", options);
162 struct TeXEnvironmentData
164 Layout const * style;
165 Language const * par_language;
166 Encoding const * prev_encoding;
168 bool leftindent_open;
172 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
174 ParagraphList::const_iterator pit,
176 OutputParams const & runparams)
178 TeXEnvironmentData data;
180 BufferParams const & bparams = buf.params();
182 // FIXME This test should not be necessary.
183 // We should perhaps issue an error if it is.
184 Layout const & style = text.inset().forcePlainLayout() ?
185 bparams.documentClass().plainLayout() : pit->layout();
187 ParagraphList const & paragraphs = text.paragraphs();
188 bool const firstpar = pit == paragraphs.begin();
189 ParagraphList::const_iterator const priorpit =
190 firstpar ? pit : prev(pit, 1);
192 OutputState * state = getOutputState();
193 bool const use_prev_env_language = state->prev_env_language_ != nullptr
194 && priorpit->layout().isEnvironment()
195 && (priorpit->getDepth() > pit->getDepth()
196 || (priorpit->getDepth() == pit->getDepth()
197 && priorpit->layout() != pit->layout()));
199 data.prev_encoding = runparams.encoding;
200 data.par_language = pit->getParLanguage(bparams);
201 Language const * const doc_language = bparams.language;
202 Language const * const prev_par_language =
203 // use font at inset or document language in first paragraph
204 firstpar ? (runparams.local_font ?
205 runparams.local_font->language()
207 : (use_prev_env_language ?
208 state->prev_env_language_
209 : priorpit->getParLanguage(bparams));
211 bool const use_polyglossia = runparams.use_polyglossia;
212 string const par_lang = use_polyglossia ?
213 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
214 string const prev_par_lang = use_polyglossia ?
215 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
216 string const doc_lang = use_polyglossia ?
217 getPolyglossiaEnvName(doc_language) : doc_language->babel();
218 string const lang_begin_command = use_polyglossia ?
219 "\\begin{$$lang}" : lyxrc.language_command_begin;
220 string const lang_end_command = use_polyglossia ?
221 "\\end{$$lang}" : lyxrc.language_command_end;
222 bool const using_begin_end = use_polyglossia ||
223 !lang_end_command.empty();
225 // For polyglossia, switch language outside of environment, if possible.
226 // However, if we are at the start of an inset, do not close languages
228 if (par_lang != prev_par_lang) {
230 && (!using_begin_end || langOpenedAtThisLevel(state))
231 && !lang_end_command.empty()
232 && prev_par_lang != doc_lang
233 && !prev_par_lang.empty()) {
234 os << from_ascii(subst(
238 // the '%' is necessary to prevent unwanted whitespace
244 // If no language was explicitly opened and we are using
245 // polyglossia or begin/end commands, then the current
246 // language is the document language.
247 string const & cur_lang = using_begin_end
248 && !state->lang_switch_depth_.empty()
249 ? openLanguageName(state)
252 if ((lang_end_command.empty() ||
253 par_lang != doc_lang ||
254 par_lang != cur_lang) &&
256 string bc = use_polyglossia ?
257 getPolyglossiaBegin(lang_begin_command, par_lang,
258 data.par_language->polyglossiaOpts())
259 : subst(lang_begin_command, "$$lang", par_lang);
261 // the '%' is necessary to prevent unwanted whitespace
264 pushLanguageName(par_lang);
268 data.leftindent_open = false;
269 if (!pit->params().leftIndent().zero()) {
270 os << "\\begin{LyXParagraphLeftIndent}{"
271 << from_ascii(pit->params().leftIndent().asLatexString())
273 data.leftindent_open = true;
276 if (style.isEnvironment())
277 state->nest_level_ += 1;
279 if (style.isEnvironment() && !style.latexname().empty()) {
280 os << "\\begin{" << from_ascii(style.latexname()) << '}';
281 if (!style.latexargs().empty()) {
282 OutputParams rp = runparams;
283 rp.local_font = &pit->getFirstFontSettings(bparams);
284 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
286 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
288 << pit->params().labelWidthString()
290 } else if (style.labeltype == LABEL_BIBLIO) {
291 if (pit->params().labelWidthString().empty())
292 os << '{' << bibitemWidest(buf, runparams) << "}\n";
295 << pit->params().labelWidthString()
298 os << from_ascii(style.latexparam()) << '\n';
299 if (style.latextype == LATEX_BIB_ENVIRONMENT
300 || style.latextype == LATEX_ITEM_ENVIRONMENT
301 || style.latextype == LATEX_LIST_ENVIRONMENT) {
302 OutputParams rp = runparams;
303 rp.local_font = &pit->getFirstFontSettings(bparams);
304 latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
310 // in multilingual environments, the CJK tags have to be nested properly
311 data.cjk_nested = false;
312 if (!bparams.useNonTeXFonts
313 && (bparams.inputenc == "auto-legacy"
314 || bparams.inputenc == "auto-legacy-plain")
315 && data.par_language->encoding()->package() == Encoding::CJK
316 && state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
317 if (prev_par_language->encoding()->package() == Encoding::CJK) {
318 os << "\\begin{CJK}{"
319 << from_ascii(data.par_language->encoding()->latexName())
320 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
322 state->open_encoding_ = CJK;
323 data.cjk_nested = true;
329 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
330 TeXEnvironmentData const & data, bool const maintext,
333 OutputState * state = getOutputState();
334 // BufferParams const & bparams = buf.params();
335 // FIXME: for speedup shortcut below, would require passing of "buf" as argument
336 if (state->open_encoding_ == CJK && data.cjk_nested) {
337 // We need to close the encoding even if it does not change
338 // to do correct environment nesting
339 os << "\\end{CJK}\n";
340 state->open_encoding_ = none;
343 if (data.style->isEnvironment()) {
345 bool const using_begin_end =
346 runparams.use_polyglossia ||
347 !lyxrc.language_command_end.empty();
348 // Close any language opened at this nest level
349 if (using_begin_end) {
350 while (langOpenedAtThisLevel(state)) {
351 if (isLocalSwitch(state)) {
355 << openLanguageName(state)
361 if (data.style->latextype == LATEX_BIB_ENVIRONMENT)
362 // bibliography needs a blank line after
363 // each item for backref to function properly
366 state->nest_level_ -= 1;
367 string const & name = data.style->latexname();
369 os << "\\end{" << from_ascii(name) << "}\n";
370 state->prev_env_language_ = data.par_language;
371 if (runparams.encoding != data.prev_encoding) {
372 runparams.encoding = data.prev_encoding;
373 os << setEncoding(data.prev_encoding->iconvName());
375 // If this is the last par of an inset, the language needs
376 // to be closed after the environment
377 if (lastpar && !maintext) {
378 if (using_begin_end && langOpenedAtThisLevel(state)) {
379 if (isLocalSwitch(state)) {
383 << openLanguageName(state)
391 if (data.leftindent_open) {
392 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
393 state->prev_env_language_ = data.par_language;
394 if (runparams.encoding != data.prev_encoding) {
395 runparams.encoding = data.prev_encoding;
396 os << setEncoding(data.prev_encoding->iconvName());
400 // Check whether we should output a blank line after the environment
401 if (!data.style->nextnoindent)
406 void TeXEnvironment(Buffer const & buf, Text const & text,
407 OutputParams const & runparams,
408 pit_type & pit, otexstream & os)
410 ParagraphList const & paragraphs = text.paragraphs();
411 ParagraphList::const_iterator ipar = paragraphs.iterator_at(pit);
412 LYXERR(Debug::OUTFILE, "TeXEnvironment for paragraph " << pit);
414 Layout const & current_layout = ipar->layout();
415 depth_type const current_depth = ipar->params().depth();
416 Length const & current_left_indent = ipar->params().leftIndent();
418 // This is for debugging purpose at the end.
419 pit_type const par_begin = pit;
420 for (; pit < runparams.par_end; ++pit) {
421 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
423 // check first if this is an higher depth paragraph.
424 bool go_out = (par->params().depth() < current_depth);
425 if (par->params().depth() == current_depth) {
426 // This environment is finished.
427 go_out |= (par->layout() != current_layout);
428 go_out |= (par->params().leftIndent() != current_left_indent);
431 // nothing to do here, restore pit and go out.
436 if (par->layout() == current_layout
437 && par->params().depth() == current_depth
438 && par->params().leftIndent() == current_left_indent) {
439 // We are still in the same environment so TeXOnePar and continue;
440 TeXOnePar(buf, text, pit, os, runparams);
444 // We are now in a deeper environment.
445 // Either par->layout() != current_layout
446 // Or par->params().depth() > current_depth
447 // Or par->params().leftIndent() != current_left_indent)
449 // FIXME This test should not be necessary.
450 // We should perhaps issue an error if it is.
451 bool const force_plain_layout = text.inset().forcePlainLayout();
452 Layout const & style = force_plain_layout
453 ? buf.params().documentClass().plainLayout()
456 if (!style.isEnvironment()) {
457 // This is a standard paragraph, no need to call TeXEnvironment.
458 TeXOnePar(buf, text, pit, os, runparams);
462 // Do not output empty environments if the whole paragraph has
463 // been deleted with ct and changes are not output.
465 if (!runparams.find_effective())
466 output_changes = buf.params().output_changes;
468 output_changes = runparams.find_with_deleted();
469 if (size_t(pit + 1) < paragraphs.size()) {
470 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
471 Paragraph const & cpar = paragraphs.at(pit);
472 if ((par->layout() != nextpar->layout()
473 || par->params().depth() == nextpar->params().depth()
474 || par->params().leftIndent() == nextpar->params().leftIndent())
476 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
477 if (!output_changes && !cpar.parEndChange().deleted())
483 // This is a new environment.
484 TeXEnvironmentData const data =
485 prepareEnvironment(buf, text, par, os, runparams);
486 // Recursive call to TeXEnvironment!
487 TeXEnvironment(buf, text, runparams, pit, os);
488 bool const lastpar = size_t(pit + 1) >= paragraphs.size();
489 finishEnvironment(os, runparams, data, text.isMainText(), lastpar);
492 if (pit != runparams.par_end)
493 LYXERR(Debug::OUTFILE, "TeXEnvironment for paragraph " << par_begin << " done.");
497 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
498 map<size_t, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
500 size_t const argnr = latexargs.size();
504 // Default and preset args are always output, so if they require
505 // other arguments, consider this.
506 for (auto const & larg : latexargs) {
507 Layout::latexarg const & arg = larg.second;
508 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.required.empty()) {
509 vector<string> req = getVectorFromString(arg.required);
510 required.insert(required.end(), req.begin(), req.end());
514 for (size_t i = 1; i <= argnr; ++i) {
515 map<size_t, InsetArgument const *>::const_iterator lit = ilist.find(i);
516 bool inserted = false;
517 if (lit != ilist.end()) {
518 InsetArgument const * ins = lit->second;
520 Layout::LaTeXArgMap::const_iterator const lait =
521 latexargs.find(ins->name());
522 if (lait != latexargs.end()) {
523 Layout::latexarg arg = lait->second;
527 ldelim = arg.mandatory ?
528 from_ascii("{") : from_ascii("[");
529 rdelim = arg.mandatory ?
530 from_ascii("}") : from_ascii("]");
532 if (!arg.ldelim.empty())
534 if (!arg.rdelim.empty())
536 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
537 if (prefix == "listpreamble:")
544 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
545 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
546 for (; lait != laend; ++lait) {
547 string const name = prefix + convert<string>(i);
548 if ((*lait).first == name) {
549 Layout::latexarg arg = (*lait).second;
550 docstring preset = arg.presetarg;
551 if (!arg.defaultarg.empty()) {
554 preset += arg.defaultarg;
557 docstring ldelim = arg.ldelim.empty() ?
558 from_ascii("{") : arg.ldelim;
559 docstring rdelim = arg.rdelim.empty() ?
560 from_ascii("}") : arg.rdelim;
561 os << ldelim << preset << rdelim;
562 } else if (!preset.empty()) {
563 docstring ldelim = arg.ldelim.empty() ?
564 from_ascii("[") : arg.ldelim;
565 docstring rdelim = arg.rdelim.empty() ?
566 from_ascii("]") : arg.rdelim;
567 os << ldelim << preset << rdelim;
568 } else if (find(required.begin(), required.end(),
569 (*lait).first) != required.end()) {
570 docstring ldelim = arg.ldelim.empty() ?
571 from_ascii("[") : arg.ldelim;
572 docstring rdelim = arg.rdelim.empty() ?
573 from_ascii("]") : arg.rdelim;
574 os << ldelim << rdelim;
581 if (runparams.find_effective() && argnr > 1) {
582 // Mark end of arguments for findadv() only
583 os << "\\endarguments{}";
591 void pushLanguageName(string const & lang_name, bool localswitch)
593 OutputState * state = getOutputState();
595 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
596 state->lang_switch_depth_.push(nest_level);
597 state->open_polyglossia_lang_.push(lang_name);
601 void popLanguageName()
603 OutputState * state = getOutputState();
605 state->lang_switch_depth_.pop();
606 state->open_polyglossia_lang_.pop();
610 bool languageStackEmpty()
612 OutputState * state = getOutputState();
614 return state->lang_switch_depth_.empty();
618 string const & openLanguageName()
620 OutputState * state = getOutputState();
622 return openLanguageName(state);
628 void addArgInsets(Paragraph const & par, string const & prefix,
629 Layout::LaTeXArgMap const & latexargs,
630 map<size_t, InsetArgument const *> & ilist,
631 vector<string> & required)
633 for (auto const & table : par.insetList()) {
634 InsetArgument const * arg = table.inset->asInsetArgument();
637 if (arg->name().empty()) {
638 LYXERR0("Error: Unnamed argument inset!");
641 string const name = prefix.empty() ?
642 arg->name() : split(arg->name(), ':');
643 size_t const nr = convert<size_t>(name);
644 ilist.insert({nr, arg});
645 Layout::LaTeXArgMap::const_iterator const lit =
646 latexargs.find(arg->name());
647 if (lit != latexargs.end()) {
648 Layout::latexarg const & larg = lit->second;
649 vector<string> req = getVectorFromString(larg.required);
650 move(req.begin(), req.end(), back_inserter(required));
658 void latexArgInsets(Paragraph const & par, otexstream & os,
659 OutputParams const & runparams,
660 Layout::LaTeXArgMap const & latexargs,
661 string const & prefix)
663 map<size_t, InsetArgument const *> ilist;
664 vector<string> required;
665 addArgInsets(par, prefix, latexargs, ilist, required);
666 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
670 void latexArgInsets(ParagraphList const & pars,
671 ParagraphList::const_iterator pit,
672 otexstream & os, OutputParams const & runparams,
673 Layout::LaTeXArgMap const & latexargs,
674 string const & prefix)
676 map<size_t, InsetArgument const *> ilist;
677 vector<string> required;
679 depth_type const current_depth = pit->params().depth();
680 Layout const current_layout = pit->layout();
682 // get the first paragraph in sequence with this layout and depth
683 ptrdiff_t offset = 0;
685 if (prev(pit, offset) == pars.begin())
687 ParagraphList::const_iterator priorpit = prev(pit, offset + 1);
688 if (priorpit->layout() == current_layout
689 && priorpit->params().depth() == current_depth)
695 ParagraphList::const_iterator spit = prev(pit, offset);
696 for (; spit != pars.end(); ++spit) {
697 if (spit->layout() != current_layout ||
698 spit->params().depth() < current_depth)
700 if (spit->params().depth() > current_depth)
702 addArgInsets(*spit, prefix, latexargs, ilist, required);
704 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
708 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
709 OutputParams const & runparams,
710 Layout::LaTeXArgMap const & latexargs,
711 string const & prefix)
713 map<size_t, InsetArgument const *> ilist;
714 vector<string> required;
716 for (Paragraph const & par : pars) {
717 if (par.layout().hasArgs())
718 // The InsetArguments inside this paragraph refer to this paragraph
720 addArgInsets(par, prefix, latexargs, ilist, required);
722 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
728 // output the proper paragraph start according to latextype.
729 void parStartCommand(Paragraph const & par, otexstream & os,
730 OutputParams const & runparams, Layout const & style)
732 switch (style.latextype) {
734 if (par.needsCProtection(runparams.moving_arg)) {
735 if (contains(runparams.active_chars, '^'))
736 // cprotect relies on ^ being on catcode 7
737 os << "\\begingroup\\catcode`\\^=7";
740 os << '\\' << from_ascii(style.latexname());
743 if (!style.latexargs().empty())
744 latexArgInsets(par, os, runparams, style.latexargs());
745 os << from_ascii(style.latexparam());
747 case LATEX_ITEM_ENVIRONMENT:
748 case LATEX_LIST_ENVIRONMENT:
749 if (runparams.find_effective()) {
750 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
753 os << "\\" + style.itemcommand();
755 if (!style.itemargs().empty())
756 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
760 case LATEX_ENVIRONMENT:
761 if (runparams.find_effective()) {
762 os << "\\latexenvironment{" << style.latexname() << "}{";
765 case LATEX_BIB_ENVIRONMENT:
766 // ignore this, the inset will write itself
775 // FIXME: this should be anonymous
776 void TeXOnePar(Buffer const & buf,
780 OutputParams const & runparams_in,
781 string const & everypar,
782 int start_pos, int end_pos,
785 BufferParams const & bparams = runparams_in.is_child
786 ? buf.masterParams() : buf.params();
787 ParagraphList const & paragraphs = text.paragraphs();
788 Paragraph const & par = paragraphs.at(pit);
789 // FIXME This check should not really be needed.
790 // Perhaps we should issue an error if it is.
791 Layout const & style = text.inset().forcePlainLayout() ?
792 bparams.documentClass().plainLayout() : par.layout();
794 if (style.inpreamble && !force)
797 // Do not output empty commands if the whole paragraph has
798 // been deleted with ct and changes are not output.
799 if (!runparams_in.find_with_deleted() && style.latextype != LATEX_ENVIRONMENT
800 && !par.empty() && par.isDeleted(0, par.size()) && !bparams.output_changes)
803 LYXERR(Debug::OUTFILE, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
806 OutputParams runparams = runparams_in;
807 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
808 // We reinitialize par begin and end to be on the safe side
809 // with embedded inset as we don't know if they set those
811 runparams.par_begin = 0;
812 runparams.par_end = 0;
814 bool const maintext = text.isMainText();
815 // we are at the beginning of an inset and CJK is already open;
816 // we count inheritation levels to get the inset nesting right.
817 OutputState * state = getOutputState();
818 if (pit == 0 && !maintext
819 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
820 state->cjk_inherited_ += 1;
821 state->open_encoding_ = none;
824 // This paragraph is merged and we do not show changes in the output
825 bool const merged_par = !bparams.output_changes && par.parEndChange().deleted();
827 if (text.inset().isPassThru()) {
828 Font const outerfont = text.outerFont(pit);
830 // No newline before first paragraph in this lyxtext
831 if (pit > 0 && !text.inset().getLayout().parbreakIgnored() && !merged_par) {
833 if (!text.inset().getLayout().parbreakIsNewline())
837 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
841 Paragraph const * nextpar = runparams.isLastPar
842 ? nullptr : ¶graphs.at(pit + 1);
844 bool const intitle_command = style.intitle && style.isCommand();
845 // Intitle commands switch languages locally, thus increase
846 // language nesting level
848 state->nest_level_ += 1;
850 if (style.pass_thru) {
851 Font const outerfont = text.outerFont(pit);
852 parStartCommand(par, os, runparams, style);
853 if (style.isCommand() && style.needprotect)
854 // Due to the moving argument, some fragile
855 // commands (labels, index entries)
856 // are output after this command (#2154)
857 runparams.postpone_fragile_stuff =
858 bparams.postpone_fragile_content;
862 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
864 // I did not create a parEndCommand for this minuscule
865 // task because in the other user of parStartCommand
866 // the code is different (JMarc)
867 if (style.isCommand()) {
869 if (par.needsCProtection(runparams.moving_arg)
870 && contains(runparams.active_chars, '^'))
877 else if (!merged_par)
879 if (!style.parbreak_is_newline && !merged_par) {
881 } else if (nextpar && !style.isEnvironment()) {
882 Layout const nextstyle = text.inset().forcePlainLayout()
883 ? bparams.documentClass().plainLayout()
885 if (nextstyle.name() != style.name() && !merged_par)
892 // This paragraph's language
893 Language const * const par_language = par.getParLanguage(bparams);
894 Language const * const nextpar_language = nextpar ?
895 nextpar->getParLanguage(bparams) : nullptr;
896 // The document's language
897 Language const * const doc_language = bparams.language;
898 // The language that was in effect when the environment this paragraph is
899 // inside of was opened
900 Language const * const outer_language =
901 (runparams.local_font != nullptr) ?
902 runparams.local_font->language() : doc_language;
904 Paragraph const * priorpar = (pit == 0) ? nullptr : ¶graphs.at(pit - 1);
906 // The previous language that was in effect is the language of the
907 // previous paragraph, unless the previous paragraph is inside an
908 // environment with nesting depth greater than (or equal to, but with
909 // a different layout) the current one. If there is no previous
910 // paragraph, the previous language is the outer language.
911 // Note further that we take the outer language also if the prior par
912 // is PassThru, since in that case it has latex_language, and all secondary
913 // languages have been closed (#10793).
914 bool const use_prev_env_language = state->prev_env_language_ != nullptr
916 && priorpar->layout().isEnvironment()
917 && (priorpar->getDepth() > par.getDepth()
918 || (priorpar->getDepth() == par.getDepth()
919 && priorpar->layout() != par.layout()));
921 // We need to ignore previous intitle commands since languages
922 // are switched locally there (# 11514)
923 // There might be paragraphs before the title, so we check this.
924 Paragraph * prior_nontitle_par = nullptr;
925 if (!intitle_command) {
929 Paragraph const * tmppar = ¶graphs.at(ppit);
930 if (tmppar->layout().intitle && tmppar->layout().isCommand())
932 prior_nontitle_par = const_cast<Paragraph*>(tmppar);
936 bool const have_prior_nptpar =
937 prior_nontitle_par && !prior_nontitle_par->isPassThru();
938 Language const * const prev_language =
939 runparams_in.find_effective()
940 ? languages.getLanguage("ignore")
941 : (have_prior_nptpar)
942 ? (use_prev_env_language
943 ? state->prev_env_language_
944 : prior_nontitle_par->getParLanguage(bparams))
947 bool const use_polyglossia = runparams.use_polyglossia;
948 string const par_lang = use_polyglossia ?
949 getPolyglossiaEnvName(par_language): par_language->babel();
950 string const prev_lang = use_polyglossia ?
951 getPolyglossiaEnvName(prev_language) : prev_language->babel();
952 string const outer_lang = use_polyglossia ?
953 getPolyglossiaEnvName(outer_language) : outer_language->babel();
954 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
955 getPolyglossiaEnvName(nextpar_language) :
956 nextpar_language->babel()) : string();
957 string lang_begin_command = use_polyglossia ?
958 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
959 string lang_end_command = use_polyglossia ?
960 "\\end{$$lang}" : lyxrc.language_command_end;
961 // the '%' is necessary to prevent unwanted whitespace
962 string lang_command_termination = "%\n";
963 bool const using_begin_end = use_polyglossia ||
964 !lang_end_command.empty();
966 // For InTitle commands, we need to switch the language inside the command
967 // (see #10849); thus open the command here.
968 if (intitle_command) {
969 parStartCommand(par, os, runparams, style);
970 if (style.isCommand() && style.needprotect)
971 // Due to the moving argument, some fragile
972 // commands (labels, index entries)
973 // are output after this command (#2154)
974 runparams.postpone_fragile_stuff =
975 bparams.postpone_fragile_content;
979 // In some insets (such as Arguments), we cannot use \selectlanguage.
980 // Also, if an RTL language is set via environment in polyglossia,
981 // only a nested \\text<lang> command will reset the direction for LTR
982 // languages (see # 10111).
983 bool const in_polyglossia_rtl_env =
985 && runparams.local_font != nullptr
986 && outer_language->rightToLeft()
987 && !par_language->rightToLeft()
988 && !(have_prior_nptpar
989 && (prev_language->rightToLeft() != par_language->rightToLeft()));
990 bool const localswitch =
991 (runparams_in.find_effective()
992 || text.inset().forceLocalFontSwitch()
993 || (using_begin_end && text.inset().forcePlainLayout())
994 || in_polyglossia_rtl_env)
995 && !text.inset().forceParDirectionSwitch();
997 lang_begin_command = use_polyglossia ?
998 "\\text$$lang$$opts{" : lyxrc.language_command_local;
999 lang_end_command = "}";
1000 lang_command_termination.clear();
1003 bool const localswitch_needed = localswitch && par_lang != outer_lang;
1005 // localswitches need to be closed and reopened at each par
1006 if (runparams_in.find_effective() || ((par_lang != prev_lang || localswitch_needed)
1007 // check if we already put language command in TeXEnvironment()
1008 && !(style.isEnvironment()
1009 && (pit == 0 || (priorpar->layout() != par.layout()
1010 && priorpar->getDepth() <= par.getDepth())
1011 || priorpar->getDepth() < par.getDepth())))) {
1013 && (!using_begin_end || langOpenedAtThisLevel(state))
1014 && !lang_end_command.empty()
1015 && prev_lang != outer_lang
1016 && !prev_lang.empty()
1017 && (!using_begin_end || !style.isEnvironment())) {
1018 os << from_ascii(subst(lang_end_command,
1021 << lang_command_termination;
1022 if (using_begin_end)
1026 // We need to open a new language if we couldn't close the previous
1027 // one (because there's no language_command_end); and even if we closed
1028 // the previous one, if the current language is different than the
1029 // outer_language (which is currently in effect once the previous one
1031 if ((lang_end_command.empty() || par_lang != outer_lang
1032 || (!using_begin_end
1033 || (style.isEnvironment() && par_lang != prev_lang)))
1034 && !par_lang.empty()) {
1035 // If we're inside an inset, and that inset is within an \L or \R
1036 // (or equivalents), then within the inset, too, any opposite
1037 // language paragraph should appear within an \L or \R (in addition
1038 // to, outside of, the normal language switch commands).
1039 // This behavior is not correct for ArabTeX, though.
1040 if (!using_begin_end
1042 && par_language->lang() != "arabic_arabtex"
1043 && outer_language->lang() != "arabic_arabtex"
1044 // are we in an inset?
1045 && runparams.local_font != nullptr
1046 // is the inset within an \L or \R?
1048 // FIXME: currently, we don't check this; this means that
1049 // we'll have unnnecessary \L and \R commands, but that
1050 // doesn't seem to hurt (though latex will complain)
1052 // is this paragraph in the opposite direction?
1053 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
1054 // FIXME: I don't have a working copy of the Arabi package, so
1055 // I'm not sure if the farsi and arabic_arabi stuff is correct
1057 if (par_language->lang() == "farsi")
1059 else if (outer_language->lang() == "farsi")
1061 else if (par_language->lang() == "arabic_arabi")
1063 else if (outer_language->lang() == "arabic_arabi")
1065 // remaining RTL languages currently is hebrew
1066 else if (par_language->rightToLeft() && !runparams.isFullUnicode())
1071 // With CJK, the CJK tag has to be closed first (see below)
1072 if ((runparams.encoding->package() != Encoding::CJK
1073 || bparams.useNonTeXFonts
1074 || runparams.find_effective())
1075 && (par_lang != openLanguageName(state) || localswitch || intitle_command)
1076 && !par_lang.empty()) {
1077 string bc = use_polyglossia ?
1078 getPolyglossiaBegin(lang_begin_command, par_lang,
1079 par_language->polyglossiaOpts(),
1081 : subst(lang_begin_command, "$$lang", par_lang);
1083 os << lang_command_termination;
1084 if (using_begin_end)
1085 pushLanguageName(par_lang, localswitch);
1090 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
1091 // encoding, since this only affects the position of the outputted
1092 // \inputencoding command; the encoding switch will occur when necessary
1093 if (bparams.inputenc == "auto-legacy"
1094 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
1095 && runparams.encoding->package() != Encoding::japanese
1096 && runparams.encoding->package() != Encoding::none) {
1097 // Look ahead for future encoding changes.
1098 // We try to output them at the beginning of the paragraph,
1099 // since the \inputencoding command is not allowed e.g. in
1100 // sections. For this reason we only set runparams.moving_arg
1101 // after checking for the encoding change, otherwise the
1102 // change would be always avoided by switchEncoding().
1103 for (pos_type i = 0; i < par.size(); ++i) {
1104 char_type const c = par.getChar(i);
1105 Encoding const * const encoding =
1106 par.getFontSettings(bparams, i).language()->encoding();
1107 if (encoding->package() != Encoding::CJK
1108 && runparams.encoding->package() == Encoding::inputenc
1113 // All characters before c are in the ASCII range, and
1114 // c is non-ASCII (but no inset), so change the
1115 // encoding to that required by the language of c.
1116 // With CJK, only add switch if we have CJK content at the beginning
1118 if (i != 0 && encoding->package() == Encoding::CJK)
1121 pair<bool, int> enc_switch = switchEncoding(os.os(),
1122 bparams, runparams, *encoding);
1123 // the following is necessary after a CJK environment in a multilingual
1124 // context (nesting issue).
1125 if (par_language->encoding()->package() == Encoding::CJK
1126 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1127 os << "\\begin{CJK}{"
1128 << from_ascii(par_language->encoding()->latexName())
1129 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1130 state->open_encoding_ = CJK;
1132 if (encoding->package() != Encoding::none && enc_switch.first) {
1133 if (enc_switch.second > 0) {
1134 // the '%' is necessary to prevent unwanted whitespace
1137 // With CJK, the CJK tag had to be closed first (see above)
1138 if (runparams.encoding->package() == Encoding::CJK
1139 && par_lang != openLanguageName(state)
1140 && !par_lang.empty()) {
1141 os << subst(lang_begin_command, "$$lang", par_lang)
1142 << lang_command_termination;
1143 if (using_begin_end)
1144 pushLanguageName(par_lang, localswitch);
1146 runparams.encoding = encoding;
1152 runparams.moving_arg |= style.needprotect;
1153 if (style.needmboxprotect)
1154 ++runparams.inulemcmd;
1155 Encoding const * const prev_encoding = runparams.encoding;
1157 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1158 if (par.allowParagraphCustomization()) {
1159 if (par.params().startOfAppendix()) {
1160 os << "\n\\appendix\n";
1163 // InTitle commands must use switches (not environments)
1164 // inside the commands (see #9332)
1165 if (style.intitle) {
1166 if (!par.params().spacing().isDefault())
1168 if (runparams.moving_arg)
1170 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1173 if (!par.params().spacing().isDefault()
1174 && (pit == 0 || !priorpar->hasSameLayout(par)))
1176 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1180 if (style.isCommand()) {
1186 // For InTitle commands, we already started the command before
1187 // the language switch
1188 if (!intitle_command) {
1189 parStartCommand(par, os, runparams, style);
1190 if (style.isCommand() && style.needprotect)
1191 // Due to the moving argument, some fragile
1192 // commands (labels, index entries)
1193 // are output after this command (#2154)
1194 runparams.postpone_fragile_stuff =
1195 bparams.postpone_fragile_content;
1198 Font const outerfont = text.outerFont(pit);
1201 os << from_utf8(everypar);
1202 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1204 Font const font = par.empty()
1205 ? par.getLayoutFont(bparams, outerfont)
1206 : par.getFont(bparams, par.size() - 1, outerfont);
1208 bool const is_command = style.isCommand();
1210 // InTitle commands need to be closed after the language has been closed.
1211 if (!intitle_command) {
1214 if (!style.postcommandargs().empty())
1215 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1216 if (!runparams.post_macro.empty()) {
1217 // Output the stored fragile commands (labels, indices etc.)
1218 // that need to be output after the command with moving argument.
1219 os << runparams.post_macro;
1220 runparams.post_macro.clear();
1222 if (par.needsCProtection(runparams.moving_arg)
1223 && contains(runparams.active_chars, '^'))
1225 if (runparams.encoding != prev_encoding) {
1226 runparams.encoding = prev_encoding;
1227 os << setEncoding(prev_encoding->iconvName());
1232 bool pending_newline = false;
1233 bool unskip_newline = false;
1234 bool close_lang_switch = false;
1235 switch (style.latextype) {
1236 case LATEX_ITEM_ENVIRONMENT:
1237 case LATEX_LIST_ENVIRONMENT:
1238 if ((nextpar && par_lang != nextpar_lang
1239 && nextpar->getDepth() == par.getDepth())
1240 || (atSameLastLangSwitchDepth(state) && nextpar
1241 && nextpar->getDepth() < par.getDepth()))
1242 close_lang_switch = using_begin_end;
1243 if (nextpar && par.params().depth() < nextpar->params().depth())
1244 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1246 case LATEX_ENVIRONMENT: {
1247 // if it's the last paragraph of the current environment
1248 // skip it otherwise fall through
1250 && ((nextpar->layout() != par.layout()
1251 || nextpar->params().depth() != par.params().depth())
1252 || (!using_begin_end || par_lang != nextpar_lang)))
1254 close_lang_switch = using_begin_end;
1261 // we don't need it for the last paragraph and in InTitle commands!!!
1262 if (nextpar && !intitle_command)
1263 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1266 // InTitle commands use switches (not environments) for space settings
1267 if (par.allowParagraphCustomization() && !style.intitle) {
1268 if (!par.params().spacing().isDefault()
1269 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1270 if (pending_newline)
1273 string const endtag =
1274 par.params().spacing().writeEnvirEnd(useSetSpace);
1275 if (prefixIs(endtag, "\\end{"))
1278 os << from_ascii(endtag);
1279 pending_newline = true;
1283 // Closing the language is needed for the last paragraph in a given language
1284 // as well as for any InTitleCommand (since these set the language locally);
1285 // it is also needed if we're within an \L or \R that we may have opened above
1286 // (not necessarily in this paragraph) and are about to close.
1287 bool closing_rtl_ltr_environment = !using_begin_end
1289 && (par_language->lang() != "arabic_arabtex"
1290 && outer_language->lang() != "arabic_arabtex")
1291 // have we opened an \L or \R environment?
1292 && runparams.local_font != nullptr
1293 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1294 // are we about to close the language?
1295 &&((nextpar && par_lang != nextpar_lang)
1296 || (runparams.isLastPar && par_lang != outer_lang));
1298 if (localswitch_needed
1299 || (intitle_command && using_begin_end)
1300 || closing_rtl_ltr_environment
1301 || (((runparams.isLastPar
1303 // Since \selectlanguage write the language to the aux file,
1304 // we need to reset the language at the end of footnote or
1306 || runparams.inFloat != OutputParams::NONFLOAT || runparams.inFootnote
1307 // Same for maintext in children (see below)
1309 || close_lang_switch)
1310 && (par_lang != outer_lang || (using_begin_end
1311 && style.isEnvironment()
1312 && par_lang != nextpar_lang)))) {
1314 if (!localswitch && (pending_newline || close_lang_switch))
1317 // when the paragraph uses CJK, the language has to be closed earlier
1318 if ((font.language()->encoding()->package() != Encoding::CJK)
1319 || bparams.useNonTeXFonts
1320 || runparams_in.find_effective()) {
1321 if (lang_end_command.empty()) {
1322 // If this is a child, we should restore the
1323 // master language after the last paragraph.
1324 Language const * const current_language =
1325 (runparams.isLastPar && runparams.master_language)
1326 ? runparams.master_language
1328 string const current_lang = use_polyglossia
1329 ? getPolyglossiaEnvName(current_language)
1330 : current_language->babel();
1331 if (!current_lang.empty()
1332 && current_lang != openLanguageName(state)) {
1333 string bc = use_polyglossia ?
1334 getPolyglossiaBegin(lang_begin_command, current_lang,
1335 current_language->polyglossiaOpts(),
1337 : subst(lang_begin_command, "$$lang", current_lang);
1339 pending_newline = !localswitch
1340 && !text.inset().getLayout().parbreakIgnored();
1341 unskip_newline = !localswitch;
1342 if (using_begin_end)
1343 pushLanguageName(current_lang, localswitch);
1345 } else if ((!using_begin_end ||
1346 langOpenedAtThisLevel(state)) &&
1347 !par_lang.empty()) {
1348 // If we are in an environment, we have to
1349 // close the "outer" language afterwards
1350 string const & cur_lang = openLanguageName(state);
1351 if (!style.isEnvironment()
1352 || (close_lang_switch
1353 && atSameLastLangSwitchDepth(state)
1354 && par_lang != outer_lang
1355 && (par_lang != cur_lang
1356 || (cur_lang != outer_lang
1358 && style != nextpar->layout())))
1359 || (atSameLastLangSwitchDepth(state)
1360 && !state->lang_switch_depth_.empty()
1361 && cur_lang != par_lang)
1362 || in_polyglossia_rtl_env)
1364 if (using_begin_end && !localswitch)
1366 os << from_ascii(subst(
1370 pending_newline = !localswitch
1371 && !text.inset().getLayout().parbreakIgnored();
1372 unskip_newline = !localswitch;
1373 if (using_begin_end)
1379 if (closing_rtl_ltr_environment)
1382 // InTitle commands need to be closed after the language has been closed.
1383 if (intitle_command) {
1385 if (!style.postcommandargs().empty())
1386 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1387 if (!runparams.post_macro.empty()) {
1388 // Output the stored fragile commands (labels, indices etc.)
1389 // that need to be output after the command with moving argument.
1390 os << runparams.post_macro;
1391 runparams.post_macro.clear();
1393 if (par.needsCProtection(runparams.moving_arg)
1394 && contains(runparams.active_chars, '^'))
1396 if (runparams.encoding != prev_encoding) {
1397 runparams.encoding = prev_encoding;
1398 os << setEncoding(prev_encoding->iconvName());
1402 bool const last_was_separator =
1403 !par.empty() && par.isEnvSeparator(par.size() - 1);
1405 // Signify added/deleted par break in output if show changes in output
1406 if (nextpar && !os.afterParbreak() && !last_was_separator
1407 && bparams.output_changes && par.parEndChange().changed()) {
1408 Changes::latexMarkChange(os, bparams, Change(Change::UNCHANGED),
1409 par.parEndChange(), runparams);
1410 os << bparams.encoding().latexString(docstring(1, 0x00b6)).first << "}";
1413 if (pending_newline) {
1415 // prevent unwanted whitespace
1417 if (!os.afterParbreak() && !last_was_separator)
1421 // if this is a CJK-paragraph and the next isn't, close CJK
1422 // also if the next paragraph is a multilingual environment (because of nesting)
1423 if (nextpar && state->open_encoding_ == CJK
1424 && bparams.encoding().iconvName() != "UTF-8"
1425 && bparams.encoding().package() != Encoding::CJK
1426 && ((nextpar_language &&
1427 nextpar_language->encoding()->package() != Encoding::CJK)
1428 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1429 // inbetween environments, CJK has to be closed later (nesting!)
1430 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1431 os << "\\end{CJK}\n";
1432 state->open_encoding_ = none;
1435 // If this is the last paragraph, close the CJK environment
1436 // if necessary. If it's an environment or nested in an environment,
1437 // we'll have to \end that first.
1438 if (runparams.isLastPar && !style.isEnvironment()
1439 && par.params().depth() < 1) {
1440 switch (state->open_encoding_) {
1442 // do nothing at the end of child documents
1443 if (maintext && buf.masterBuffer() != &buf)
1445 // end of main text: also insert a \clearpage (see #5386)
1447 os << "\n\\clearpage\n\\end{CJK}\n";
1451 state->open_encoding_ = none;
1455 // FIXME: If we are in an inset and the switch happened outside this inset,
1456 // do not switch back at the end of the inset (bug #8479)
1457 // The following attempt does not help with listings-caption in a CJK document:
1458 // if (runparams_in.local_font != 0
1459 // && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1462 state->open_encoding_ = none;
1472 // Information about local language is stored as a font feature.
1473 // If this is the last paragraph of the inset and a local_font was set upon entering
1474 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1475 // ensure the encoding is set back to the default encoding of the local language.
1476 if (runparams.isLastPar && runparams_in.local_font != nullptr
1477 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1478 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1479 && !runparams.isFullUnicode()
1481 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1482 os << setEncoding(runparams_in.encoding->iconvName());
1484 // Otherwise, the current encoding should be set for the next paragraph.
1486 runparams_in.encoding = runparams.encoding;
1488 // Also pass the post_macros upstream
1489 runparams_in.post_macro = runparams.post_macro;
1490 // These need to be passed upstream as well
1491 runparams_in.need_maketitle = runparams.need_maketitle;
1492 runparams_in.have_maketitle = runparams.have_maketitle;
1495 // we don't need a newline for the last paragraph!!!
1496 // Note from JMarc: we will re-add a \n explicitly in
1497 // TeXEnvironment, because it is needed in this case
1498 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1499 if (!text.inset().getLayout().parbreakIgnored() && !merged_par)
1500 // Make sure to start a new line
1502 // A newline '\n' is always output before a command,
1503 // so avoid doubling it.
1504 Layout const & next_layout = nextpar->layout();
1505 if (!next_layout.isCommand()) {
1506 // Here we now try to avoid spurious empty lines by
1507 // outputting a paragraph break only if:
1508 // (case 1) the paragraph style allows parbreaks and
1509 // no \begin, \end or \item tags are going to follow
1510 // (i.e., if the next isn't the first or the current
1511 // isn't the last paragraph of an environment or itemize)
1512 // and the depth and alignment of the following paragraph is
1514 // (case 2) the following is a non-environment paragraph
1515 // whose depth is increased but whose alignment is unchanged, or
1516 // (case 3) the paragraph is not an environment and the next one
1517 // is a non-itemize-like env at lower depth, or
1518 // (case 4) the paragraph is a command not followed by an
1519 // environment and the alignment of the current and next
1520 // paragraph is unchanged, or
1521 // (case 5) the current alignment is changed and a
1522 // standard paragraph follows.
1523 DocumentClass const & tclass = bparams.documentClass();
1524 if ((style == next_layout
1525 && !style.parbreak_is_newline
1526 && !text.inset().getLayout().parbreakIsNewline()
1527 && !text.inset().getLayout().parbreakIgnored()
1528 && style.latextype != LATEX_ITEM_ENVIRONMENT
1529 && style.latextype != LATEX_LIST_ENVIRONMENT
1530 && style.align == par.getAlign(bparams)
1531 && nextpar->getDepth() == par.getDepth()
1532 && (nextpar->getAlign(bparams) == par.getAlign(bparams)
1533 || par.params().spacing() != nextpar->params().spacing()))
1534 || (!next_layout.isEnvironment()
1535 && nextpar->getDepth() > par.getDepth()
1536 && nextpar->getAlign(bparams) == next_layout.align)
1537 || (!style.isEnvironment()
1538 && next_layout.latextype == LATEX_ENVIRONMENT
1539 && nextpar->getDepth() < par.getDepth())
1540 || (style.isCommand()
1541 && !next_layout.isEnvironment()
1542 && style.align == par.getAlign(bparams)
1543 && next_layout.align == nextpar->getAlign(bparams))
1544 || (style.align != par.getAlign(bparams)
1545 && tclass.isDefaultLayout(next_layout))) {
1546 // and omit paragraph break if it has been deleted with ct
1547 // and changes are not shown in output
1549 if (runparams.isNonLong)
1550 // This is to allow parbreak in multirow
1551 // It could also be used for other non-long
1553 os << "\\endgraf\n";
1561 // Reset language nesting level after intitle command
1562 if (intitle_command)
1563 state->nest_level_ -= 1;
1565 LYXERR(Debug::OUTFILE, "TeXOnePar for paragraph " << pit << " done; ptr "
1566 << &par << " next " << nextpar);
1572 // LaTeX all paragraphs
1573 void latexParagraphs(Buffer const & buf,
1576 OutputParams const & runparams,
1577 string const & everypar)
1579 LASSERT(runparams.par_begin <= runparams.par_end,
1580 { os << "% LaTeX Output Error\n"; return; } );
1582 BufferParams const & bparams = buf.params();
1583 BufferParams const & mparams = buf.masterParams();
1585 bool const maintext = text.isMainText();
1586 bool const is_child = buf.masterBuffer() != &buf;
1587 bool const multibib_child = maintext && is_child
1588 && mparams.multibib == "child";
1590 if (multibib_child && mparams.useBiblatex())
1591 os << "\\newrefsection";
1592 else if (multibib_child && mparams.useBibtopic()
1593 && !buf.masterBibInfo().empty()) {
1594 os << "\\begin{btUnit}\n";
1595 runparams.openbtUnit = true;
1598 // Open a CJK environment at the beginning of the main buffer
1599 // if the document's main encoding requires the CJK package
1600 // or the document encoding is utf8 and the CJK package is required
1601 // (but not in child documents or documents using system fonts):
1602 OutputState * state = getOutputState();
1603 if (maintext && !is_child && !bparams.useNonTeXFonts
1604 && (bparams.encoding().package() == Encoding::CJK
1605 || (bparams.encoding().name() == "utf8"
1606 && runparams.use_CJK))
1608 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1609 ? from_ascii("UTF8")
1610 : from_ascii(bparams.encoding().latexName());
1611 os << "\\begin{CJK}{" << cjkenc
1612 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1613 state->open_encoding_ = CJK;
1615 // if "auto begin" is switched off, explicitly switch the
1616 // language on at start
1617 string const mainlang = runparams.use_polyglossia
1618 ? getPolyglossiaEnvName(bparams.language)
1619 : bparams.language->babel();
1620 string const lang_begin_command = runparams.use_polyglossia ?
1621 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1622 string const lang_end_command = runparams.use_polyglossia ?
1623 "\\end{$$lang}" : lyxrc.language_command_end;
1624 bool const using_begin_end = runparams.use_polyglossia ||
1625 !lang_end_command.empty();
1627 if (maintext && !lyxrc.language_auto_begin &&
1628 !mainlang.empty()) {
1630 string bc = runparams.use_polyglossia ?
1631 getPolyglossiaBegin(lang_begin_command, mainlang,
1632 bparams.language->polyglossiaOpts())
1633 : subst(lang_begin_command, "$$lang", mainlang);
1636 if (using_begin_end)
1637 pushLanguageName(mainlang);
1640 ParagraphList const & paragraphs = text.paragraphs();
1642 if (runparams.par_begin == runparams.par_end) {
1643 // The full doc will be exported but it is easier to just rely on
1644 // runparams range parameters that will be passed TeXEnvironment.
1645 runparams.par_begin = 0;
1646 runparams.par_end = static_cast<int>(paragraphs.size());
1649 pit_type pit = runparams.par_begin;
1650 // lastpit is for the language check after the loop.
1651 pit_type lastpit = pit;
1652 DocumentClass const & tclass = bparams.documentClass();
1654 // Did we already warn about inTitle layout mixing? (we only warn once)
1655 bool gave_layout_warning = false;
1656 for (; pit < runparams.par_end; ++pit) {
1658 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
1660 // FIXME This check should not be needed. We should
1661 // perhaps issue an error if it is.
1662 Layout const & layout = text.inset().forcePlainLayout() ?
1663 tclass.plainLayout() : par->layout();
1665 if (layout.intitle) {
1666 if (runparams.have_maketitle) {
1667 if (!gave_layout_warning && !runparams.dryrun) {
1668 gave_layout_warning = true;
1669 frontend::Alert::warning(_("Error in latexParagraphs"),
1670 bformat(_("You are using at least one "
1671 "layout (%1$s) intended for the title, "
1672 "after using non-title layouts. This "
1673 "could lead to missing or incorrect output."
1676 } else if (!runparams.need_maketitle) {
1677 runparams.need_maketitle = true;
1678 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1680 << from_ascii(tclass.titlename())
1684 } else if (runparams.need_maketitle && !runparams.have_maketitle
1685 && !layout.inpreamble && !text.inset().isInTitle()) {
1686 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1687 os << "\\end{" << from_ascii(tclass.titlename())
1691 os << "\\" << from_ascii(tclass.titlename())
1694 runparams.have_maketitle = true;
1695 runparams.need_maketitle = false;
1698 if (layout.isCommand() && !layout.latexname().empty()
1699 && layout.latexname() == bparams.multibib) {
1700 if (runparams.openbtUnit)
1701 os << "\\end{btUnit}\n";
1702 if (!bparams.useBiblatex()
1703 && !buf.masterBibInfo().empty()) {
1704 os << '\n' << "\\begin{btUnit}\n";
1705 runparams.openbtUnit = true;
1709 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1710 // This is a standard top level paragraph, TeX it and continue.
1711 TeXOnePar(buf, text, pit, os, runparams, everypar);
1715 // Do not output empty environments if the whole paragraph has
1716 // been deleted with ct and changes are not output.
1717 bool output_changes;
1718 if (!runparams.find_effective())
1719 output_changes = bparams.output_changes;
1721 output_changes = runparams.find_with_deleted();
1722 bool const lastpar = size_t(pit + 1) >= paragraphs.size();
1724 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
1725 Paragraph const & cpar = paragraphs.at(pit);
1726 if ((par->layout() != nextpar->layout()
1727 || par->params().depth() == nextpar->params().depth()
1728 || par->params().leftIndent() == nextpar->params().leftIndent())
1730 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
1731 if (!cpar.parEndChange().deleted())
1736 // This is the last par
1737 Paragraph const & cpar = paragraphs.at(pit);
1739 && cpar.isDeleted(0, cpar.size()) && !output_changes) {
1740 if (!cpar.parEndChange().deleted())
1746 TeXEnvironmentData const data =
1747 prepareEnvironment(buf, text, par, os, runparams);
1748 // pit can be changed in TeXEnvironment.
1749 TeXEnvironment(buf, text, runparams, pit, os);
1750 finishEnvironment(os, runparams, data, maintext, lastpar);
1753 // FIXME: uncomment the content or remove this block
1754 if (pit == runparams.par_end) {
1755 // Make sure that the last paragraph is
1756 // correctly terminated (because TeXOnePar does
1757 // not add a \n in this case)
1761 // It might be that we only have a title in this document.
1762 // But if we're in an inset, this is not the end of
1763 // the document. (There may be some other checks of this
1764 // kind that are needed.)
1765 if (runparams.need_maketitle && !runparams.have_maketitle && maintext) {
1766 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1767 os << "\\end{" << from_ascii(tclass.titlename())
1770 os << "\\" << from_ascii(tclass.titlename())
1775 if (maintext && !is_child && runparams.openbtUnit)
1776 os << "\\end{btUnit}\n";
1778 // if "auto end" is switched off, explicitly close the language at the end
1779 // but only if the last par is in a babel or polyglossia language
1780 Language const * const lastpar_language =
1781 paragraphs.at(lastpit).getParLanguage(bparams);
1782 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1783 lastpar_language->encoding()->package() != Encoding::CJK) {
1784 os << from_utf8(subst(lang_end_command,
1788 // If we have language_auto_begin, the stack will
1789 // already be empty, nothing to pop()
1790 if (using_begin_end && langOpenedAtThisLevel(state))
1794 // If the last paragraph is an environment, we'll have to close
1795 // CJK at the very end to do proper nesting.
1796 if (maintext && !is_child && state->open_encoding_ == CJK) {
1797 os << "\\clearpage\n\\end{CJK}\n";
1798 state->open_encoding_ = none;
1800 // Likewise for polyglossia or when using begin/end commands
1801 // or at the very end of an active branch inset with a language switch
1802 Language const * const outer_language = (runparams.local_font != nullptr)
1803 ? runparams.local_font->language() : bparams.language;
1804 string const & prev_lang = runparams.use_polyglossia
1805 ? getPolyglossiaEnvName(outer_language)
1806 : outer_language->babel();
1807 string const lastpar_lang = runparams.use_polyglossia ?
1808 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1809 string const & cur_lang = openLanguageName(state);
1810 if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1811 || (maintext && !is_child)) && !cur_lang.empty()) {
1812 os << from_utf8(subst(lang_end_command,
1816 if (using_begin_end)
1818 } else if (runparams.inbranch && !using_begin_end
1819 && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1820 // with !using_begin_end, cur_lang is empty, so we need to
1821 // compare against the paragraph language (and we are in the
1822 // last paragraph at this point)
1823 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1826 // reset inherited encoding
1827 if (state->cjk_inherited_ > 0) {
1828 state->cjk_inherited_ -= 1;
1829 if (state->cjk_inherited_ == 0)
1830 state->open_encoding_ = CJK;
1833 if (multibib_child && mparams.useBibtopic()) {
1834 os << "\\end{btUnit}\n";
1835 runparams.openbtUnit = false;
1839 // Switch the input encoding for some part(s) of the document.
1840 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1841 OutputParams const & runparams, Encoding const & newEnc,
1842 bool force, bool noswitchmacro)
1844 // Never switch encoding with XeTeX/LuaTeX
1845 // or if we're in a moving argument or inherit the outer encoding.
1846 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1847 return make_pair(false, 0);
1849 // Only switch for auto-selected legacy encodings (inputenc setting
1850 // "auto-legacy" or "auto-legacy-plain").
1851 // The "listings" environment can force a switch also with other
1852 // encoding settings (it does not support variable width encodings
1853 // (utf8, jis, ...) under 8-bit latex engines).
1854 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1855 || runparams.moving_arg))
1856 return make_pair(false, 0);
1858 Encoding const & oldEnc = *runparams.encoding;
1859 // Do not switch, if the encoding is unchanged or switching is not supported.
1860 if (oldEnc.name() == newEnc.name()
1861 || oldEnc.package() == Encoding::japanese
1862 || oldEnc.package() == Encoding::none
1863 || newEnc.package() == Encoding::none
1864 || runparams.find_effective())
1865 return make_pair(false, 0);
1866 // FIXME We ignore encoding switches from/to encodings that do
1867 // neither support the inputenc package nor the CJK package here.
1868 // This may fail for characters not supported by "unicodesymbols"
1869 // or for non-ASCII characters in "listings"
1870 // but it is the best we can do.
1873 LYXERR(Debug::OUTFILE, "Changing LaTeX encoding from "
1874 << oldEnc.name() << " to " << newEnc.name());
1875 os << setEncoding(newEnc.iconvName());
1876 if (bparams.inputenc == "auto-legacy-plain")
1877 return make_pair(true, 0);
1879 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1880 OutputState * state = getOutputState();
1881 switch (newEnc.package()) {
1882 case Encoding::none:
1883 case Encoding::japanese:
1884 // shouldn't ever reach here (see above) but avoids warning.
1885 return make_pair(true, 0);
1886 case Encoding::inputenc: {
1887 size_t count = inputenc_arg.length();
1888 if (oldEnc.package() == Encoding::CJK &&
1889 state->open_encoding_ == CJK) {
1891 state->open_encoding_ = none;
1894 else if (oldEnc.package() == Encoding::inputenc &&
1895 state->open_encoding_ == inputenc) {
1897 state->open_encoding_ = none;
1900 if (runparams.local_font != nullptr
1901 && oldEnc.package() == Encoding::CJK) {
1902 // within insets, \inputenc switches need
1903 // to be embraced within \bgroup...\egroup;
1907 state->open_encoding_ = inputenc;
1910 return make_pair(true, count);
1911 os << "\\inputencoding{" << inputenc_arg << '}';
1912 return make_pair(true, count + 16);
1914 case Encoding::CJK: {
1915 size_t count = inputenc_arg.length();
1916 if (oldEnc.package() == Encoding::CJK &&
1917 state->open_encoding_ == CJK) {
1921 if (oldEnc.package() == Encoding::inputenc &&
1922 state->open_encoding_ == inputenc) {
1926 os << "\\begin{CJK}{"
1927 << from_ascii(newEnc.latexName()) << "}{"
1928 << from_ascii(bparams.fonts_cjk) << "}";
1929 state->open_encoding_ = CJK;
1930 return make_pair(true, count + 15);
1933 // Dead code to avoid a warning:
1934 return make_pair(true, 0);