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"
16 #include "BufferParams.h"
19 #include "InsetList.h"
21 #include "LaTeXFeatures.h"
24 #include "OutputParams.h"
25 #include "Paragraph.h"
26 #include "ParagraphParameters.h"
27 #include "texstream.h"
28 #include "TextClass.h"
30 #include "insets/InsetBibitem.h"
31 #include "insets/InsetArgument.h"
33 #include "frontends/alert.h"
35 #include "support/lassert.h"
36 #include "support/convert.h"
37 #include "support/debug.h"
38 #include "support/lstrings.h"
39 #include "support/lyxalgo.h"
40 #include "support/textutils.h"
41 #include "support/gettext.h"
43 #include <QThreadStorage>
49 using namespace lyx::support;
65 OutputState() : open_encoding_(none), cjk_inherited_(0),
66 prev_env_language_(0), nest_level_(0)
69 OpenEncoding open_encoding_;
71 Language const * prev_env_language_;
73 stack<int> lang_switch_depth_; // Both are always empty when
74 stack<string> open_polyglossia_lang_; // not using polyglossia
78 OutputState * getOutputState()
80 // FIXME An instance of OutputState should be kept around for each export
81 // instead of using local thread storage
82 static QThreadStorage<OutputState *> outputstate;
83 if (!outputstate.hasLocalData())
84 outputstate.setLocalData(new OutputState);
85 return outputstate.localData();
89 string const & openLanguageName(OutputState const * state)
91 // Return a reference to the last active language opened with
92 // polyglossia or when using begin/end commands. If none or when
93 // using babel with only a begin command, return a reference to
96 static string const empty;
98 return state->open_polyglossia_lang_.empty()
100 : state->open_polyglossia_lang_.top();
104 bool atSameLastLangSwitchDepth(OutputState const * state)
106 // Return true if the actual nest level is the same at which the
107 // language was switched when using polyglossia or begin/end
108 // commands. Instead, return always true when using babel with
109 // only a begin command.
111 return state->lang_switch_depth_.size() == 0
113 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
117 bool isLocalSwitch(OutputState const * state)
119 // Return true if the language was opened by a local command switch.
121 return state->lang_switch_depth_.size()
122 && state->lang_switch_depth_.top() < 0;
126 bool langOpenedAtThisLevel(OutputState const * state)
128 // Return true if the language was opened at the current nesting level.
130 return state->lang_switch_depth_.size()
131 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
135 string const getPolyglossiaEnvName(Language const * lang)
137 string result = lang->polyglossia();
138 if (result == "arabic")
139 // exceptional spelling; see polyglossia docs.
145 string const getPolyglossiaBegin(string const & lang_begin_command,
146 string const & lang, string const & opts,
147 bool const localswitch = false)
151 // we need to revert the upcasing done in getPolyglossiaEnvName()
152 // in case we have a local polyglossia command (\textarabic).
153 string language = localswitch ? ascii_lowercase(lang) : lang;
154 result = subst(lang_begin_command, "$$lang", language);
156 string options = opts.empty() ?
157 string() : "[" + opts + "]";
158 result = subst(result, "$$opts", options);
164 struct TeXEnvironmentData
167 Layout const * style;
168 Language const * par_language;
169 Encoding const * prev_encoding;
170 bool leftindent_open;
174 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
176 ParagraphList::const_iterator pit,
178 OutputParams const & runparams)
180 TeXEnvironmentData data;
182 BufferParams const & bparams = buf.params();
184 // FIXME This test should not be necessary.
185 // We should perhaps issue an error if it is.
186 Layout const & style = text.inset().forcePlainLayout() ?
187 bparams.documentClass().plainLayout() : pit->layout();
189 ParagraphList const & paragraphs = text.paragraphs();
190 ParagraphList::const_iterator const priorpit =
191 pit == paragraphs.begin() ? pit : prev(pit, 1);
193 OutputState * state = getOutputState();
194 bool const use_prev_env_language = state->prev_env_language_ != 0
195 && priorpit->layout().isEnvironment()
196 && (priorpit->getDepth() > pit->getDepth()
197 || (priorpit->getDepth() == pit->getDepth()
198 && priorpit->layout() != pit->layout()));
200 data.prev_encoding = runparams.encoding;
201 data.par_language = pit->getParLanguage(bparams);
202 Language const * const doc_language = bparams.language;
203 Language const * const prev_par_language =
204 (pit != paragraphs.begin())
205 ? (use_prev_env_language ? state->prev_env_language_
206 : priorpit->getParLanguage(bparams))
209 bool const use_polyglossia = runparams.use_polyglossia;
210 string const par_lang = use_polyglossia ?
211 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
212 string const prev_par_lang = use_polyglossia ?
213 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
214 string const doc_lang = use_polyglossia ?
215 getPolyglossiaEnvName(doc_language) : doc_language->babel();
216 string const lang_begin_command = use_polyglossia ?
217 "\\begin{$$lang}" : lyxrc.language_command_begin;
218 string const lang_end_command = use_polyglossia ?
219 "\\end{$$lang}" : lyxrc.language_command_end;
220 bool const using_begin_end = use_polyglossia ||
221 !lang_end_command.empty();
223 // For polyglossia, switch language outside of environment, if possible.
224 if (par_lang != prev_par_lang) {
225 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
226 !lang_end_command.empty() &&
227 prev_par_lang != doc_lang &&
228 !prev_par_lang.empty()) {
229 os << from_ascii(subst(
233 // the '%' is necessary to prevent unwanted whitespace
239 // If no language was explicitly opened and we are using
240 // polyglossia or begin/end commands, then the current
241 // language is the document language.
242 string const & cur_lang = using_begin_end
243 && state->lang_switch_depth_.size()
244 ? openLanguageName(state)
247 if ((lang_end_command.empty() ||
248 par_lang != doc_lang ||
249 par_lang != cur_lang) &&
251 string bc = use_polyglossia ?
252 getPolyglossiaBegin(lang_begin_command, par_lang,
253 data.par_language->polyglossiaOpts())
254 : subst(lang_begin_command, "$$lang", par_lang);
256 // the '%' is necessary to prevent unwanted whitespace
259 pushLanguageName(par_lang);
263 data.leftindent_open = false;
264 if (!pit->params().leftIndent().zero()) {
265 os << "\\begin{LyXParagraphLeftIndent}{"
266 << from_ascii(pit->params().leftIndent().asLatexString())
268 data.leftindent_open = true;
271 if (style.isEnvironment())
272 state->nest_level_ += 1;
274 if (style.isEnvironment() && !style.latexname().empty()) {
275 os << "\\begin{" << from_ascii(style.latexname()) << '}';
276 if (!style.latexargs().empty()) {
277 OutputParams rp = runparams;
278 rp.local_font = &pit->getFirstFontSettings(bparams);
279 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
281 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
283 << pit->params().labelWidthString()
285 } else if (style.labeltype == LABEL_BIBLIO) {
286 if (pit->params().labelWidthString().empty())
287 os << '{' << bibitemWidest(buf, runparams) << "}\n";
290 << pit->params().labelWidthString()
293 os << from_ascii(style.latexparam()) << '\n';
294 if (style.latextype == LATEX_BIB_ENVIRONMENT
295 || style.latextype == LATEX_ITEM_ENVIRONMENT
296 || style.latextype == LATEX_LIST_ENVIRONMENT) {
297 OutputParams rp = runparams;
298 rp.local_font = &pit->getFirstFontSettings(bparams);
299 latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
305 // in multilingual environments, the CJK tags have to be nested properly
306 data.cjk_nested = false;
307 if (data.par_language->encoding()->package() == Encoding::CJK &&
308 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
309 if (prev_par_language->encoding()->package() == Encoding::CJK) {
310 os << "\\begin{CJK}{"
311 << from_ascii(data.par_language->encoding()->latexName())
312 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
314 state->open_encoding_ = CJK;
315 data.cjk_nested = true;
321 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
322 TeXEnvironmentData const & data)
324 OutputState * state = getOutputState();
325 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
326 if (state->open_encoding_ == CJK && data.cjk_nested) {
327 // We need to close the encoding even if it does not change
328 // to do correct environment nesting
329 os << "\\end{CJK}\n";
330 state->open_encoding_ = none;
333 if (data.style->isEnvironment()) {
335 bool const using_begin_end =
336 runparams.use_polyglossia ||
337 !lyxrc.language_command_end.empty();
338 // Close any language opened at this nest level
339 if (using_begin_end) {
340 while (langOpenedAtThisLevel(state)) {
341 if (isLocalSwitch(state)) {
345 << openLanguageName(state)
351 state->nest_level_ -= 1;
352 string const & name = data.style->latexname();
354 os << "\\end{" << from_ascii(name) << "}\n";
355 state->prev_env_language_ = data.par_language;
356 if (runparams.encoding != data.prev_encoding) {
357 runparams.encoding = data.prev_encoding;
358 os << setEncoding(data.prev_encoding->iconvName());
362 if (data.leftindent_open) {
363 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
364 state->prev_env_language_ = data.par_language;
365 if (runparams.encoding != data.prev_encoding) {
366 runparams.encoding = data.prev_encoding;
367 os << setEncoding(data.prev_encoding->iconvName());
371 // Check whether we should output a blank line after the environment
372 if (!data.style->nextnoindent)
377 void TeXEnvironment(Buffer const & buf, Text const & text,
378 OutputParams const & runparams,
379 pit_type & pit, otexstream & os)
381 ParagraphList const & paragraphs = text.paragraphs();
382 ParagraphList::const_iterator ipar = paragraphs.constIterator(pit);
383 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
385 Layout const & current_layout = ipar->layout();
386 depth_type const current_depth = ipar->params().depth();
387 Length const & current_left_indent = ipar->params().leftIndent();
389 // This is for debugging purpose at the end.
390 pit_type const par_begin = pit;
391 for (; pit < runparams.par_end; ++pit) {
392 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
394 // check first if this is an higher depth paragraph.
395 bool go_out = (par->params().depth() < current_depth);
396 if (par->params().depth() == current_depth) {
397 // This environment is finished.
398 go_out |= (par->layout() != current_layout);
399 go_out |= (par->params().leftIndent() != current_left_indent);
402 // nothing to do here, restore pit and go out.
407 if (par->layout() == current_layout
408 && par->params().depth() == current_depth
409 && par->params().leftIndent() == current_left_indent) {
410 // We are still in the same environment so TeXOnePar and continue;
411 TeXOnePar(buf, text, pit, os, runparams);
415 // We are now in a deeper environment.
416 // Either par->layout() != current_layout
417 // Or par->params().depth() > current_depth
418 // Or par->params().leftIndent() != current_left_indent)
420 // FIXME This test should not be necessary.
421 // We should perhaps issue an error if it is.
422 bool const force_plain_layout = text.inset().forcePlainLayout();
423 Layout const & style = force_plain_layout
424 ? buf.params().documentClass().plainLayout()
427 if (!style.isEnvironment()) {
428 // This is a standard paragraph, no need to call TeXEnvironment.
429 TeXOnePar(buf, text, pit, os, runparams);
433 // This is a new environment.
434 TeXEnvironmentData const data =
435 prepareEnvironment(buf, text, par, os, runparams);
436 // Recursive call to TeXEnvironment!
437 TeXEnvironment(buf, text, runparams, pit, os);
438 finishEnvironment(os, runparams, data);
441 if (pit != runparams.par_end)
442 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
446 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
447 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
449 unsigned int const argnr = latexargs.size();
453 // Default and preset args are always output, so if they require
454 // other arguments, consider this.
455 for (auto const & larg : latexargs) {
456 Layout::latexarg const & arg = larg.second;
457 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
458 vector<string> req = getVectorFromString(arg.requires);
459 required.insert(required.end(), req.begin(), req.end());
463 for (unsigned int i = 1; i <= argnr; ++i) {
464 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
465 bool inserted = false;
466 if (lit != ilist.end()) {
467 InsetArgument const * ins = (*lit).second;
469 Layout::LaTeXArgMap::const_iterator const lait =
470 latexargs.find(ins->name());
471 if (lait != latexargs.end()) {
472 Layout::latexarg arg = (*lait).second;
476 ldelim = arg.mandatory ?
477 from_ascii("{") : from_ascii("[");
478 rdelim = arg.mandatory ?
479 from_ascii("}") : from_ascii("]");
481 if (!arg.ldelim.empty())
483 if (!arg.rdelim.empty())
485 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
486 if (prefix == "listpreamble:")
493 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
494 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
495 for (; lait != laend; ++lait) {
496 string const name = prefix + convert<string>(i);
497 if ((*lait).first == name) {
498 Layout::latexarg arg = (*lait).second;
499 docstring preset = arg.presetarg;
500 if (!arg.defaultarg.empty()) {
503 preset += arg.defaultarg;
506 docstring ldelim = arg.ldelim.empty() ?
507 from_ascii("{") : arg.ldelim;
508 docstring rdelim = arg.rdelim.empty() ?
509 from_ascii("}") : arg.rdelim;
510 os << ldelim << preset << rdelim;
511 } else if (!preset.empty()) {
512 docstring ldelim = arg.ldelim.empty() ?
513 from_ascii("[") : arg.ldelim;
514 docstring rdelim = arg.rdelim.empty() ?
515 from_ascii("]") : arg.rdelim;
516 os << ldelim << preset << rdelim;
517 } else if (find(required.begin(), required.end(),
518 (*lait).first) != required.end()) {
519 docstring ldelim = arg.ldelim.empty() ?
520 from_ascii("[") : arg.ldelim;
521 docstring rdelim = arg.rdelim.empty() ?
522 from_ascii("]") : arg.rdelim;
523 os << ldelim << rdelim;
530 if (runparams.for_search) {
531 // Mark end of arguments for findadv() only
532 os << "\\endarguments{}";
540 void pushLanguageName(string const & lang_name, bool localswitch)
542 OutputState * state = getOutputState();
544 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
545 state->lang_switch_depth_.push(nest_level);
546 state->open_polyglossia_lang_.push(lang_name);
550 void popLanguageName()
552 OutputState * state = getOutputState();
554 state->lang_switch_depth_.pop();
555 state->open_polyglossia_lang_.pop();
559 string const & openLanguageName()
561 OutputState * state = getOutputState();
563 return openLanguageName(state);
569 void addArgInsets(Paragraph const & par, string const & prefix,
570 Layout::LaTeXArgMap const & latexargs,
571 map<int, InsetArgument const *> & ilist,
572 vector<string> & required)
574 for (auto const & table : par.insetList()) {
575 InsetArgument const * arg = table.inset->asInsetArgument();
578 if (arg->name().empty()) {
579 LYXERR0("Error: Unnamed argument inset!");
582 string const name = prefix.empty() ?
583 arg->name() : split(arg->name(), ':');
584 // why converting into an integer?
585 unsigned int const nr = convert<unsigned int>(name);
586 if (ilist.find(nr) == ilist.end())
588 Layout::LaTeXArgMap::const_iterator const lit =
589 latexargs.find(arg->name());
590 if (lit != latexargs.end()) {
591 Layout::latexarg const & larg = lit->second;
592 vector<string> req = getVectorFromString(larg.requires);
593 move(req.begin(), req.end(), back_inserter(required));
601 void latexArgInsets(Paragraph const & par, otexstream & os,
602 OutputParams const & runparams,
603 Layout::LaTeXArgMap const & latexargs,
604 string const & prefix)
606 map<int, InsetArgument const *> ilist;
607 vector<string> required;
608 addArgInsets(par, prefix, latexargs, ilist, required);
609 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
613 void latexArgInsets(ParagraphList const & pars,
614 ParagraphList::const_iterator pit,
615 otexstream & os, OutputParams const & runparams,
616 Layout::LaTeXArgMap const & latexargs,
617 string const & prefix)
619 map<int, InsetArgument const *> ilist;
620 vector<string> required;
622 depth_type const current_depth = pit->params().depth();
623 Layout const current_layout = pit->layout();
625 // get the first paragraph in sequence with this layout and depth
628 if (lyx::prev(pit, offset) == pars.begin())
630 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
631 if (priorpit->layout() == current_layout
632 && priorpit->params().depth() == current_depth)
638 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
640 for (; spit != pars.end(); ++spit) {
641 if (spit->layout() != current_layout ||
642 spit->params().depth() < current_depth)
644 if (spit->params().depth() > current_depth)
646 addArgInsets(*spit, prefix, latexargs, ilist, required);
648 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
652 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
653 OutputParams const & runparams,
654 Layout::LaTeXArgMap const & latexargs,
655 string const & prefix)
657 map<int, InsetArgument const *> ilist;
658 vector<string> required;
660 for (Paragraph const & par : pars) {
661 if (par.layout().hasArgs())
662 // The InsetArguments inside this paragraph refer to this paragraph
664 addArgInsets(par, prefix, latexargs, ilist, required);
666 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
672 // output the proper paragraph start according to latextype.
673 void parStartCommand(Paragraph const & par, otexstream & os,
674 OutputParams const & runparams, Layout const & style)
676 switch (style.latextype) {
678 if (par.needsCProtection(runparams.moving_arg))
680 os << '\\' << from_ascii(style.latexname());
683 if (!style.latexargs().empty())
684 latexArgInsets(par, os, runparams, style.latexargs());
685 os << from_ascii(style.latexparam());
687 case LATEX_ITEM_ENVIRONMENT:
688 case LATEX_LIST_ENVIRONMENT:
689 if (runparams.for_search) {
690 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
693 os << "\\" + style.itemcommand();
695 if (!style.itemargs().empty())
696 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
700 case LATEX_ENVIRONMENT:
701 if (runparams.for_search) {
702 os << "\\latexenvironment{" << style.latexname() << "}{";
705 case LATEX_BIB_ENVIRONMENT:
706 // ignore this, the inset will write itself
715 // FIXME: this should be anonymous
716 void TeXOnePar(Buffer const & buf,
720 OutputParams const & runparams_in,
721 string const & everypar,
722 int start_pos, int end_pos,
725 BufferParams const & bparams = runparams_in.is_child
726 ? buf.masterParams() : buf.params();
727 ParagraphList const & paragraphs = text.paragraphs();
728 Paragraph const & par = paragraphs.at(pit);
729 // FIXME This check should not really be needed.
730 // Perhaps we should issue an error if it is.
731 Layout const & style = text.inset().forcePlainLayout() ?
732 bparams.documentClass().plainLayout() : par.layout();
734 if (style.inpreamble && !force)
737 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
740 OutputParams runparams = runparams_in;
741 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
742 // We reinitialze par begin and end to be on the safe side
743 // with embedded inset as we don't know if they set those
745 runparams.par_begin = 0;
746 runparams.par_end = 0;
748 bool const maintext = text.isMainText();
749 // we are at the beginning of an inset and CJK is already open;
750 // we count inheritation levels to get the inset nesting right.
751 OutputState * state = getOutputState();
752 if (pit == 0 && !maintext
753 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
754 state->cjk_inherited_ += 1;
755 state->open_encoding_ = none;
758 if (text.inset().isPassThru()) {
759 Font const outerfont = text.outerFont(pit);
761 // No newline before first paragraph in this lyxtext
764 if (!text.inset().getLayout().parbreakIsNewline())
768 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
772 Paragraph const * nextpar = runparams.isLastPar
773 ? 0 : ¶graphs.at(pit + 1);
775 bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
777 if (style.pass_thru) {
778 Font const outerfont = text.outerFont(pit);
779 parStartCommand(par, os, runparams, style);
783 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
785 // I did not create a parEndCommand for this minuscule
786 // task because in the other user of parStartCommand
787 // the code is different (JMarc)
788 if (style.isCommand())
792 if (!style.parbreak_is_newline) {
794 } else if (nextpar && !style.isEnvironment()) {
795 Layout const nextstyle = text.inset().forcePlainLayout()
796 ? bparams.documentClass().plainLayout()
798 if (nextstyle.name() != style.name())
805 // This paragraph's language
806 Language const * const par_language = par.getParLanguage(bparams);
807 Language const * const nextpar_language = nextpar ?
808 nextpar->getParLanguage(bparams) : 0;
809 // The document's language
810 Language const * const doc_language = bparams.language;
811 // The language that was in effect when the environment this paragraph is
812 // inside of was opened
813 Language const * const outer_language =
814 (runparams.local_font != 0) ?
815 runparams.local_font->language() : doc_language;
817 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
819 // The previous language that was in effect is the language of the
820 // previous paragraph, unless the previous paragraph is inside an
821 // environment with nesting depth greater than (or equal to, but with
822 // a different layout) the current one. If there is no previous
823 // paragraph, the previous language is the outer language.
824 // Note further that we take the outer language also if the prior par
825 // is PassThru, since in that case it has latex_language, and all secondary
826 // languages have been closed (#10793).
827 bool const use_prev_env_language = state->prev_env_language_ != 0
829 && priorpar->layout().isEnvironment()
830 && (priorpar->getDepth() > par.getDepth()
831 || (priorpar->getDepth() == par.getDepth()
832 && priorpar->layout() != par.layout()));
833 Language const * const prev_language =
834 runparams_in.for_search ?
835 languages.getLanguage("ignore")
836 :(priorpar && !priorpar->isPassThru())
837 ? (use_prev_env_language ? state->prev_env_language_
838 : priorpar->getParLanguage(bparams))
841 bool const use_polyglossia = runparams.use_polyglossia;
842 string const par_lang = use_polyglossia ?
843 getPolyglossiaEnvName(par_language): par_language->babel();
844 string const prev_lang = use_polyglossia ?
845 getPolyglossiaEnvName(prev_language) : prev_language->babel();
846 string const outer_lang = use_polyglossia ?
847 getPolyglossiaEnvName(outer_language) : outer_language->babel();
848 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
849 getPolyglossiaEnvName(nextpar_language) :
850 nextpar_language->babel()) : string();
851 string lang_begin_command = use_polyglossia ?
852 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
853 string lang_end_command = use_polyglossia ?
854 "\\end{$$lang}" : lyxrc.language_command_end;
855 // the '%' is necessary to prevent unwanted whitespace
856 string lang_command_termination = "%\n";
857 bool const using_begin_end = use_polyglossia ||
858 !lang_end_command.empty();
860 // For InTitle commands, we need to switch the language inside the command
861 // (see #10849); thus open the command here.
862 if (intitle_command) {
863 parStartCommand(par, os, runparams, style);
867 // In some insets (such as Arguments), we cannot use \selectlanguage.
868 // Also, if an RTL language is set via environment in polyglossia,
869 // only a nested \\text<lang> command will reset the direction for LTR
870 // languages (see # 10111).
871 bool const in_polyglossia_rtl_env =
873 && runparams.local_font != 0
874 && outer_language->rightToLeft()
875 && !par_language->rightToLeft();
876 bool const localswitch = runparams_in.for_search
877 || text.inset().forceLocalFontSwitch()
878 || (using_begin_end && text.inset().forcePlainLayout())
879 || in_polyglossia_rtl_env;
881 lang_begin_command = use_polyglossia ?
882 "\\text$$lang$$opts{" : lyxrc.language_command_local;
883 lang_end_command = "}";
884 lang_command_termination.clear();
887 bool const localswitch_needed = localswitch && par_lang != outer_lang;
889 // localswitches need to be closed and reopened at each par
890 if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
891 // check if we already put language command in TeXEnvironment()
892 && !(style.isEnvironment()
893 && (pit == 0 || (priorpar->layout() != par.layout()
894 && priorpar->getDepth() <= par.getDepth())
895 || priorpar->getDepth() < par.getDepth())))) {
897 && (!using_begin_end || langOpenedAtThisLevel(state))
898 && !lang_end_command.empty()
899 && prev_lang != outer_lang
900 && !prev_lang.empty()
901 && (!using_begin_end || !style.isEnvironment())) {
902 os << from_ascii(subst(lang_end_command,
905 << lang_command_termination;
910 // We need to open a new language if we couldn't close the previous
911 // one (because there's no language_command_end); and even if we closed
912 // the previous one, if the current language is different than the
913 // outer_language (which is currently in effect once the previous one
915 if ((lang_end_command.empty() || par_lang != outer_lang
917 || (style.isEnvironment() && par_lang != prev_lang)))
918 && !par_lang.empty()) {
919 // If we're inside an inset, and that inset is within an \L or \R
920 // (or equivalents), then within the inset, too, any opposite
921 // language paragraph should appear within an \L or \R (in addition
922 // to, outside of, the normal language switch commands).
923 // This behavior is not correct for ArabTeX, though.
926 && par_language->lang() != "arabic_arabtex"
927 && outer_language->lang() != "arabic_arabtex"
928 // are we in an inset?
929 && runparams.local_font != 0
930 // is the inset within an \L or \R?
932 // FIXME: currently, we don't check this; this means that
933 // we'll have unnnecessary \L and \R commands, but that
934 // doesn't seem to hurt (though latex will complain)
936 // is this paragraph in the opposite direction?
937 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
938 // FIXME: I don't have a working copy of the Arabi package, so
939 // I'm not sure if the farsi and arabic_arabi stuff is correct
941 if (par_language->lang() == "farsi")
943 else if (outer_language->lang() == "farsi")
945 else if (par_language->lang() == "arabic_arabi")
947 else if (outer_language->lang() == "arabic_arabi")
949 // remaining RTL languages currently is hebrew
950 else if (par_language->rightToLeft())
955 // With CJK, the CJK tag has to be closed first (see below)
956 if ((runparams.encoding->package() != Encoding::CJK || runparams.for_search)
957 && (par_lang != openLanguageName(state) || localswitch)
958 && !par_lang.empty()) {
959 string bc = use_polyglossia ?
960 getPolyglossiaBegin(lang_begin_command, par_lang,
961 par_language->polyglossiaOpts(),
963 : subst(lang_begin_command, "$$lang", par_lang);
965 os << lang_command_termination;
967 pushLanguageName(par_lang, localswitch);
972 // Switch file encoding if necessary; no need to do this for "default"
973 // encoding, since this only affects the position of the outputted
974 // \inputencoding command; the encoding switch will occur when necessary
975 if (bparams.inputenc == "auto"
976 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
977 && runparams.encoding->package() != Encoding::none) {
978 // Look ahead for future encoding changes.
979 // We try to output them at the beginning of the paragraph,
980 // since the \inputencoding command is not allowed e.g. in
981 // sections. For this reason we only set runparams.moving_arg
982 // after checking for the encoding change, otherwise the
983 // change would be always avoided by switchEncoding().
984 for (pos_type i = 0; i < par.size(); ++i) {
985 char_type const c = par.getChar(i);
986 Encoding const * const encoding =
987 par.getFontSettings(bparams, i).language()->encoding();
988 if (encoding->package() != Encoding::CJK
989 && runparams.encoding->package() == Encoding::inputenc
994 // All characters before c are in the ASCII range, and
995 // c is non-ASCII (but no inset), so change the
996 // encoding to that required by the language of c.
997 // With CJK, only add switch if we have CJK content at the beginning
999 if (i != 0 && encoding->package() == Encoding::CJK)
1002 pair<bool, int> enc_switch = switchEncoding(os.os(),
1003 bparams, runparams, *encoding);
1004 // the following is necessary after a CJK environment in a multilingual
1005 // context (nesting issue).
1006 if (par_language->encoding()->package() == Encoding::CJK
1007 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1008 os << "\\begin{CJK}{"
1009 << from_ascii(par_language->encoding()->latexName())
1010 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1011 state->open_encoding_ = CJK;
1013 if (encoding->package() != Encoding::none && enc_switch.first) {
1014 if (enc_switch.second > 0) {
1015 // the '%' is necessary to prevent unwanted whitespace
1018 // With CJK, the CJK tag had to be closed first (see above)
1019 if (runparams.encoding->package() == Encoding::CJK
1020 && par_lang != openLanguageName(state)
1021 && !par_lang.empty()) {
1022 string bc = use_polyglossia ?
1023 getPolyglossiaBegin(lang_begin_command, par_lang,
1024 par_language->polyglossiaOpts(),
1026 : subst(lang_begin_command, "$$lang", par_lang);
1028 << lang_command_termination;
1029 if (using_begin_end)
1030 pushLanguageName(par_lang, localswitch);
1032 runparams.encoding = encoding;
1038 runparams.moving_arg |= style.needprotect;
1039 Encoding const * const prev_encoding = runparams.encoding;
1041 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1042 if (par.allowParagraphCustomization()) {
1043 if (par.params().startOfAppendix()) {
1044 os << "\n\\appendix\n";
1047 // InTitle commands must use switches (not environments)
1048 // inside the commands (see #9332)
1049 if (style.intitle) {
1050 if (!par.params().spacing().isDefault())
1052 if (runparams.moving_arg)
1054 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1057 if (!par.params().spacing().isDefault()
1058 && (pit == 0 || !priorpar->hasSameLayout(par)))
1060 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1064 if (style.isCommand()) {
1070 // For InTitle commands, we already started the command before
1071 // the language switch
1072 if (!intitle_command)
1073 parStartCommand(par, os, runparams, style);
1075 Font const outerfont = text.outerFont(pit);
1078 os << from_utf8(everypar);
1079 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1081 Font const font = par.empty()
1082 ? par.getLayoutFont(bparams, outerfont)
1083 : par.getFont(bparams, par.size() - 1, outerfont);
1085 bool const is_command = style.isCommand();
1087 // InTitle commands need to be closed after the language has been closed.
1088 if (!intitle_command) {
1091 if (!style.postcommandargs().empty())
1092 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1093 if (runparams.encoding != prev_encoding) {
1094 runparams.encoding = prev_encoding;
1095 os << setEncoding(prev_encoding->iconvName());
1100 bool pending_newline = false;
1101 bool unskip_newline = false;
1102 bool close_lang_switch = false;
1103 switch (style.latextype) {
1104 case LATEX_ITEM_ENVIRONMENT:
1105 case LATEX_LIST_ENVIRONMENT:
1106 if ((nextpar && par_lang != nextpar_lang
1107 && nextpar->getDepth() == par.getDepth())
1108 || (atSameLastLangSwitchDepth(state) && nextpar
1109 && nextpar->getDepth() < par.getDepth()))
1110 close_lang_switch = using_begin_end;
1111 if (nextpar && par.params().depth() < nextpar->params().depth())
1112 pending_newline = true;
1114 case LATEX_ENVIRONMENT: {
1115 // if its the last paragraph of the current environment
1116 // skip it otherwise fall through
1118 && ((nextpar->layout() != par.layout()
1119 || nextpar->params().depth() != par.params().depth())
1120 || (!using_begin_end || par_lang != nextpar_lang)))
1122 close_lang_switch = using_begin_end;
1129 // we don't need it for the last paragraph and in InTitle commands!!!
1130 if (nextpar && !intitle_command)
1131 pending_newline = true;
1134 // InTitle commands use switches (not environments) for space settings
1135 if (par.allowParagraphCustomization() && !style.intitle) {
1136 if (!par.params().spacing().isDefault()
1137 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1138 if (pending_newline)
1141 string const endtag =
1142 par.params().spacing().writeEnvirEnd(useSetSpace);
1143 if (prefixIs(endtag, "\\end{"))
1146 os << from_ascii(endtag);
1147 pending_newline = true;
1151 // Closing the language is needed for the last paragraph in a given language
1152 // as well as for any InTitleCommand (since these set the language locally);
1153 // it is also needed if we're within an \L or \R that we may have opened above
1154 // (not necessarily in this paragraph) and are about to close.
1155 bool closing_rtl_ltr_environment = !using_begin_end
1157 && (par_language->lang() != "arabic_arabtex"
1158 && outer_language->lang() != "arabic_arabtex")
1159 // have we opened an \L or \R environment?
1160 && runparams.local_font != 0
1161 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1162 // are we about to close the language?
1163 &&((nextpar && par_lang != nextpar_lang)
1164 || (runparams.isLastPar && par_lang != outer_lang));
1166 if (localswitch_needed
1167 || (intitle_command && using_begin_end)
1168 || closing_rtl_ltr_environment
1169 || ((runparams.isLastPar || close_lang_switch)
1170 && (par_lang != outer_lang || (using_begin_end
1171 && style.isEnvironment()
1172 && par_lang != nextpar_lang)))) {
1173 // Since \selectlanguage write the language to the aux file,
1174 // we need to reset the language at the end of footnote or
1177 if (!localswitch && (pending_newline || close_lang_switch))
1180 // when the paragraph uses CJK, the language has to be closed earlier
1181 if ((font.language()->encoding()->package() != Encoding::CJK) || runparams_in.for_search) {
1182 if (lang_end_command.empty()) {
1183 // If this is a child, we should restore the
1184 // master language after the last paragraph.
1185 Language const * const current_language =
1186 (runparams.isLastPar && runparams.master_language)
1187 ? runparams.master_language
1189 string const current_lang = use_polyglossia
1190 ? getPolyglossiaEnvName(current_language)
1191 : current_language->babel();
1192 if (!current_lang.empty()
1193 && current_lang != openLanguageName(state)) {
1194 string bc = use_polyglossia ?
1195 getPolyglossiaBegin(lang_begin_command, current_lang,
1196 current_language->polyglossiaOpts(),
1198 : subst(lang_begin_command, "$$lang", current_lang);
1200 pending_newline = !localswitch;
1201 unskip_newline = !localswitch;
1202 if (using_begin_end)
1203 pushLanguageName(current_lang, localswitch);
1205 } else if ((!using_begin_end ||
1206 langOpenedAtThisLevel(state)) &&
1207 !par_lang.empty()) {
1208 // If we are in an environment, we have to
1209 // close the "outer" language afterwards
1210 string const & cur_lang = openLanguageName(state);
1211 if (!style.isEnvironment()
1212 || (close_lang_switch
1213 && atSameLastLangSwitchDepth(state)
1214 && par_lang != outer_lang
1215 && (par_lang != cur_lang
1216 || (cur_lang != outer_lang
1218 && style != nextpar->layout())))
1219 || (atSameLastLangSwitchDepth(state)
1220 && state->lang_switch_depth_.size()
1221 && cur_lang != par_lang)
1222 || in_polyglossia_rtl_env)
1224 if (using_begin_end && !localswitch)
1226 os << from_ascii(subst(
1230 pending_newline = !localswitch;
1231 unskip_newline = !localswitch;
1232 if (using_begin_end)
1238 if (closing_rtl_ltr_environment)
1241 // InTitle commands need to be closed after the language has been closed.
1242 if (intitle_command) {
1245 if (!style.postcommandargs().empty())
1246 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1247 if (runparams.encoding != prev_encoding) {
1248 runparams.encoding = prev_encoding;
1249 os << setEncoding(prev_encoding->iconvName());
1254 bool const last_was_separator =
1255 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1257 if (pending_newline) {
1259 // prevent unwanted whitespace
1261 if (!os.afterParbreak() && !last_was_separator)
1265 // if this is a CJK-paragraph and the next isn't, close CJK
1266 // also if the next paragraph is a multilingual environment (because of nesting)
1268 && (state->open_encoding_ == CJK && bparams.encoding().iconvName() != "UTF-8"
1269 && bparams.encoding().package() != Encoding::CJK )
1270 && (nextpar_language->encoding()->package() != Encoding::CJK
1271 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1272 // inbetween environments, CJK has to be closed later (nesting!)
1273 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1274 os << "\\end{CJK}\n";
1275 state->open_encoding_ = none;
1278 // If this is the last paragraph, close the CJK environment
1279 // if necessary. If it's an environment or nested in an environment,
1280 // we'll have to \end that first.
1281 if (runparams.isLastPar && !style.isEnvironment()
1282 && par.params().depth() < 1) {
1283 switch (state->open_encoding_) {
1285 // do nothing at the end of child documents
1286 if (maintext && buf.masterBuffer() != &buf)
1288 // end of main text: also insert a \clearpage (see #5386)
1290 os << "\n\\clearpage\n\\end{CJK}\n";
1294 state->open_encoding_ = none;
1299 state->open_encoding_ = none;
1309 // If this is the last paragraph, and a local_font was set upon entering
1310 // the inset, and we're using "auto" or "default" encoding, and not
1311 // compiling with XeTeX or LuaTeX, the encoding
1312 // should be set back to that local_font's encoding.
1313 if (runparams.isLastPar && runparams_in.local_font != 0
1314 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1315 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1316 && !runparams.isFullUnicode()
1318 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1319 os << setEncoding(runparams_in.encoding->iconvName());
1321 // Otherwise, the current encoding should be set for the next paragraph.
1323 runparams_in.encoding = runparams.encoding;
1326 // we don't need a newline for the last paragraph!!!
1327 // Note from JMarc: we will re-add a \n explicitly in
1328 // TeXEnvironment, because it is needed in this case
1329 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1330 // Make sure to start a new line
1332 Layout const & next_layout = nextpar->layout();
1333 // A newline '\n' is always output before a command,
1334 // so avoid doubling it.
1335 if (!next_layout.isCommand()) {
1336 // Here we now try to avoid spurious empty lines by
1337 // outputting a paragraph break only if: (case 1) the
1338 // paragraph style allows parbreaks and no \begin, \end
1339 // or \item tags are going to follow (i.e., if the next
1340 // isn't the first or the current isn't the last
1341 // paragraph of an environment or itemize) and the
1342 // depth and alignment of the following paragraph is
1343 // unchanged, or (case 2) the following is a
1344 // non-environment paragraph whose depth is increased
1345 // but whose alignment is unchanged, or (case 3) the
1346 // paragraph is not an environment and the next one is a
1347 // non-itemize-like env at lower depth, or (case 4) the
1348 // paragraph is a command not followed by an environment
1349 // and the alignment of the current and next paragraph
1350 // is unchanged, or (case 5) the current alignment is
1351 // changed and a standard paragraph follows.
1352 DocumentClass const & tclass = bparams.documentClass();
1353 if ((style == next_layout
1354 && !style.parbreak_is_newline
1355 && !text.inset().getLayout().parbreakIsNewline()
1356 && style.latextype != LATEX_ITEM_ENVIRONMENT
1357 && style.latextype != LATEX_LIST_ENVIRONMENT
1358 && style.align == par.getAlign()
1359 && nextpar->getDepth() == par.getDepth()
1360 && nextpar->getAlign() == par.getAlign())
1361 || (!next_layout.isEnvironment()
1362 && nextpar->getDepth() > par.getDepth()
1363 && nextpar->getAlign() == par.getAlign())
1364 || (!style.isEnvironment()
1365 && next_layout.latextype == LATEX_ENVIRONMENT
1366 && nextpar->getDepth() < par.getDepth())
1367 || (style.isCommand()
1368 && !next_layout.isEnvironment()
1369 && style.align == par.getAlign()
1370 && next_layout.align == nextpar->getAlign())
1371 || (style.align != par.getAlign()
1372 && tclass.isDefaultLayout(next_layout))) {
1378 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1379 << &par << " next " << nextpar);
1385 // LaTeX all paragraphs
1386 void latexParagraphs(Buffer const & buf,
1389 OutputParams const & runparams,
1390 string const & everypar)
1392 LASSERT(runparams.par_begin <= runparams.par_end,
1393 { os << "% LaTeX Output Error\n"; return; } );
1395 BufferParams const & bparams = buf.params();
1396 BufferParams const & mparams = buf.masterParams();
1398 bool const maintext = text.isMainText();
1399 bool const is_child = buf.masterBuffer() != &buf;
1400 bool const multibib_child = maintext && is_child
1401 && mparams.multibib == "child";
1403 if (multibib_child && mparams.useBiblatex())
1404 os << "\\newrefsection";
1405 else if (multibib_child && mparams.useBibtopic()) {
1406 os << "\\begin{btUnit}\n";
1407 runparams.openbtUnit = true;
1410 // Open a CJK environment at the beginning of the main buffer
1411 // if the document's main encoding requires the CJK package
1412 // or the document encoding is utf8 and the CJK package is required
1413 // (but not in child documents or documents using system fonts):
1414 OutputState * state = getOutputState();
1415 if (maintext && !is_child && !bparams.useNonTeXFonts
1416 && (bparams.encoding().package() == Encoding::CJK
1417 || (bparams.encoding().name() == "utf8"
1418 && bparams.language->encoding()->package() == Encoding::CJK)
1419 // FIXME: should test if any language requires CJK
1420 // && LaTeXFeatures::mustProvide("CJK"))
1421 // error: cannot call member function ‘bool lyx::LaTeXFeatures::mustProvide(const string&) const’ without object
1423 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1424 ? from_ascii("UTF8") : from_ascii(bparams.encoding().latexName());
1425 os << "\\begin{CJK}{" << cjkenc
1426 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1427 state->open_encoding_ = CJK;
1429 // if "auto begin" is switched off, explicitly switch the
1430 // language on at start
1431 string const mainlang = runparams.use_polyglossia
1432 ? getPolyglossiaEnvName(bparams.language)
1433 : bparams.language->babel();
1434 string const lang_begin_command = runparams.use_polyglossia ?
1435 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1436 string const lang_end_command = runparams.use_polyglossia ?
1437 "\\end{$$lang}" : lyxrc.language_command_end;
1438 bool const using_begin_end = runparams.use_polyglossia ||
1439 !lang_end_command.empty();
1441 if (maintext && !lyxrc.language_auto_begin &&
1442 !mainlang.empty()) {
1444 string bc = runparams.use_polyglossia ?
1445 getPolyglossiaBegin(lang_begin_command, mainlang,
1446 bparams.language->polyglossiaOpts())
1447 : subst(lang_begin_command, "$$lang", mainlang);
1450 if (using_begin_end)
1451 pushLanguageName(mainlang);
1454 ParagraphList const & paragraphs = text.paragraphs();
1456 if (runparams.par_begin == runparams.par_end) {
1457 // The full doc will be exported but it is easier to just rely on
1458 // runparams range parameters that will be passed TeXEnvironment.
1459 runparams.par_begin = 0;
1460 runparams.par_end = paragraphs.size();
1463 pit_type pit = runparams.par_begin;
1464 // lastpit is for the language check after the loop.
1465 pit_type lastpit = pit;
1466 // variables used in the loop:
1467 bool was_title = false;
1468 bool already_title = false;
1469 DocumentClass const & tclass = bparams.documentClass();
1471 // Did we already warn about inTitle layout mixing? (we only warn once)
1472 bool gave_layout_warning = false;
1473 for (; pit < runparams.par_end; ++pit) {
1475 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1477 // FIXME This check should not be needed. We should
1478 // perhaps issue an error if it is.
1479 Layout const & layout = text.inset().forcePlainLayout() ?
1480 tclass.plainLayout() : par->layout();
1482 if (layout.intitle) {
1483 if (already_title) {
1484 if (!gave_layout_warning && !runparams.dryrun) {
1485 gave_layout_warning = true;
1486 frontend::Alert::warning(_("Error in latexParagraphs"),
1487 bformat(_("You are using at least one "
1488 "layout (%1$s) intended for the title, "
1489 "after using non-title layouts. This "
1490 "could lead to missing or incorrect output."
1493 } else if (!was_title) {
1495 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1497 << from_ascii(tclass.titlename())
1501 } else if (was_title && !already_title && !layout.inpreamble) {
1502 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1503 os << "\\end{" << from_ascii(tclass.titlename())
1507 os << "\\" << from_ascii(tclass.titlename())
1510 already_title = true;
1514 if (layout.isCommand() && !layout.latexname().empty()
1515 && layout.latexname() == bparams.multibib) {
1516 if (runparams.openbtUnit)
1517 os << "\\end{btUnit}\n";
1518 if (!bparams.useBiblatex()) {
1519 os << '\n' << "\\begin{btUnit}\n";
1520 runparams.openbtUnit = true;
1524 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1525 // This is a standard top level paragraph, TeX it and continue.
1526 TeXOnePar(buf, text, pit, os, runparams, everypar);
1530 TeXEnvironmentData const data =
1531 prepareEnvironment(buf, text, par, os, runparams);
1532 // pit can be changed in TeXEnvironment.
1533 TeXEnvironment(buf, text, runparams, pit, os);
1534 finishEnvironment(os, runparams, data);
1537 if (pit == runparams.par_end) {
1538 // Make sure that the last paragraph is
1539 // correctly terminated (because TeXOnePar does
1540 // not add a \n in this case)
1544 // It might be that we only have a title in this document
1545 if (was_title && !already_title) {
1546 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1547 os << "\\end{" << from_ascii(tclass.titlename())
1550 os << "\\" << from_ascii(tclass.titlename())
1555 if (maintext && !is_child && runparams.openbtUnit)
1556 os << "\\end{btUnit}\n";
1558 // if "auto end" is switched off, explicitly close the language at the end
1559 // but only if the last par is in a babel or polyglossia language
1560 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1561 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1562 os << from_utf8(subst(lang_end_command,
1566 if (using_begin_end)
1570 // If the last paragraph is an environment, we'll have to close
1571 // CJK at the very end to do proper nesting.
1572 if (maintext && !is_child && state->open_encoding_ == CJK) {
1573 os << "\\clearpage\n\\end{CJK}\n";
1574 state->open_encoding_ = none;
1576 // Likewise for polyglossia or when using begin/end commands
1577 string const & cur_lang = openLanguageName(state);
1578 if (maintext && !is_child && !cur_lang.empty()) {
1579 os << from_utf8(subst(lang_end_command,
1583 if (using_begin_end)
1587 // reset inherited encoding
1588 if (state->cjk_inherited_ > 0) {
1589 state->cjk_inherited_ -= 1;
1590 if (state->cjk_inherited_ == 0)
1591 state->open_encoding_ = CJK;
1594 if (multibib_child && mparams.useBibtopic()) {
1595 os << "\\end{btUnit}\n";
1596 runparams.openbtUnit = false;
1601 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1602 OutputParams const & runparams, Encoding const & newEnc,
1603 bool force, bool noswitchmacro)
1605 // XeTeX/LuaTeX use only one encoding per document:
1606 // * with useNonTeXFonts: "utf8plain",
1607 // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1608 // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1609 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1610 return make_pair(false, 0);
1612 Encoding const & oldEnc = *runparams.encoding;
1613 bool moving_arg = runparams.moving_arg;
1615 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1616 return make_pair(false, 0);
1618 // Do nothing if the encoding is unchanged.
1619 if (oldEnc.name() == newEnc.name())
1620 return make_pair(false, 0);
1622 // FIXME We ignore encoding switches from/to encodings that do
1623 // neither support the inputenc package nor the CJK package here.
1624 // This does of course only work in special cases (e.g. switch from
1625 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1626 // but it is the best we can do
1628 // 2019-01-08 Possibly no longer required since tis620-0 is supported
1629 // by inputenc (but check special encodings "utf8-plain" and "default").
1630 if (oldEnc.package() == Encoding::none || newEnc.package() == Encoding::none)
1631 return make_pair(false, 0);
1634 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1635 << oldEnc.name() << " to " << newEnc.name());
1636 os << setEncoding(newEnc.iconvName());
1637 if (bparams.inputenc == "default")
1638 return make_pair(true, 0);
1640 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1641 OutputState * state = getOutputState();
1642 switch (newEnc.package()) {
1643 case Encoding::none:
1644 case Encoding::japanese:
1645 // shouldn't ever reach here, see above
1646 return make_pair(true, 0);
1647 case Encoding::inputenc: {
1648 int count = inputenc_arg.length();
1649 if (oldEnc.package() == Encoding::CJK &&
1650 state->open_encoding_ == CJK) {
1652 state->open_encoding_ = none;
1655 else if (oldEnc.package() == Encoding::inputenc &&
1656 state->open_encoding_ == inputenc) {
1658 state->open_encoding_ = none;
1661 if (runparams.local_font != 0
1662 && oldEnc.package() == Encoding::CJK) {
1663 // within insets, \inputenc switches need
1664 // to be embraced within \bgroup...\egroup;
1668 state->open_encoding_ = inputenc;
1670 // with the japanese option, inputenc is omitted.
1671 if (runparams.use_japanese || noswitchmacro)
1672 return make_pair(true, count);
1673 os << "\\inputencoding{" << inputenc_arg << '}';
1674 return make_pair(true, count + 16);
1676 case Encoding::CJK: {
1677 int count = inputenc_arg.length();
1678 if (oldEnc.package() == Encoding::CJK &&
1679 state->open_encoding_ == CJK) {
1683 if (oldEnc.package() == Encoding::inputenc &&
1684 state->open_encoding_ == inputenc) {
1688 os << "\\begin{CJK}{"
1689 << from_ascii(newEnc.latexName()) << "}{"
1690 << from_ascii(bparams.fonts_cjk) << "}";
1691 state->open_encoding_ = CJK;
1692 return make_pair(true, count + 15);
1695 // Dead code to avoid a warning:
1696 return make_pair(true, 0);