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 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
311 && LaTeXFeatures::isAvailable("CJKutf8")) ?
313 : from_ascii(data.par_language->encoding()->latexName());
314 os << "\\begin{CJK}{" << cjkenc
315 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
317 state->open_encoding_ = CJK;
318 data.cjk_nested = true;
324 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
325 TeXEnvironmentData const & data)
327 OutputState * state = getOutputState();
328 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
329 if (state->open_encoding_ == CJK && data.cjk_nested) {
330 // We need to close the encoding even if it does not change
331 // to do correct environment nesting
332 os << "\\end{CJK}\n";
333 state->open_encoding_ = none;
336 if (data.style->isEnvironment()) {
338 bool const using_begin_end =
339 runparams.use_polyglossia ||
340 !lyxrc.language_command_end.empty();
341 // Close any language opened at this nest level
342 if (using_begin_end) {
343 while (langOpenedAtThisLevel(state)) {
344 if (isLocalSwitch(state)) {
348 << openLanguageName(state)
354 state->nest_level_ -= 1;
355 string const & name = data.style->latexname();
357 os << "\\end{" << from_ascii(name) << "}\n";
358 state->prev_env_language_ = data.par_language;
359 if (runparams.encoding != data.prev_encoding) {
360 runparams.encoding = data.prev_encoding;
361 os << setEncoding(data.prev_encoding->iconvName());
365 if (data.leftindent_open) {
366 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
367 state->prev_env_language_ = data.par_language;
368 if (runparams.encoding != data.prev_encoding) {
369 runparams.encoding = data.prev_encoding;
370 os << setEncoding(data.prev_encoding->iconvName());
374 // Check whether we should output a blank line after the environment
375 if (!data.style->nextnoindent)
380 void TeXEnvironment(Buffer const & buf, Text const & text,
381 OutputParams const & runparams,
382 pit_type & pit, otexstream & os)
384 ParagraphList const & paragraphs = text.paragraphs();
385 ParagraphList::const_iterator ipar = paragraphs.constIterator(pit);
386 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
388 Layout const & current_layout = ipar->layout();
389 depth_type const current_depth = ipar->params().depth();
390 Length const & current_left_indent = ipar->params().leftIndent();
392 // This is for debugging purpose at the end.
393 pit_type const par_begin = pit;
394 for (; pit < runparams.par_end; ++pit) {
395 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
397 // check first if this is an higher depth paragraph.
398 bool go_out = (par->params().depth() < current_depth);
399 if (par->params().depth() == current_depth) {
400 // This environment is finished.
401 go_out |= (par->layout() != current_layout);
402 go_out |= (par->params().leftIndent() != current_left_indent);
405 // nothing to do here, restore pit and go out.
410 if (par->layout() == current_layout
411 && par->params().depth() == current_depth
412 && par->params().leftIndent() == current_left_indent) {
413 // We are still in the same environment so TeXOnePar and continue;
414 TeXOnePar(buf, text, pit, os, runparams);
418 // We are now in a deeper environment.
419 // Either par->layout() != current_layout
420 // Or par->params().depth() > current_depth
421 // Or par->params().leftIndent() != current_left_indent)
423 // FIXME This test should not be necessary.
424 // We should perhaps issue an error if it is.
425 bool const force_plain_layout = text.inset().forcePlainLayout();
426 Layout const & style = force_plain_layout
427 ? buf.params().documentClass().plainLayout()
430 if (!style.isEnvironment()) {
431 // This is a standard paragraph, no need to call TeXEnvironment.
432 TeXOnePar(buf, text, pit, os, runparams);
436 // This is a new environment.
437 TeXEnvironmentData const data =
438 prepareEnvironment(buf, text, par, os, runparams);
439 // Recursive call to TeXEnvironment!
440 TeXEnvironment(buf, text, runparams, pit, os);
441 finishEnvironment(os, runparams, data);
444 if (pit != runparams.par_end)
445 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
449 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
450 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
452 unsigned int const argnr = latexargs.size();
456 // Default and preset args are always output, so if they require
457 // other arguments, consider this.
458 for (auto const & larg : latexargs) {
459 Layout::latexarg const & arg = larg.second;
460 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
461 vector<string> req = getVectorFromString(arg.requires);
462 required.insert(required.end(), req.begin(), req.end());
466 for (unsigned int i = 1; i <= argnr; ++i) {
467 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
468 bool inserted = false;
469 if (lit != ilist.end()) {
470 InsetArgument const * ins = (*lit).second;
472 Layout::LaTeXArgMap::const_iterator const lait =
473 latexargs.find(ins->name());
474 if (lait != latexargs.end()) {
475 Layout::latexarg arg = (*lait).second;
479 ldelim = arg.mandatory ?
480 from_ascii("{") : from_ascii("[");
481 rdelim = arg.mandatory ?
482 from_ascii("}") : from_ascii("]");
484 if (!arg.ldelim.empty())
486 if (!arg.rdelim.empty())
488 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
489 if (prefix == "listpreamble:")
496 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
497 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
498 for (; lait != laend; ++lait) {
499 string const name = prefix + convert<string>(i);
500 if ((*lait).first == name) {
501 Layout::latexarg arg = (*lait).second;
502 docstring preset = arg.presetarg;
503 if (!arg.defaultarg.empty()) {
506 preset += arg.defaultarg;
509 docstring ldelim = arg.ldelim.empty() ?
510 from_ascii("{") : arg.ldelim;
511 docstring rdelim = arg.rdelim.empty() ?
512 from_ascii("}") : arg.rdelim;
513 os << ldelim << preset << rdelim;
514 } else if (!preset.empty()) {
515 docstring ldelim = arg.ldelim.empty() ?
516 from_ascii("[") : arg.ldelim;
517 docstring rdelim = arg.rdelim.empty() ?
518 from_ascii("]") : arg.rdelim;
519 os << ldelim << preset << rdelim;
520 } else if (find(required.begin(), required.end(),
521 (*lait).first) != required.end()) {
522 docstring ldelim = arg.ldelim.empty() ?
523 from_ascii("[") : arg.ldelim;
524 docstring rdelim = arg.rdelim.empty() ?
525 from_ascii("]") : arg.rdelim;
526 os << ldelim << rdelim;
539 void pushLanguageName(string const & lang_name, bool localswitch)
541 OutputState * state = getOutputState();
543 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
544 state->lang_switch_depth_.push(nest_level);
545 state->open_polyglossia_lang_.push(lang_name);
549 void popLanguageName()
551 OutputState * state = getOutputState();
553 state->lang_switch_depth_.pop();
554 state->open_polyglossia_lang_.pop();
558 string const & openLanguageName()
560 OutputState * state = getOutputState();
562 return openLanguageName(state);
568 void addArgInsets(Paragraph const & par, string const & prefix,
569 Layout::LaTeXArgMap const & latexargs,
570 map<int, InsetArgument const *> & ilist,
571 vector<string> & required)
573 for (auto const & table : par.insetList()) {
574 InsetArgument const * arg = table.inset->asInsetArgument();
577 if (arg->name().empty()) {
578 LYXERR0("Error: Unnamed argument inset!");
581 string const name = prefix.empty() ?
582 arg->name() : split(arg->name(), ':');
583 // why converting into an integer?
584 unsigned int const nr = convert<unsigned int>(name);
585 if (ilist.find(nr) == ilist.end())
587 Layout::LaTeXArgMap::const_iterator const lit =
588 latexargs.find(arg->name());
589 if (lit != latexargs.end()) {
590 Layout::latexarg const & larg = lit->second;
591 vector<string> req = getVectorFromString(larg.requires);
592 move(req.begin(), req.end(), back_inserter(required));
600 void latexArgInsets(Paragraph const & par, otexstream & os,
601 OutputParams const & runparams,
602 Layout::LaTeXArgMap const & latexargs,
603 string const & prefix)
605 map<int, InsetArgument const *> ilist;
606 vector<string> required;
607 addArgInsets(par, prefix, latexargs, ilist, required);
608 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
612 void latexArgInsets(ParagraphList const & pars,
613 ParagraphList::const_iterator pit,
614 otexstream & os, OutputParams const & runparams,
615 Layout::LaTeXArgMap const & latexargs,
616 string const & prefix)
618 map<int, InsetArgument const *> ilist;
619 vector<string> required;
621 depth_type const current_depth = pit->params().depth();
622 Layout const current_layout = pit->layout();
624 // get the first paragraph in sequence with this layout and depth
627 if (lyx::prev(pit, offset) == pars.begin())
629 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
630 if (priorpit->layout() == current_layout
631 && priorpit->params().depth() == current_depth)
637 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
639 for (; spit != pars.end(); ++spit) {
640 if (spit->layout() != current_layout ||
641 spit->params().depth() < current_depth)
643 if (spit->params().depth() > current_depth)
645 addArgInsets(*spit, prefix, latexargs, ilist, required);
647 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
651 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
652 OutputParams const & runparams,
653 Layout::LaTeXArgMap const & latexargs,
654 string const & prefix)
656 map<int, InsetArgument const *> ilist;
657 vector<string> required;
659 for (Paragraph const & par : pars) {
660 if (par.layout().hasArgs())
661 // The InsetArguments inside this paragraph refer to this paragraph
663 addArgInsets(par, prefix, latexargs, ilist, required);
665 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
671 // output the proper paragraph start according to latextype.
672 void parStartCommand(Paragraph const & par, otexstream & os,
673 OutputParams const & runparams, Layout const & style)
675 switch (style.latextype) {
677 if (par.needsCProtection(runparams.moving_arg))
679 os << '\\' << from_ascii(style.latexname());
682 if (!style.latexargs().empty())
683 latexArgInsets(par, os, runparams, style.latexargs());
684 os << from_ascii(style.latexparam());
686 case LATEX_ITEM_ENVIRONMENT:
687 case LATEX_LIST_ENVIRONMENT:
688 if (runparams.for_search) {
689 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
692 os << "\\" + style.itemcommand();
694 if (!style.itemargs().empty())
695 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
699 case LATEX_BIB_ENVIRONMENT:
700 // ignore this, the inset will write itself
709 // FIXME: this should be anonymous
710 void TeXOnePar(Buffer const & buf,
714 OutputParams const & runparams_in,
715 string const & everypar,
716 int start_pos, int end_pos,
719 BufferParams const & bparams = runparams_in.is_child
720 ? buf.masterParams() : buf.params();
721 ParagraphList const & paragraphs = text.paragraphs();
722 Paragraph const & par = paragraphs.at(pit);
723 // FIXME This check should not really be needed.
724 // Perhaps we should issue an error if it is.
725 Layout const & style = text.inset().forcePlainLayout() ?
726 bparams.documentClass().plainLayout() : par.layout();
728 if (style.inpreamble && !force)
731 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
734 OutputParams runparams = runparams_in;
735 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
736 // We reinitialze par begin and end to be on the safe side
737 // with embedded inset as we don't know if they set those
739 runparams.par_begin = 0;
740 runparams.par_end = 0;
742 bool const maintext = text.isMainText();
743 // we are at the beginning of an inset and CJK is already open;
744 // we count inheritation levels to get the inset nesting right.
745 OutputState * state = getOutputState();
746 if (pit == 0 && !maintext
747 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
748 state->cjk_inherited_ += 1;
749 state->open_encoding_ = none;
752 if (text.inset().isPassThru()) {
753 Font const outerfont = text.outerFont(pit);
755 // No newline before first paragraph in this lyxtext
758 if (!text.inset().getLayout().parbreakIsNewline())
762 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
766 Paragraph const * nextpar = runparams.isLastPar
767 ? 0 : ¶graphs.at(pit + 1);
769 bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
771 if (style.pass_thru) {
772 Font const outerfont = text.outerFont(pit);
773 parStartCommand(par, os, runparams, style);
777 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
779 // I did not create a parEndCommand for this minuscule
780 // task because in the other user of parStartCommand
781 // the code is different (JMarc)
782 if (style.isCommand())
786 if (!style.parbreak_is_newline) {
788 } else if (nextpar && !style.isEnvironment()) {
789 Layout const nextstyle = text.inset().forcePlainLayout()
790 ? bparams.documentClass().plainLayout()
792 if (nextstyle.name() != style.name())
799 // This paragraph's language
800 Language const * const par_language = par.getParLanguage(bparams);
801 Language const * const nextpar_language = nextpar ?
802 nextpar->getParLanguage(bparams) : 0;
803 // The document's language
804 Language const * const doc_language = bparams.language;
805 // The language that was in effect when the environment this paragraph is
806 // inside of was opened
807 Language const * const outer_language =
808 (runparams.local_font != 0) ?
809 runparams.local_font->language() : doc_language;
811 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
813 // The previous language that was in effect is the language of the
814 // previous paragraph, unless the previous paragraph is inside an
815 // environment with nesting depth greater than (or equal to, but with
816 // a different layout) the current one. If there is no previous
817 // paragraph, the previous language is the outer language.
818 // Note further that we take the outer language also if the prior par
819 // is PassThru, since in that case it has latex_language, and all secondary
820 // languages have been closed (#10793).
821 bool const use_prev_env_language = state->prev_env_language_ != 0
823 && priorpar->layout().isEnvironment()
824 && (priorpar->getDepth() > par.getDepth()
825 || (priorpar->getDepth() == par.getDepth()
826 && priorpar->layout() != par.layout()));
827 Language const * const prev_language =
828 runparams_in.for_search ?
829 languages.getLanguage("ignore")
830 :(priorpar && !priorpar->isPassThru())
831 ? (use_prev_env_language ? state->prev_env_language_
832 : priorpar->getParLanguage(bparams))
835 bool const use_polyglossia = runparams.use_polyglossia;
836 string const par_lang = use_polyglossia ?
837 getPolyglossiaEnvName(par_language): par_language->babel();
838 string const prev_lang = use_polyglossia ?
839 getPolyglossiaEnvName(prev_language) : prev_language->babel();
840 string const outer_lang = use_polyglossia ?
841 getPolyglossiaEnvName(outer_language) : outer_language->babel();
842 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
843 getPolyglossiaEnvName(nextpar_language) :
844 nextpar_language->babel()) : string();
845 string lang_begin_command = use_polyglossia ?
846 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
847 string lang_end_command = use_polyglossia ?
848 "\\end{$$lang}" : lyxrc.language_command_end;
849 // the '%' is necessary to prevent unwanted whitespace
850 string lang_command_termination = "%\n";
851 bool const using_begin_end = use_polyglossia ||
852 !lang_end_command.empty();
854 // For InTitle commands, we need to switch the language inside the command
855 // (see #10849); thus open the command here.
856 if (intitle_command) {
857 parStartCommand(par, os, runparams, style);
861 // In some insets (such as Arguments), we cannot use \selectlanguage.
862 // Also, if an RTL language is set via environment in polyglossia,
863 // only a nested \\text<lang> command will reset the direction for LTR
864 // languages (see # 10111).
865 bool const in_polyglossia_rtl_env =
867 && runparams.local_font != 0
868 && outer_language->rightToLeft()
869 && !par_language->rightToLeft();
870 bool const localswitch = runparams_in.for_search
871 || text.inset().forceLocalFontSwitch()
872 || (using_begin_end && text.inset().forcePlainLayout())
873 || in_polyglossia_rtl_env;
875 lang_begin_command = use_polyglossia ?
876 "\\text$$lang$$opts{" : lyxrc.language_command_local;
877 lang_end_command = "}";
878 lang_command_termination.clear();
881 bool const localswitch_needed = localswitch && par_lang != outer_lang;
883 // localswitches need to be closed and reopened at each par
884 if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
885 // check if we already put language command in TeXEnvironment()
886 && !(style.isEnvironment()
887 && (pit == 0 || (priorpar->layout() != par.layout()
888 && priorpar->getDepth() <= par.getDepth())
889 || priorpar->getDepth() < par.getDepth())))) {
891 && (!using_begin_end || langOpenedAtThisLevel(state))
892 && !lang_end_command.empty()
893 && prev_lang != outer_lang
894 && !prev_lang.empty()
895 && (!using_begin_end || !style.isEnvironment())) {
896 os << from_ascii(subst(lang_end_command,
899 << lang_command_termination;
904 // We need to open a new language if we couldn't close the previous
905 // one (because there's no language_command_end); and even if we closed
906 // the previous one, if the current language is different than the
907 // outer_language (which is currently in effect once the previous one
909 if ((lang_end_command.empty() || par_lang != outer_lang
911 || (style.isEnvironment() && par_lang != prev_lang)))
912 && !par_lang.empty()) {
913 // If we're inside an inset, and that inset is within an \L or \R
914 // (or equivalents), then within the inset, too, any opposite
915 // language paragraph should appear within an \L or \R (in addition
916 // to, outside of, the normal language switch commands).
917 // This behavior is not correct for ArabTeX, though.
920 && par_language->lang() != "arabic_arabtex"
921 && outer_language->lang() != "arabic_arabtex"
922 // are we in an inset?
923 && runparams.local_font != 0
924 // is the inset within an \L or \R?
926 // FIXME: currently, we don't check this; this means that
927 // we'll have unnnecessary \L and \R commands, but that
928 // doesn't seem to hurt (though latex will complain)
930 // is this paragraph in the opposite direction?
931 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
932 // FIXME: I don't have a working copy of the Arabi package, so
933 // I'm not sure if the farsi and arabic_arabi stuff is correct
935 if (par_language->lang() == "farsi")
937 else if (outer_language->lang() == "farsi")
939 else if (par_language->lang() == "arabic_arabi")
941 else if (outer_language->lang() == "arabic_arabi")
943 // remaining RTL languages currently is hebrew
944 else if (par_language->rightToLeft())
949 // With CJK, the CJK tag has to be closed first (see below)
950 if ((runparams.encoding->package() != Encoding::CJK || runparams.for_search)
951 && (par_lang != openLanguageName(state) || localswitch)
952 && !par_lang.empty()) {
953 string bc = use_polyglossia ?
954 getPolyglossiaBegin(lang_begin_command, par_lang,
955 par_language->polyglossiaOpts(),
957 : subst(lang_begin_command, "$$lang", par_lang);
959 os << lang_command_termination;
961 pushLanguageName(par_lang, localswitch);
966 // Switch file encoding if necessary; no need to do this for "default"
967 // encoding, since this only affects the position of the outputted
968 // \inputencoding command; the encoding switch will occur when necessary
969 if (bparams.inputenc == "auto"
970 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
971 && runparams.encoding->package() != Encoding::none) {
972 // Look ahead for future encoding changes.
973 // We try to output them at the beginning of the paragraph,
974 // since the \inputencoding command is not allowed e.g. in
975 // sections. For this reason we only set runparams.moving_arg
976 // after checking for the encoding change, otherwise the
977 // change would be always avoided by switchEncoding().
978 for (pos_type i = 0; i < par.size(); ++i) {
979 char_type const c = par.getChar(i);
980 Encoding const * const encoding =
981 par.getFontSettings(bparams, i).language()->encoding();
982 if (encoding->package() != Encoding::CJK
983 && runparams.encoding->package() == Encoding::inputenc
988 // All characters before c are in the ASCII range, and
989 // c is non-ASCII (but no inset), so change the
990 // encoding to that required by the language of c.
991 // With CJK, only add switch if we have CJK content at the beginning
993 if (i != 0 && encoding->package() == Encoding::CJK)
996 pair<bool, int> enc_switch = switchEncoding(os.os(),
997 bparams, runparams, *encoding);
998 // the following is necessary after a CJK environment in a multilingual
999 // context (nesting issue).
1000 if (par_language->encoding()->package() == Encoding::CJK
1001 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1002 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1003 && LaTeXFeatures::isAvailable("CJKutf8")) ?
1005 : from_ascii(par_language->encoding()->latexName());
1006 os << "\\begin{CJK}{" << cjkenc
1007 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1008 state->open_encoding_ = CJK;
1010 if (encoding->package() != Encoding::none && enc_switch.first) {
1011 if (enc_switch.second > 0) {
1012 // the '%' is necessary to prevent unwanted whitespace
1015 // With CJK, the CJK tag had to be closed first (see above)
1016 if (runparams.encoding->package() == Encoding::CJK
1017 && par_lang != openLanguageName(state)
1018 && !par_lang.empty()) {
1019 string bc = use_polyglossia ?
1020 getPolyglossiaBegin(lang_begin_command, par_lang,
1021 par_language->polyglossiaOpts(),
1023 : subst(lang_begin_command, "$$lang", par_lang);
1025 << lang_command_termination;
1026 if (using_begin_end)
1027 pushLanguageName(par_lang, localswitch);
1029 runparams.encoding = encoding;
1035 runparams.moving_arg |= style.needprotect;
1036 Encoding const * const prev_encoding = runparams.encoding;
1038 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1039 if (par.allowParagraphCustomization()) {
1040 if (par.params().startOfAppendix()) {
1041 os << "\n\\appendix\n";
1044 // InTitle commands must use switches (not environments)
1045 // inside the commands (see #9332)
1046 if (style.intitle) {
1047 if (!par.params().spacing().isDefault())
1049 if (runparams.moving_arg)
1051 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1054 if (!par.params().spacing().isDefault()
1055 && (pit == 0 || !priorpar->hasSameLayout(par)))
1057 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1061 if (style.isCommand()) {
1067 // For InTitle commands, we already started the command before
1068 // the language switch
1069 if (!intitle_command)
1070 parStartCommand(par, os, runparams, style);
1072 Font const outerfont = text.outerFont(pit);
1075 os << from_utf8(everypar);
1076 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1078 Font const font = par.empty()
1079 ? par.getLayoutFont(bparams, outerfont)
1080 : par.getFont(bparams, par.size() - 1, outerfont);
1082 bool const is_command = style.isCommand();
1084 // InTitle commands need to be closed after the language has been closed.
1085 if (!intitle_command) {
1088 if (!style.postcommandargs().empty())
1089 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1090 if (runparams.encoding != prev_encoding) {
1091 runparams.encoding = prev_encoding;
1092 os << setEncoding(prev_encoding->iconvName());
1097 bool pending_newline = false;
1098 bool unskip_newline = false;
1099 bool close_lang_switch = false;
1100 switch (style.latextype) {
1101 case LATEX_ITEM_ENVIRONMENT:
1102 case LATEX_LIST_ENVIRONMENT:
1103 if ((nextpar && par_lang != nextpar_lang
1104 && nextpar->getDepth() == par.getDepth())
1105 || (atSameLastLangSwitchDepth(state) && nextpar
1106 && nextpar->getDepth() < par.getDepth()))
1107 close_lang_switch = using_begin_end;
1108 if (nextpar && par.params().depth() < nextpar->params().depth())
1109 pending_newline = true;
1111 case LATEX_ENVIRONMENT: {
1112 // if its the last paragraph of the current environment
1113 // skip it otherwise fall through
1115 && ((nextpar->layout() != par.layout()
1116 || nextpar->params().depth() != par.params().depth())
1117 || (!using_begin_end || par_lang != nextpar_lang)))
1119 close_lang_switch = using_begin_end;
1126 // we don't need it for the last paragraph and in InTitle commands!!!
1127 if (nextpar && !intitle_command)
1128 pending_newline = true;
1131 // InTitle commands use switches (not environments) for space settings
1132 if (par.allowParagraphCustomization() && !style.intitle) {
1133 if (!par.params().spacing().isDefault()
1134 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1135 if (pending_newline)
1138 string const endtag =
1139 par.params().spacing().writeEnvirEnd(useSetSpace);
1140 if (prefixIs(endtag, "\\end{"))
1143 os << from_ascii(endtag);
1144 pending_newline = true;
1148 // Closing the language is needed for the last paragraph in a given language
1149 // as well as for any InTitleCommand (since these set the language locally);
1150 // it is also needed if we're within an \L or \R that we may have opened above
1151 // (not necessarily in this paragraph) and are about to close.
1152 bool closing_rtl_ltr_environment = !using_begin_end
1154 && (par_language->lang() != "arabic_arabtex"
1155 && outer_language->lang() != "arabic_arabtex")
1156 // have we opened an \L or \R environment?
1157 && runparams.local_font != 0
1158 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1159 // are we about to close the language?
1160 &&((nextpar && par_lang != nextpar_lang)
1161 || (runparams.isLastPar && par_lang != outer_lang));
1163 if (localswitch_needed
1164 || (intitle_command && using_begin_end)
1165 || closing_rtl_ltr_environment
1166 || ((runparams.isLastPar || close_lang_switch)
1167 && (par_lang != outer_lang || (using_begin_end
1168 && style.isEnvironment()
1169 && par_lang != nextpar_lang)))) {
1170 // Since \selectlanguage write the language to the aux file,
1171 // we need to reset the language at the end of footnote or
1174 if (!localswitch && (pending_newline || close_lang_switch))
1177 // when the paragraph uses CJK, the language has to be closed earlier
1178 if ((font.language()->encoding()->package() != Encoding::CJK) || runparams_in.for_search) {
1179 if (lang_end_command.empty()) {
1180 // If this is a child, we should restore the
1181 // master language after the last paragraph.
1182 Language const * const current_language =
1183 (runparams.isLastPar && runparams.master_language)
1184 ? runparams.master_language
1186 string const current_lang = use_polyglossia
1187 ? getPolyglossiaEnvName(current_language)
1188 : current_language->babel();
1189 if (!current_lang.empty()
1190 && current_lang != openLanguageName(state)) {
1191 string bc = use_polyglossia ?
1192 getPolyglossiaBegin(lang_begin_command, current_lang,
1193 current_language->polyglossiaOpts(),
1195 : subst(lang_begin_command, "$$lang", current_lang);
1197 pending_newline = !localswitch;
1198 unskip_newline = !localswitch;
1199 if (using_begin_end)
1200 pushLanguageName(current_lang, localswitch);
1202 } else if ((!using_begin_end ||
1203 langOpenedAtThisLevel(state)) &&
1204 !par_lang.empty()) {
1205 // If we are in an environment, we have to
1206 // close the "outer" language afterwards
1207 string const & cur_lang = openLanguageName(state);
1208 if (!style.isEnvironment()
1209 || (close_lang_switch
1210 && atSameLastLangSwitchDepth(state)
1211 && par_lang != outer_lang
1212 && (par_lang != cur_lang
1213 || (cur_lang != outer_lang
1215 && style != nextpar->layout())))
1216 || (atSameLastLangSwitchDepth(state)
1217 && state->lang_switch_depth_.size()
1218 && cur_lang != par_lang)
1219 || in_polyglossia_rtl_env)
1221 if (using_begin_end && !localswitch)
1223 os << from_ascii(subst(
1227 pending_newline = !localswitch;
1228 unskip_newline = !localswitch;
1229 if (using_begin_end)
1235 if (closing_rtl_ltr_environment)
1238 // InTitle commands need to be closed after the language has been closed.
1239 if (intitle_command) {
1242 if (!style.postcommandargs().empty())
1243 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1244 if (runparams.encoding != prev_encoding) {
1245 runparams.encoding = prev_encoding;
1246 os << setEncoding(prev_encoding->iconvName());
1251 bool const last_was_separator =
1252 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1254 if (pending_newline) {
1256 // prevent unwanted whitespace
1258 if (!os.afterParbreak() && !last_was_separator)
1262 // if this is a CJK-paragraph and the next isn't, close CJK
1263 // also if the next paragraph is a multilingual environment (because of nesting)
1265 && (state->open_encoding_ == CJK && bparams.encoding().iconvName() != "UTF-8")
1266 && (nextpar_language->encoding()->package() != Encoding::CJK
1267 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1268 // inbetween environments, CJK has to be closed later (nesting!)
1269 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1270 os << "\\end{CJK}\n";
1271 state->open_encoding_ = none;
1274 // If this is the last paragraph, close the CJK environment
1275 // if necessary. If it's an environment or nested in an environment,
1276 // we'll have to \end that first.
1277 if (runparams.isLastPar && !style.isEnvironment()
1278 && par.params().depth() < 1) {
1279 switch (state->open_encoding_) {
1281 // do nothing at the end of child documents
1282 if (maintext && buf.masterBuffer() != &buf)
1284 // end of main text: also insert a \clearpage (see #5386)
1286 os << "\n\\clearpage\n\\end{CJK}\n";
1290 state->open_encoding_ = none;
1295 state->open_encoding_ = none;
1305 // If this is the last paragraph, and a local_font was set upon entering
1306 // the inset, and we're using "auto" or "default" encoding, and not
1307 // compiling with XeTeX or LuaTeX, the encoding
1308 // should be set back to that local_font's encoding.
1309 if (runparams.isLastPar && runparams_in.local_font != 0
1310 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1311 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1312 && !runparams.isFullUnicode()
1314 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1315 os << setEncoding(runparams_in.encoding->iconvName());
1317 // Otherwise, the current encoding should be set for the next paragraph.
1319 runparams_in.encoding = runparams.encoding;
1322 // we don't need a newline for the last paragraph!!!
1323 // Note from JMarc: we will re-add a \n explicitly in
1324 // TeXEnvironment, because it is needed in this case
1325 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1326 // Make sure to start a new line
1328 Layout const & next_layout = nextpar->layout();
1329 // A newline '\n' is always output before a command,
1330 // so avoid doubling it.
1331 if (!next_layout.isCommand()) {
1332 // Here we now try to avoid spurious empty lines by
1333 // outputting a paragraph break only if: (case 1) the
1334 // paragraph style allows parbreaks and no \begin, \end
1335 // or \item tags are going to follow (i.e., if the next
1336 // isn't the first or the current isn't the last
1337 // paragraph of an environment or itemize) and the
1338 // depth and alignment of the following paragraph is
1339 // unchanged, or (case 2) the following is a
1340 // non-environment paragraph whose depth is increased
1341 // but whose alignment is unchanged, or (case 3) the
1342 // paragraph is not an environment and the next one is a
1343 // non-itemize-like env at lower depth, or (case 4) the
1344 // paragraph is a command not followed by an environment
1345 // and the alignment of the current and next paragraph
1346 // is unchanged, or (case 5) the current alignment is
1347 // changed and a standard paragraph follows.
1348 DocumentClass const & tclass = bparams.documentClass();
1349 if ((style == next_layout
1350 && !style.parbreak_is_newline
1351 && !text.inset().getLayout().parbreakIsNewline()
1352 && style.latextype != LATEX_ITEM_ENVIRONMENT
1353 && style.latextype != LATEX_LIST_ENVIRONMENT
1354 && style.align == par.getAlign()
1355 && nextpar->getDepth() == par.getDepth()
1356 && nextpar->getAlign() == par.getAlign())
1357 || (!next_layout.isEnvironment()
1358 && nextpar->getDepth() > par.getDepth()
1359 && nextpar->getAlign() == par.getAlign())
1360 || (!style.isEnvironment()
1361 && next_layout.latextype == LATEX_ENVIRONMENT
1362 && nextpar->getDepth() < par.getDepth())
1363 || (style.isCommand()
1364 && !next_layout.isEnvironment()
1365 && style.align == par.getAlign()
1366 && next_layout.align == nextpar->getAlign())
1367 || (style.align != par.getAlign()
1368 && tclass.isDefaultLayout(next_layout))) {
1374 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1375 << &par << " next " << nextpar);
1381 // LaTeX all paragraphs
1382 void latexParagraphs(Buffer const & buf,
1385 OutputParams const & runparams,
1386 string const & everypar)
1388 LASSERT(runparams.par_begin <= runparams.par_end,
1389 { os << "% LaTeX Output Error\n"; return; } );
1391 BufferParams const & bparams = buf.params();
1392 BufferParams const & mparams = buf.masterParams();
1394 bool const maintext = text.isMainText();
1395 bool const is_child = buf.masterBuffer() != &buf;
1396 bool const multibib_child = maintext && is_child
1397 && mparams.multibib == "child";
1399 if (multibib_child && mparams.useBiblatex())
1400 os << "\\newrefsection";
1401 else if (multibib_child && mparams.useBibtopic()) {
1402 os << "\\begin{btUnit}\n";
1403 runparams.openbtUnit = true;
1406 // Open a CJK environment at the beginning of the main buffer
1407 // (but not in child documents or documents using system fonts)
1408 // if the document's language is a CJK language (with some exceptions)
1409 // or the document encoding is utf8-cjk:
1410 OutputState * state = getOutputState();
1411 if (maintext && !is_child && !bparams.useNonTeXFonts
1412 && ((bparams.language->encoding()->package() == Encoding::CJK
1413 && (bparams.encoding().iconvName() != "UTF-8"
1414 || bparams.encoding().name() == "utf8-cjk"
1415 || bparams.encoding().name() == "utf8" ))
1416 || (bparams.encoding().name() == "utf8-cjk"
1417 && LaTeXFeatures::isAvailable("CJKutf8")))) {
1418 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1419 ? from_ascii("UTF8") : from_ascii(bparams.encoding().latexName());
1420 os << "\\begin{CJK}{" << cjkenc
1421 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1422 state->open_encoding_ = CJK;
1424 // if "auto begin" is switched off, explicitly switch the
1425 // language on at start
1426 string const mainlang = runparams.use_polyglossia
1427 ? getPolyglossiaEnvName(bparams.language)
1428 : bparams.language->babel();
1429 string const lang_begin_command = runparams.use_polyglossia ?
1430 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1431 string const lang_end_command = runparams.use_polyglossia ?
1432 "\\end{$$lang}" : lyxrc.language_command_end;
1433 bool const using_begin_end = runparams.use_polyglossia ||
1434 !lang_end_command.empty();
1436 if (maintext && !lyxrc.language_auto_begin &&
1437 !mainlang.empty()) {
1439 string bc = runparams.use_polyglossia ?
1440 getPolyglossiaBegin(lang_begin_command, mainlang,
1441 bparams.language->polyglossiaOpts())
1442 : subst(lang_begin_command, "$$lang", mainlang);
1445 if (using_begin_end)
1446 pushLanguageName(mainlang);
1449 ParagraphList const & paragraphs = text.paragraphs();
1451 if (runparams.par_begin == runparams.par_end) {
1452 // The full doc will be exported but it is easier to just rely on
1453 // runparams range parameters that will be passed TeXEnvironment.
1454 runparams.par_begin = 0;
1455 runparams.par_end = paragraphs.size();
1458 pit_type pit = runparams.par_begin;
1459 // lastpit is for the language check after the loop.
1460 pit_type lastpit = pit;
1461 // variables used in the loop:
1462 bool was_title = false;
1463 bool already_title = false;
1464 DocumentClass const & tclass = bparams.documentClass();
1466 // Did we already warn about inTitle layout mixing? (we only warn once)
1467 bool gave_layout_warning = false;
1468 for (; pit < runparams.par_end; ++pit) {
1470 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1472 // FIXME This check should not be needed. We should
1473 // perhaps issue an error if it is.
1474 Layout const & layout = text.inset().forcePlainLayout() ?
1475 tclass.plainLayout() : par->layout();
1477 if (layout.intitle) {
1478 if (already_title) {
1479 if (!gave_layout_warning && !runparams.dryrun) {
1480 gave_layout_warning = true;
1481 frontend::Alert::warning(_("Error in latexParagraphs"),
1482 bformat(_("You are using at least one "
1483 "layout (%1$s) intended for the title, "
1484 "after using non-title layouts. This "
1485 "could lead to missing or incorrect output."
1488 } else if (!was_title) {
1490 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1492 << from_ascii(tclass.titlename())
1496 } else if (was_title && !already_title && !layout.inpreamble) {
1497 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1498 os << "\\end{" << from_ascii(tclass.titlename())
1502 os << "\\" << from_ascii(tclass.titlename())
1505 already_title = true;
1509 if (layout.isCommand() && !layout.latexname().empty()
1510 && layout.latexname() == bparams.multibib) {
1511 if (runparams.openbtUnit)
1512 os << "\\end{btUnit}\n";
1513 if (!bparams.useBiblatex()) {
1514 os << '\n' << "\\begin{btUnit}\n";
1515 runparams.openbtUnit = true;
1519 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1520 // This is a standard top level paragraph, TeX it and continue.
1521 TeXOnePar(buf, text, pit, os, runparams, everypar);
1525 TeXEnvironmentData const data =
1526 prepareEnvironment(buf, text, par, os, runparams);
1527 // pit can be changed in TeXEnvironment.
1528 TeXEnvironment(buf, text, runparams, pit, os);
1529 finishEnvironment(os, runparams, data);
1532 if (pit == runparams.par_end) {
1533 // Make sure that the last paragraph is
1534 // correctly terminated (because TeXOnePar does
1535 // not add a \n in this case)
1539 // It might be that we only have a title in this document
1540 if (was_title && !already_title) {
1541 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1542 os << "\\end{" << from_ascii(tclass.titlename())
1545 os << "\\" << from_ascii(tclass.titlename())
1550 if (maintext && !is_child && runparams.openbtUnit)
1551 os << "\\end{btUnit}\n";
1553 // if "auto end" is switched off, explicitly close the language at the end
1554 // but only if the last par is in a babel or polyglossia language
1555 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1556 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1557 os << from_utf8(subst(lang_end_command,
1561 if (using_begin_end)
1565 // If the last paragraph is an environment, we'll have to close
1566 // CJK at the very end to do proper nesting.
1567 if (maintext && !is_child && state->open_encoding_ == CJK) {
1568 os << "\\clearpage\n\\end{CJK}\n";
1569 state->open_encoding_ = none;
1571 // Likewise for polyglossia or when using begin/end commands
1572 string const & cur_lang = openLanguageName(state);
1573 if (maintext && !is_child && !cur_lang.empty()) {
1574 os << from_utf8(subst(lang_end_command,
1578 if (using_begin_end)
1582 // reset inherited encoding
1583 if (state->cjk_inherited_ > 0) {
1584 state->cjk_inherited_ -= 1;
1585 if (state->cjk_inherited_ == 0)
1586 state->open_encoding_ = CJK;
1589 if (multibib_child && mparams.useBibtopic()) {
1590 os << "\\end{btUnit}\n";
1591 runparams.openbtUnit = false;
1596 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1597 OutputParams const & runparams, Encoding const & newEnc,
1598 bool force, bool noswitchmacro)
1600 // XeTeX/LuaTeX use only one encoding per document:
1601 // * with useNonTeXFonts: "utf8plain",
1602 // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1603 // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1604 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1605 return make_pair(false, 0);
1607 Encoding const & oldEnc = *runparams.encoding;
1608 bool moving_arg = runparams.moving_arg;
1609 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc,
1610 // except if we use CJKutf8
1611 bool const from_to_cjk =
1612 ((oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1613 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK))
1614 && ((bparams.encoding().name() != "utf8-cjk" && bparams.encoding().name() != "utf8")
1615 || !LaTeXFeatures::isAvailable("CJKutf8"));
1616 if (!force && !from_to_cjk
1617 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1618 return make_pair(false, 0);
1620 // Do nothing if the encoding is unchanged.
1621 if (oldEnc.name() == newEnc.name())
1622 return make_pair(false, 0);
1624 // FIXME We ignore encoding switches from/to encodings that do
1625 // neither support the inputenc package nor the CJK package here.
1626 // This does of course only work in special cases (e.g. switch from
1627 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1628 // but it is the best we can do
1630 // 2019-01-08 Possibly no longer required since tis620-0 is supported
1631 // by inputenc (but check special encodings "utf8-plain" and "default").
1632 if (oldEnc.package() == Encoding::none || newEnc.package() == Encoding::none)
1633 return make_pair(false, 0);
1635 // change encoding (not required with UTF8)
1636 if (bparams.encoding().iconvName() != "UTF-8") {
1637 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1638 << oldEnc.name() << " to " << newEnc.name());
1639 os << setEncoding(newEnc.iconvName());
1640 if (bparams.inputenc == "default")
1641 return make_pair(true, 0);
1644 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1645 OutputState * state = getOutputState();
1646 switch (newEnc.package()) {
1647 case Encoding::none:
1648 case Encoding::japanese:
1649 // shouldn't ever reach here, see above
1650 return make_pair(true, 0);
1651 case Encoding::inputenc: {
1652 int count = inputenc_arg.length();
1653 if (oldEnc.package() == Encoding::CJK &&
1654 state->open_encoding_ == CJK) {
1656 state->open_encoding_ = none;
1659 else if (oldEnc.package() == Encoding::inputenc &&
1660 state->open_encoding_ == inputenc) {
1662 state->open_encoding_ = none;
1665 if (runparams.local_font != 0
1666 && oldEnc.package() == Encoding::CJK) {
1667 // within insets, \inputenc switches need
1668 // to be embraced within \bgroup...\egroup;
1672 state->open_encoding_ = inputenc;
1674 // with the japanese option, inputenc is omitted.
1675 if (runparams.use_japanese || noswitchmacro)
1676 return make_pair(true, count);
1677 os << "\\inputencoding{" << inputenc_arg << '}';
1678 return make_pair(true, count + 16);
1680 case Encoding::CJK: {
1681 int count = inputenc_arg.length();
1682 if (oldEnc.package() == Encoding::CJK &&
1683 state->open_encoding_ == CJK) {
1687 if (oldEnc.package() == Encoding::inputenc &&
1688 state->open_encoding_ == inputenc) {
1692 docstring const cjkenc = (bparams.encoding().iconvName() == "UTF-8"
1693 && LaTeXFeatures::isAvailable("CJKutf8"))
1694 ? from_ascii("UTF8") : from_ascii(newEnc.latexName());
1695 os << "\\begin{CJK}{" << cjkenc << "}{"
1696 << from_ascii(bparams.fonts_cjk) << "}";
1697 state->open_encoding_ = CJK;
1698 return make_pair(true, count + 15);
1701 // Dead code to avoid a warning:
1702 return make_pair(true, 0);