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';
297 // in multilingual environments, the CJK tags have to be nested properly
298 data.cjk_nested = false;
299 if (data.par_language->encoding()->package() == Encoding::CJK &&
300 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
301 if (prev_par_language->encoding()->package() == Encoding::CJK) {
302 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
303 && LaTeXFeatures::isAvailable("CJKutf8")) ?
305 : from_ascii(data.par_language->encoding()->latexName());
306 os << "\\begin{CJK}{" << cjkenc
307 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
309 state->open_encoding_ = CJK;
310 data.cjk_nested = true;
316 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
317 TeXEnvironmentData const & data)
319 OutputState * state = getOutputState();
320 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
321 if (state->open_encoding_ == CJK && data.cjk_nested) {
322 // We need to close the encoding even if it does not change
323 // to do correct environment nesting
324 os << "\\end{CJK}\n";
325 state->open_encoding_ = none;
328 if (data.style->isEnvironment()) {
330 bool const using_begin_end =
331 runparams.use_polyglossia ||
332 !lyxrc.language_command_end.empty();
333 // Close any language opened at this nest level
334 if (using_begin_end) {
335 while (langOpenedAtThisLevel(state)) {
336 if (isLocalSwitch(state)) {
340 << openLanguageName(state)
346 state->nest_level_ -= 1;
347 string const & name = data.style->latexname();
349 os << "\\end{" << from_ascii(name) << "}\n";
350 state->prev_env_language_ = data.par_language;
351 if (runparams.encoding != data.prev_encoding) {
352 runparams.encoding = data.prev_encoding;
353 os << setEncoding(data.prev_encoding->iconvName());
357 if (data.leftindent_open) {
358 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
359 state->prev_env_language_ = data.par_language;
360 if (runparams.encoding != data.prev_encoding) {
361 runparams.encoding = data.prev_encoding;
362 os << setEncoding(data.prev_encoding->iconvName());
366 // Check whether we should output a blank line after the environment
367 if (!data.style->nextnoindent)
372 void TeXEnvironment(Buffer const & buf, Text const & text,
373 OutputParams const & runparams,
374 pit_type & pit, otexstream & os)
376 ParagraphList const & paragraphs = text.paragraphs();
377 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
378 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
380 Layout const & current_layout = par->layout();
381 depth_type const current_depth = par->params().depth();
382 Length const & current_left_indent = par->params().leftIndent();
384 // This is for debugging purpose at the end.
385 pit_type const par_begin = pit;
386 for (; pit < runparams.par_end; ++pit) {
387 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
389 // check first if this is an higher depth paragraph.
390 bool go_out = (par->params().depth() < current_depth);
391 if (par->params().depth() == current_depth) {
392 // This environment is finished.
393 go_out |= (par->layout() != current_layout);
394 go_out |= (par->params().leftIndent() != current_left_indent);
397 // nothing to do here, restore pit and go out.
402 if (par->layout() == current_layout
403 && par->params().depth() == current_depth
404 && par->params().leftIndent() == current_left_indent) {
405 // We are still in the same environment so TeXOnePar and continue;
406 TeXOnePar(buf, text, pit, os, runparams);
410 // We are now in a deeper environment.
411 // Either par->layout() != current_layout
412 // Or par->params().depth() > current_depth
413 // Or par->params().leftIndent() != current_left_indent)
415 // FIXME This test should not be necessary.
416 // We should perhaps issue an error if it is.
417 bool const force_plain_layout = text.inset().forcePlainLayout();
418 Layout const & style = force_plain_layout
419 ? buf.params().documentClass().plainLayout()
422 if (!style.isEnvironment()) {
423 // This is a standard paragraph, no need to call TeXEnvironment.
424 TeXOnePar(buf, text, pit, os, runparams);
428 // This is a new environment.
429 TeXEnvironmentData const data =
430 prepareEnvironment(buf, text, par, os, runparams);
431 // Recursive call to TeXEnvironment!
432 TeXEnvironment(buf, text, runparams, pit, os);
433 finishEnvironment(os, runparams, data);
436 if (pit != runparams.par_end)
437 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
441 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
442 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
444 unsigned int const argnr = latexargs.size();
448 // Default and preset args are always output, so if they require
449 // other arguments, consider this.
450 Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
451 Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
452 for (; lit != lend; ++lit) {
453 Layout::latexarg arg = (*lit).second;
454 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
455 vector<string> req = getVectorFromString(arg.requires);
456 required.insert(required.end(), req.begin(), req.end());
460 for (unsigned int i = 1; i <= argnr; ++i) {
461 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
462 bool inserted = false;
463 if (lit != ilist.end()) {
464 InsetArgument const * ins = (*lit).second;
466 Layout::LaTeXArgMap::const_iterator const lait =
467 latexargs.find(ins->name());
468 if (lait != latexargs.end()) {
469 Layout::latexarg arg = (*lait).second;
470 docstring ldelim = arg.mandatory ?
471 from_ascii("{") : from_ascii("[");
472 docstring rdelim = arg.mandatory ?
473 from_ascii("}") : from_ascii("]");
474 if (!arg.ldelim.empty())
476 if (!arg.rdelim.empty())
478 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
484 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
485 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
486 for (; lait != laend; ++lait) {
487 string const name = prefix + convert<string>(i);
488 if ((*lait).first == name) {
489 Layout::latexarg arg = (*lait).second;
490 docstring preset = arg.presetarg;
491 if (!arg.defaultarg.empty()) {
494 preset += arg.defaultarg;
497 docstring ldelim = arg.ldelim.empty() ?
498 from_ascii("{") : arg.ldelim;
499 docstring rdelim = arg.rdelim.empty() ?
500 from_ascii("}") : arg.rdelim;
501 os << ldelim << preset << rdelim;
502 } else if (!preset.empty()) {
503 docstring ldelim = arg.ldelim.empty() ?
504 from_ascii("[") : arg.ldelim;
505 docstring rdelim = arg.rdelim.empty() ?
506 from_ascii("]") : arg.rdelim;
507 os << ldelim << preset << rdelim;
508 } else if (find(required.begin(), required.end(),
509 (*lait).first) != required.end()) {
510 docstring ldelim = arg.ldelim.empty() ?
511 from_ascii("[") : arg.ldelim;
512 docstring rdelim = arg.rdelim.empty() ?
513 from_ascii("]") : arg.rdelim;
514 os << ldelim << rdelim;
527 void pushLanguageName(string const & lang_name, bool localswitch)
529 OutputState * state = getOutputState();
531 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
532 state->lang_switch_depth_.push(nest_level);
533 state->open_polyglossia_lang_.push(lang_name);
537 void popLanguageName()
539 OutputState * state = getOutputState();
541 state->lang_switch_depth_.pop();
542 state->open_polyglossia_lang_.pop();
546 string const & openLanguageName()
548 OutputState * state = getOutputState();
550 return openLanguageName(state);
556 void addArgInsets(Paragraph const & par, string const & prefix,
557 Layout::LaTeXArgMap const & latexargs,
558 map<int, InsetArgument const *> & ilist,
559 vector<string> & required)
561 for (auto const & table : par.insetList()) {
562 InsetArgument const * arg = table.inset->asInsetArgument();
565 if (arg->name().empty()) {
566 LYXERR0("Error: Unnamed argument inset!");
569 string const name = prefix.empty() ?
570 arg->name() : split(arg->name(), ':');
571 // why converting into an integer?
572 unsigned int const nr = convert<unsigned int>(name);
573 if (ilist.find(nr) == ilist.end())
575 Layout::LaTeXArgMap::const_iterator const lit =
576 latexargs.find(arg->name());
577 if (lit != latexargs.end()) {
578 Layout::latexarg const & larg = lit->second;
579 vector<string> req = getVectorFromString(larg.requires);
580 move(req.begin(), req.end(), back_inserter(required));
588 void latexArgInsets(Paragraph const & par, otexstream & os,
589 OutputParams const & runparams,
590 Layout::LaTeXArgMap const & latexargs,
591 string const & prefix)
593 map<int, InsetArgument const *> ilist;
594 vector<string> required;
595 addArgInsets(par, prefix, latexargs, ilist, required);
596 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
600 void latexArgInsets(ParagraphList const & pars,
601 ParagraphList::const_iterator pit,
602 otexstream & os, OutputParams const & runparams,
603 Layout::LaTeXArgMap const & latexargs,
604 string const & prefix)
606 map<int, InsetArgument const *> ilist;
607 vector<string> required;
609 depth_type const current_depth = pit->params().depth();
610 Layout const current_layout = pit->layout();
612 // get the first paragraph in sequence with this layout and depth
615 if (lyx::prev(pit, offset) == pars.begin())
617 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
618 if (priorpit->layout() == current_layout
619 && priorpit->params().depth() == current_depth)
625 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
627 for (; spit != pars.end(); ++spit) {
628 if (spit->layout() != current_layout ||
629 spit->params().depth() < current_depth)
631 if (spit->params().depth() > current_depth)
633 addArgInsets(*spit, prefix, latexargs, ilist, required);
635 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
639 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
640 OutputParams const & runparams,
641 Layout::LaTeXArgMap const & latexargs,
642 string const & prefix)
644 map<int, InsetArgument const *> ilist;
645 vector<string> required;
647 for (Paragraph const & par : pars) {
648 if (par.layout().hasArgs())
649 // The InsetArguments inside this paragraph refer to this paragraph
651 addArgInsets(par, prefix, latexargs, ilist, required);
653 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
659 // output the proper paragraph start according to latextype.
660 void parStartCommand(Paragraph const & par, otexstream & os,
661 OutputParams const & runparams, Layout const & style)
663 switch (style.latextype) {
665 os << '\\' << from_ascii(style.latexname());
668 if (!style.latexargs().empty())
669 latexArgInsets(par, os, runparams, style.latexargs());
670 os << from_ascii(style.latexparam());
672 case LATEX_ITEM_ENVIRONMENT:
673 case LATEX_LIST_ENVIRONMENT:
674 os << "\\" + style.itemcommand();
676 if (!style.itemargs().empty())
677 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
680 case LATEX_BIB_ENVIRONMENT:
681 // ignore this, the inset will write itself
690 // FIXME: this should be anonymous
691 void TeXOnePar(Buffer const & buf,
695 OutputParams const & runparams_in,
696 string const & everypar,
697 int start_pos, int end_pos,
700 BufferParams const & bparams = runparams_in.is_child
701 ? buf.masterParams() : buf.params();
702 ParagraphList const & paragraphs = text.paragraphs();
703 Paragraph const & par = paragraphs.at(pit);
704 // FIXME This check should not really be needed.
705 // Perhaps we should issue an error if it is.
706 Layout const & style = text.inset().forcePlainLayout() ?
707 bparams.documentClass().plainLayout() : par.layout();
709 if (style.inpreamble && !force)
712 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
715 OutputParams runparams = runparams_in;
716 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
717 // We reinitialze par begin and end to be on the safe side
718 // with embedded inset as we don't know if they set those
720 runparams.par_begin = 0;
721 runparams.par_end = 0;
723 bool const maintext = text.isMainText();
724 // we are at the beginning of an inset and CJK is already open;
725 // we count inheritation levels to get the inset nesting right.
726 OutputState * state = getOutputState();
727 if (pit == 0 && !maintext
728 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
729 state->cjk_inherited_ += 1;
730 state->open_encoding_ = none;
733 if (text.inset().isPassThru()) {
734 Font const outerfont = text.outerFont(pit);
736 // No newline before first paragraph in this lyxtext
739 if (!text.inset().getLayout().parbreakIsNewline())
743 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
747 Paragraph const * nextpar = runparams.isLastPar
748 ? 0 : ¶graphs.at(pit + 1);
750 bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
752 if (style.pass_thru) {
753 Font const outerfont = text.outerFont(pit);
754 parStartCommand(par, os, runparams, style);
758 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
760 // I did not create a parEndCommand for this minuscule
761 // task because in the other user of parStartCommand
762 // the code is different (JMarc)
763 if (style.isCommand())
767 if (!style.parbreak_is_newline) {
769 } else if (nextpar && !style.isEnvironment()) {
770 Layout const nextstyle = text.inset().forcePlainLayout()
771 ? bparams.documentClass().plainLayout()
773 if (nextstyle.name() != style.name())
780 // This paragraph's language
781 Language const * const par_language = par.getParLanguage(bparams);
782 Language const * const nextpar_language = nextpar ?
783 nextpar->getParLanguage(bparams) : 0;
784 // The document's language
785 Language const * const doc_language = bparams.language;
786 // The language that was in effect when the environment this paragraph is
787 // inside of was opened
788 Language const * const outer_language =
789 (runparams.local_font != 0) ?
790 runparams.local_font->language() : doc_language;
792 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
794 // The previous language that was in effect is the language of the
795 // previous paragraph, unless the previous paragraph is inside an
796 // environment with nesting depth greater than (or equal to, but with
797 // a different layout) the current one. If there is no previous
798 // paragraph, the previous language is the outer language.
799 // Note further that we take the outer language also if the prior par
800 // is PassThru, since in that case it has latex_language, and all secondary
801 // languages have been closed (#10793).
802 bool const use_prev_env_language = state->prev_env_language_ != 0
804 && priorpar->layout().isEnvironment()
805 && (priorpar->getDepth() > par.getDepth()
806 || (priorpar->getDepth() == par.getDepth()
807 && priorpar->layout() != par.layout()));
808 Language const * const prev_language =
809 (priorpar && !priorpar->isPassThru())
810 ? (use_prev_env_language ? state->prev_env_language_
811 : priorpar->getParLanguage(bparams))
814 bool const use_polyglossia = runparams.use_polyglossia;
815 string const par_lang = use_polyglossia ?
816 getPolyglossiaEnvName(par_language): par_language->babel();
817 string const prev_lang = use_polyglossia ?
818 getPolyglossiaEnvName(prev_language) : prev_language->babel();
819 string const outer_lang = use_polyglossia ?
820 getPolyglossiaEnvName(outer_language) : outer_language->babel();
821 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
822 getPolyglossiaEnvName(nextpar_language) :
823 nextpar_language->babel()) : string();
824 string lang_begin_command = use_polyglossia ?
825 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
826 string lang_end_command = use_polyglossia ?
827 "\\end{$$lang}" : lyxrc.language_command_end;
828 // the '%' is necessary to prevent unwanted whitespace
829 string lang_command_termination = "%\n";
830 bool const using_begin_end = use_polyglossia ||
831 !lang_end_command.empty();
833 // For InTitle commands, we need to switch the language inside the command
834 // (see #10849); thus open the command here.
835 if (intitle_command) {
836 parStartCommand(par, os, runparams, style);
840 // In some insets (such as Arguments), we cannot use \selectlanguage.
841 // Also, if an RTL language is set via environment in polyglossia,
842 // only a nested \\text<lang> command will reset the direction for LTR
843 // languages (see # 10111).
844 bool const in_polyglossia_rtl_env =
846 && runparams.local_font != 0
847 && outer_language->rightToLeft()
848 && !par_language->rightToLeft();
849 bool const localswitch = text.inset().forceLocalFontSwitch()
850 || (using_begin_end && text.inset().forcePlainLayout())
851 || in_polyglossia_rtl_env;
853 lang_begin_command = use_polyglossia ?
854 "\\text$$lang$$opts{" : lyxrc.language_command_local;
855 lang_end_command = "}";
856 lang_command_termination.clear();
859 bool const localswitch_needed = localswitch && par_lang != outer_lang;
861 // localswitches need to be closed and reopened at each par
862 if ((par_lang != prev_lang || localswitch_needed)
863 // check if we already put language command in TeXEnvironment()
864 && !(style.isEnvironment()
865 && (pit == 0 || (priorpar->layout() != par.layout()
866 && priorpar->getDepth() <= par.getDepth())
867 || priorpar->getDepth() < par.getDepth()))) {
869 && (!using_begin_end || langOpenedAtThisLevel(state))
870 && !lang_end_command.empty()
871 && prev_lang != outer_lang
872 && !prev_lang.empty()
873 && (!using_begin_end || !style.isEnvironment())) {
874 os << from_ascii(subst(lang_end_command,
877 << lang_command_termination;
882 // We need to open a new language if we couldn't close the previous
883 // one (because there's no language_command_end); and even if we closed
884 // the previous one, if the current language is different than the
885 // outer_language (which is currently in effect once the previous one
887 if ((lang_end_command.empty() || par_lang != outer_lang
889 || (style.isEnvironment() && par_lang != prev_lang)))
890 && !par_lang.empty()) {
891 // If we're inside an inset, and that inset is within an \L or \R
892 // (or equivalents), then within the inset, too, any opposite
893 // language paragraph should appear within an \L or \R (in addition
894 // to, outside of, the normal language switch commands).
895 // This behavior is not correct for ArabTeX, though.
898 && par_language->lang() != "arabic_arabtex"
899 && outer_language->lang() != "arabic_arabtex"
900 // are we in an inset?
901 && runparams.local_font != 0
902 // is the inset within an \L or \R?
904 // FIXME: currently, we don't check this; this means that
905 // we'll have unnnecessary \L and \R commands, but that
906 // doesn't seem to hurt (though latex will complain)
908 // is this paragraph in the opposite direction?
909 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
910 // FIXME: I don't have a working copy of the Arabi package, so
911 // I'm not sure if the farsi and arabic_arabi stuff is correct
913 if (par_language->lang() == "farsi")
915 else if (outer_language->lang() == "farsi")
917 else if (par_language->lang() == "arabic_arabi")
919 else if (outer_language->lang() == "arabic_arabi")
921 // remaining RTL languages currently is hebrew
922 else if (par_language->rightToLeft())
927 // With CJK, the CJK tag has to be closed first (see below)
928 if (runparams.encoding->package() != Encoding::CJK
929 && (par_lang != openLanguageName(state) || localswitch)
930 && !par_lang.empty()) {
931 string bc = use_polyglossia ?
932 getPolyglossiaBegin(lang_begin_command, par_lang,
933 par_language->polyglossiaOpts(),
935 : subst(lang_begin_command, "$$lang", par_lang);
937 os << lang_command_termination;
939 pushLanguageName(par_lang, localswitch);
944 // Switch file encoding if necessary; no need to do this for "default"
945 // encoding, since this only affects the position of the outputted
946 // \inputencoding command; the encoding switch will occur when necessary
947 if (bparams.inputenc == "auto"
948 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
949 && runparams.encoding->package() != Encoding::none) {
950 // Look ahead for future encoding changes.
951 // We try to output them at the beginning of the paragraph,
952 // since the \inputencoding command is not allowed e.g. in
953 // sections. For this reason we only set runparams.moving_arg
954 // after checking for the encoding change, otherwise the
955 // change would be always avoided by switchEncoding().
956 for (pos_type i = 0; i < par.size(); ++i) {
957 char_type const c = par.getChar(i);
958 Encoding const * const encoding =
959 par.getFontSettings(bparams, i).language()->encoding();
960 if (encoding->package() != Encoding::CJK
961 && runparams.encoding->package() == Encoding::inputenc
966 // All characters before c are in the ASCII range, and
967 // c is non-ASCII (but no inset), so change the
968 // encoding to that required by the language of c.
969 // With CJK, only add switch if we have CJK content at the beginning
971 if (i != 0 && encoding->package() == Encoding::CJK)
974 pair<bool, int> enc_switch = switchEncoding(os.os(),
975 bparams, runparams, *encoding);
976 // the following is necessary after a CJK environment in a multilingual
977 // context (nesting issue).
978 if (par_language->encoding()->package() == Encoding::CJK
979 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
980 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
981 && LaTeXFeatures::isAvailable("CJKutf8")) ?
983 : from_ascii(par_language->encoding()->latexName());
984 os << "\\begin{CJK}{" << cjkenc
985 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
986 state->open_encoding_ = CJK;
988 if (encoding->package() != Encoding::none && enc_switch.first) {
989 if (enc_switch.second > 0) {
990 // the '%' is necessary to prevent unwanted whitespace
993 // With CJK, the CJK tag had to be closed first (see above)
994 if (runparams.encoding->package() == Encoding::CJK
995 && par_lang != openLanguageName(state)
996 && !par_lang.empty()) {
997 string bc = use_polyglossia ?
998 getPolyglossiaBegin(lang_begin_command, par_lang,
999 par_language->polyglossiaOpts(),
1001 : subst(lang_begin_command, "$$lang", par_lang);
1003 << lang_command_termination;
1004 if (using_begin_end)
1005 pushLanguageName(par_lang, localswitch);
1007 runparams.encoding = encoding;
1013 runparams.moving_arg |= style.needprotect;
1014 Encoding const * const prev_encoding = runparams.encoding;
1016 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1017 if (par.allowParagraphCustomization()) {
1018 if (par.params().startOfAppendix()) {
1019 os << "\n\\appendix\n";
1022 // InTitle commands must use switches (not environments)
1023 // inside the commands (see #9332)
1024 if (style.intitle) {
1025 if (!par.params().spacing().isDefault())
1027 if (runparams.moving_arg)
1029 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1032 if (!par.params().spacing().isDefault()
1033 && (pit == 0 || !priorpar->hasSameLayout(par)))
1035 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1039 if (style.isCommand()) {
1045 // For InTitle commands, we already started the command before
1046 // the language switch
1047 if (!intitle_command)
1048 parStartCommand(par, os, runparams, style);
1050 Font const outerfont = text.outerFont(pit);
1053 os << from_utf8(everypar);
1054 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1056 Font const font = par.empty()
1057 ? par.getLayoutFont(bparams, outerfont)
1058 : par.getFont(bparams, par.size() - 1, outerfont);
1060 bool const is_command = style.isCommand();
1062 // InTitle commands need to be closed after the language has been closed.
1063 if (!intitle_command) {
1066 if (!style.postcommandargs().empty())
1067 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1068 if (runparams.encoding != prev_encoding) {
1069 runparams.encoding = prev_encoding;
1070 os << setEncoding(prev_encoding->iconvName());
1075 bool pending_newline = false;
1076 bool unskip_newline = false;
1077 bool close_lang_switch = false;
1078 switch (style.latextype) {
1079 case LATEX_ITEM_ENVIRONMENT:
1080 case LATEX_LIST_ENVIRONMENT:
1081 if ((nextpar && par_lang != nextpar_lang
1082 && nextpar->getDepth() == par.getDepth())
1083 || (atSameLastLangSwitchDepth(state) && nextpar
1084 && nextpar->getDepth() < par.getDepth()))
1085 close_lang_switch = using_begin_end;
1086 if (nextpar && par.params().depth() < nextpar->params().depth())
1087 pending_newline = true;
1089 case LATEX_ENVIRONMENT: {
1090 // if its the last paragraph of the current environment
1091 // skip it otherwise fall through
1093 && ((nextpar->layout() != par.layout()
1094 || nextpar->params().depth() != par.params().depth())
1095 || (!using_begin_end || par_lang != nextpar_lang)))
1097 close_lang_switch = using_begin_end;
1104 // we don't need it for the last paragraph and in InTitle commands!!!
1105 if (nextpar && !intitle_command)
1106 pending_newline = true;
1109 // InTitle commands use switches (not environments) for space settings
1110 if (par.allowParagraphCustomization() && !style.intitle) {
1111 if (!par.params().spacing().isDefault()
1112 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1113 if (pending_newline)
1116 string const endtag =
1117 par.params().spacing().writeEnvirEnd(useSetSpace);
1118 if (prefixIs(endtag, "\\end{"))
1121 os << from_ascii(endtag);
1122 pending_newline = true;
1126 // Closing the language is needed for the last paragraph in a given language
1127 // as well as for any InTitleCommand (since these set the language locally);
1128 // it is also needed if we're within an \L or \R that we may have opened above
1129 // (not necessarily in this paragraph) and are about to close.
1130 bool closing_rtl_ltr_environment = !using_begin_end
1132 && (par_language->lang() != "arabic_arabtex"
1133 && outer_language->lang() != "arabic_arabtex")
1134 // have we opened an \L or \R environment?
1135 && runparams.local_font != 0
1136 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1137 // are we about to close the language?
1138 &&((nextpar && par_lang != nextpar_lang)
1139 || (runparams.isLastPar && par_lang != outer_lang));
1141 if (localswitch_needed
1142 || (intitle_command && using_begin_end)
1143 || closing_rtl_ltr_environment
1144 || ((runparams.isLastPar || close_lang_switch)
1145 && (par_lang != outer_lang || (using_begin_end
1146 && style.isEnvironment()
1147 && par_lang != nextpar_lang)))) {
1148 // Since \selectlanguage write the language to the aux file,
1149 // we need to reset the language at the end of footnote or
1152 if (!localswitch && (pending_newline || close_lang_switch))
1155 // when the paragraph uses CJK, the language has to be closed earlier
1156 if (font.language()->encoding()->package() != Encoding::CJK) {
1157 if (lang_end_command.empty()) {
1158 // If this is a child, we should restore the
1159 // master language after the last paragraph.
1160 Language const * const current_language =
1161 (runparams.isLastPar && runparams.master_language)
1162 ? runparams.master_language
1164 string const current_lang = use_polyglossia
1165 ? getPolyglossiaEnvName(current_language)
1166 : current_language->babel();
1167 if (!current_lang.empty()
1168 && current_lang != openLanguageName(state)) {
1169 string bc = use_polyglossia ?
1170 getPolyglossiaBegin(lang_begin_command, current_lang,
1171 current_language->polyglossiaOpts(),
1173 : subst(lang_begin_command, "$$lang", current_lang);
1175 pending_newline = !localswitch;
1176 unskip_newline = !localswitch;
1177 if (using_begin_end)
1178 pushLanguageName(current_lang, localswitch);
1180 } else if ((!using_begin_end ||
1181 langOpenedAtThisLevel(state)) &&
1182 !par_lang.empty()) {
1183 // If we are in an environment, we have to
1184 // close the "outer" language afterwards
1185 string const & cur_lang = openLanguageName(state);
1186 if (!style.isEnvironment()
1187 || (close_lang_switch
1188 && atSameLastLangSwitchDepth(state)
1189 && par_lang != outer_lang
1190 && (par_lang != cur_lang
1191 || (cur_lang != outer_lang
1193 && style != nextpar->layout())))
1194 || (atSameLastLangSwitchDepth(state)
1195 && state->lang_switch_depth_.size()
1196 && cur_lang != par_lang)
1197 || in_polyglossia_rtl_env)
1199 if (using_begin_end && !localswitch)
1201 os << from_ascii(subst(
1205 pending_newline = !localswitch;
1206 unskip_newline = !localswitch;
1207 if (using_begin_end)
1213 if (closing_rtl_ltr_environment)
1216 // InTitle commands need to be closed after the language has been closed.
1217 if (intitle_command) {
1220 if (!style.postcommandargs().empty())
1221 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1222 if (runparams.encoding != prev_encoding) {
1223 runparams.encoding = prev_encoding;
1224 os << setEncoding(prev_encoding->iconvName());
1229 bool const last_was_separator =
1230 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1232 if (pending_newline) {
1234 // prevent unwanted whitespace
1236 if (!os.afterParbreak() && !last_was_separator)
1240 // if this is a CJK-paragraph and the next isn't, close CJK
1241 // also if the next paragraph is a multilingual environment (because of nesting)
1243 && state->open_encoding_ == CJK
1244 && (nextpar_language->encoding()->package() != Encoding::CJK
1245 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1246 // inbetween environments, CJK has to be closed later (nesting!)
1247 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1248 os << "\\end{CJK}\n";
1249 state->open_encoding_ = none;
1252 // If this is the last paragraph, close the CJK environment
1253 // if necessary. If it's an environment, we'll have to \end that first.
1254 if (runparams.isLastPar && !style.isEnvironment()) {
1255 switch (state->open_encoding_) {
1257 // do nothing at the end of child documents
1258 if (maintext && buf.masterBuffer() != &buf)
1262 os << "\n\\end{CJK}\n";
1266 state->open_encoding_ = none;
1271 state->open_encoding_ = none;
1281 // If this is the last paragraph, and a local_font was set upon entering
1282 // the inset, and we're using "auto" or "default" encoding, and not
1283 // compiling with XeTeX or LuaTeX, the encoding
1284 // should be set back to that local_font's encoding.
1285 if (runparams.isLastPar && runparams_in.local_font != 0
1286 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1287 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1288 && !runparams.isFullUnicode()
1290 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1291 os << setEncoding(runparams_in.encoding->iconvName());
1293 // Otherwise, the current encoding should be set for the next paragraph.
1295 runparams_in.encoding = runparams.encoding;
1298 // we don't need a newline for the last paragraph!!!
1299 // Note from JMarc: we will re-add a \n explicitly in
1300 // TeXEnvironment, because it is needed in this case
1301 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1302 // Make sure to start a new line
1304 Layout const & next_layout = nextpar->layout();
1305 // A newline '\n' is always output before a command,
1306 // so avoid doubling it.
1307 if (!next_layout.isCommand()) {
1308 // Here we now try to avoid spurious empty lines by
1309 // outputting a paragraph break only if: (case 1) the
1310 // paragraph style allows parbreaks and no \begin, \end
1311 // or \item tags are going to follow (i.e., if the next
1312 // isn't the first or the current isn't the last
1313 // paragraph of an environment or itemize) and the
1314 // depth and alignment of the following paragraph is
1315 // unchanged, or (case 2) the following is a
1316 // non-environment paragraph whose depth is increased
1317 // but whose alignment is unchanged, or (case 3) the
1318 // paragraph is not an environment and the next one is a
1319 // non-itemize-like env at lower depth, or (case 4) the
1320 // paragraph is a command not followed by an environment
1321 // and the alignment of the current and next paragraph
1322 // is unchanged, or (case 5) the current alignment is
1323 // changed and a standard paragraph follows.
1324 DocumentClass const & tclass = bparams.documentClass();
1325 if ((style == next_layout
1326 && !style.parbreak_is_newline
1327 && !text.inset().getLayout().parbreakIsNewline()
1328 && style.latextype != LATEX_ITEM_ENVIRONMENT
1329 && style.latextype != LATEX_LIST_ENVIRONMENT
1330 && style.align == par.getAlign()
1331 && nextpar->getDepth() == par.getDepth()
1332 && nextpar->getAlign() == par.getAlign())
1333 || (!next_layout.isEnvironment()
1334 && nextpar->getDepth() > par.getDepth()
1335 && nextpar->getAlign() == par.getAlign())
1336 || (!style.isEnvironment()
1337 && next_layout.latextype == LATEX_ENVIRONMENT
1338 && nextpar->getDepth() < par.getDepth())
1339 || (style.isCommand()
1340 && !next_layout.isEnvironment()
1341 && style.align == par.getAlign()
1342 && next_layout.align == nextpar->getAlign())
1343 || (style.align != par.getAlign()
1344 && tclass.isDefaultLayout(next_layout))) {
1350 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1351 << &par << " next " << nextpar);
1357 // LaTeX all paragraphs
1358 void latexParagraphs(Buffer const & buf,
1361 OutputParams const & runparams,
1362 string const & everypar)
1364 LASSERT(runparams.par_begin <= runparams.par_end,
1365 { os << "% LaTeX Output Error\n"; return; } );
1367 BufferParams const & bparams = buf.params();
1368 BufferParams const & mparams = buf.masterParams();
1370 bool const maintext = text.isMainText();
1371 bool const is_child = buf.masterBuffer() != &buf;
1372 bool const multibib_child = maintext && is_child
1373 && mparams.multibib == "child";
1375 if (multibib_child && mparams.useBiblatex())
1376 os << "\\newrefsection";
1377 else if (multibib_child && mparams.useBibtopic()) {
1378 os << "\\begin{btUnit}\n";
1379 runparams.openbtUnit = true;
1382 // Open a CJK environment at the beginning of the main buffer
1383 // if the document's language is a CJK language
1384 // (but not in child documents)
1385 OutputState * state = getOutputState();
1386 if (maintext && !is_child && !bparams.useNonTeXFonts
1387 && bparams.language->encoding()->package() == Encoding::CJK
1388 && (bparams.encoding().name() == "utf8-cjk"
1389 || bparams.encoding().iconvName() != "UTF-8")) {
1390 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1391 && LaTeXFeatures::isAvailable("CJKutf8")) ?
1393 : from_ascii(bparams.encoding().latexName());
1394 os << "\\begin{CJK}{" << cjkenc
1395 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1396 state->open_encoding_ = CJK;
1398 // if "auto begin" is switched off, explicitly switch the
1399 // language on at start
1400 string const mainlang = runparams.use_polyglossia
1401 ? getPolyglossiaEnvName(bparams.language)
1402 : bparams.language->babel();
1403 string const lang_begin_command = runparams.use_polyglossia ?
1404 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1405 string const lang_end_command = runparams.use_polyglossia ?
1406 "\\end{$$lang}" : lyxrc.language_command_end;
1407 bool const using_begin_end = runparams.use_polyglossia ||
1408 !lang_end_command.empty();
1410 if (maintext && !lyxrc.language_auto_begin &&
1411 !mainlang.empty()) {
1413 string bc = runparams.use_polyglossia ?
1414 getPolyglossiaBegin(lang_begin_command, mainlang,
1415 bparams.language->polyglossiaOpts())
1416 : subst(lang_begin_command, "$$lang", mainlang);
1419 if (using_begin_end)
1420 pushLanguageName(mainlang);
1423 ParagraphList const & paragraphs = text.paragraphs();
1425 if (runparams.par_begin == runparams.par_end) {
1426 // The full doc will be exported but it is easier to just rely on
1427 // runparams range parameters that will be passed TeXEnvironment.
1428 runparams.par_begin = 0;
1429 runparams.par_end = paragraphs.size();
1432 pit_type pit = runparams.par_begin;
1433 // lastpit is for the language check after the loop.
1434 pit_type lastpit = pit;
1435 // variables used in the loop:
1436 bool was_title = false;
1437 bool already_title = false;
1438 DocumentClass const & tclass = bparams.documentClass();
1440 // Did we already warn about inTitle layout mixing? (we only warn once)
1441 bool gave_layout_warning = false;
1442 for (; pit < runparams.par_end; ++pit) {
1444 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1446 // FIXME This check should not be needed. We should
1447 // perhaps issue an error if it is.
1448 Layout const & layout = text.inset().forcePlainLayout() ?
1449 tclass.plainLayout() : par->layout();
1451 if (layout.intitle) {
1452 if (already_title) {
1453 if (!gave_layout_warning && !runparams.dryrun) {
1454 gave_layout_warning = true;
1455 frontend::Alert::warning(_("Error in latexParagraphs"),
1456 bformat(_("You are using at least one "
1457 "layout (%1$s) intended for the title, "
1458 "after using non-title layouts. This "
1459 "could lead to missing or incorrect output."
1462 } else if (!was_title) {
1464 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1466 << from_ascii(tclass.titlename())
1470 } else if (was_title && !already_title && !layout.inpreamble) {
1471 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1472 os << "\\end{" << from_ascii(tclass.titlename())
1476 os << "\\" << from_ascii(tclass.titlename())
1479 already_title = true;
1483 if (layout.isCommand() && !layout.latexname().empty()
1484 && layout.latexname() == bparams.multibib) {
1485 if (runparams.openbtUnit)
1486 os << "\\end{btUnit}\n";
1487 if (!bparams.useBiblatex()) {
1488 os << '\n' << "\\begin{btUnit}\n";
1489 runparams.openbtUnit = true;
1493 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1494 // This is a standard top level paragraph, TeX it and continue.
1495 TeXOnePar(buf, text, pit, os, runparams, everypar);
1499 TeXEnvironmentData const data =
1500 prepareEnvironment(buf, text, par, os, runparams);
1501 // pit can be changed in TeXEnvironment.
1502 TeXEnvironment(buf, text, runparams, pit, os);
1503 finishEnvironment(os, runparams, data);
1506 if (pit == runparams.par_end) {
1507 // Make sure that the last paragraph is
1508 // correctly terminated (because TeXOnePar does
1509 // not add a \n in this case)
1513 // It might be that we only have a title in this document
1514 if (was_title && !already_title) {
1515 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1516 os << "\\end{" << from_ascii(tclass.titlename())
1519 os << "\\" << from_ascii(tclass.titlename())
1524 if (maintext && !is_child && runparams.openbtUnit)
1525 os << "\\end{btUnit}\n";
1527 // if "auto end" is switched off, explicitly close the language at the end
1528 // but only if the last par is in a babel or polyglossia language
1529 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1530 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1531 os << from_utf8(subst(lang_end_command,
1535 if (using_begin_end)
1539 // If the last paragraph is an environment, we'll have to close
1540 // CJK at the very end to do proper nesting.
1541 if (maintext && !is_child && state->open_encoding_ == CJK) {
1542 os << "\\end{CJK}\n";
1543 state->open_encoding_ = none;
1545 // Likewise for polyglossia or when using begin/end commands
1546 string const & cur_lang = openLanguageName(state);
1547 if (maintext && !is_child && !cur_lang.empty()) {
1548 os << from_utf8(subst(lang_end_command,
1552 if (using_begin_end)
1556 // reset inherited encoding
1557 if (state->cjk_inherited_ > 0) {
1558 state->cjk_inherited_ -= 1;
1559 if (state->cjk_inherited_ == 0)
1560 state->open_encoding_ = CJK;
1563 if (multibib_child && mparams.useBibtopic()) {
1564 os << "\\end{btUnit}\n";
1565 runparams.openbtUnit = false;
1570 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1571 OutputParams const & runparams, Encoding const & newEnc,
1574 // XeTeX/LuaTeX use only one encoding per document:
1575 // * with useNonTeXFonts: "utf8plain",
1576 // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1577 // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1578 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1579 return make_pair(false, 0);
1581 Encoding const & oldEnc = *runparams.encoding;
1582 bool moving_arg = runparams.moving_arg;
1583 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc,
1584 // except if we use CJKutf8
1585 bool const from_to_cjk =
1586 ((oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1587 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK))
1588 && (bparams.encoding().name() != "utf8-cjk" || !LaTeXFeatures::isAvailable("CJKutf8"));
1589 if (!force && !from_to_cjk
1590 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1591 return make_pair(false, 0);
1593 // Do nothing if the encoding is unchanged.
1594 if (oldEnc.name() == newEnc.name())
1595 return make_pair(false, 0);
1597 // FIXME We ignore encoding switches from/to encodings that do
1598 // neither support the inputenc package nor the CJK package here.
1599 // This does of course only work in special cases (e.g. switch from
1600 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1601 // but it is the best we can do
1602 if (oldEnc.package() == Encoding::none
1603 || newEnc.package() == Encoding::none)
1604 return make_pair(false, 0);
1606 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1607 << oldEnc.name() << " to " << newEnc.name());
1608 os << setEncoding(newEnc.iconvName());
1609 if (bparams.inputenc == "default")
1610 return make_pair(true, 0);
1612 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1613 OutputState * state = getOutputState();
1614 switch (newEnc.package()) {
1615 case Encoding::none:
1616 case Encoding::japanese:
1617 // shouldn't ever reach here, see above
1618 return make_pair(true, 0);
1619 case Encoding::inputenc: {
1620 int count = inputenc_arg.length();
1621 if (oldEnc.package() == Encoding::CJK &&
1622 state->open_encoding_ == CJK) {
1624 state->open_encoding_ = none;
1627 else if (oldEnc.package() == Encoding::inputenc &&
1628 state->open_encoding_ == inputenc) {
1630 state->open_encoding_ = none;
1633 if (runparams.local_font != 0
1634 && oldEnc.package() == Encoding::CJK) {
1635 // within insets, \inputenc switches need
1636 // to be embraced within \bgroup...\egroup;
1640 state->open_encoding_ = inputenc;
1642 // with the japanese option, inputenc is omitted.
1643 if (runparams.use_japanese)
1644 return make_pair(true, count);
1645 os << "\\inputencoding{" << inputenc_arg << '}';
1646 return make_pair(true, count + 16);
1648 case Encoding::CJK: {
1649 int count = inputenc_arg.length();
1650 if (oldEnc.package() == Encoding::CJK &&
1651 state->open_encoding_ == CJK) {
1655 if (oldEnc.package() == Encoding::inputenc &&
1656 state->open_encoding_ == inputenc) {
1660 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1661 && LaTeXFeatures::isAvailable("CJKutf8")) ?
1663 : from_ascii(bparams.encoding().latexName());
1664 os << "\\begin{CJK}{" << cjkenc << "}{"
1665 << from_ascii(bparams.fonts_cjk) << "}";
1666 state->open_encoding_ = CJK;
1667 return make_pair(true, count + 15);
1670 // Dead code to avoid a warning:
1671 return make_pair(true, 0);