2 * \file output_latex.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
13 #include "output_latex.h"
15 #include "BiblioInfo.h"
17 #include "BufferParams.h"
20 #include "InsetList.h"
22 #include "LaTeXFeatures.h"
25 #include "OutputParams.h"
26 #include "Paragraph.h"
27 #include "ParagraphParameters.h"
28 #include "texstream.h"
29 #include "TextClass.h"
31 #include "insets/InsetBibitem.h"
32 #include "insets/InsetArgument.h"
34 #include "frontends/alert.h"
36 #include "support/lassert.h"
37 #include "support/convert.h"
38 #include "support/debug.h"
39 #include "support/lstrings.h"
40 #include "support/lyxalgo.h"
41 #include "support/textutils.h"
42 #include "support/gettext.h"
44 #include <QThreadStorage>
50 using namespace lyx::support;
66 OutputState() : open_encoding_(none), cjk_inherited_(0),
67 prev_env_language_(0), nest_level_(0)
70 OpenEncoding open_encoding_;
72 Language const * prev_env_language_;
74 stack<int> lang_switch_depth_; // Both are always empty when
75 stack<string> open_polyglossia_lang_; // not using polyglossia
79 OutputState * getOutputState()
81 // FIXME An instance of OutputState should be kept around for each export
82 // instead of using local thread storage
83 static QThreadStorage<OutputState *> outputstate;
84 if (!outputstate.hasLocalData())
85 outputstate.setLocalData(new OutputState);
86 return outputstate.localData();
90 string const & openLanguageName(OutputState const * state)
92 // Return a reference to the last active language opened with
93 // polyglossia or when using begin/end commands. If none or when
94 // using babel with only a begin command, return a reference to
97 static string const empty;
99 return state->open_polyglossia_lang_.empty()
101 : state->open_polyglossia_lang_.top();
105 bool atSameLastLangSwitchDepth(OutputState const * state)
107 // Return true if the actual nest level is the same at which the
108 // language was switched when using polyglossia or begin/end
109 // commands. Instead, return always true when using babel with
110 // only a begin command.
112 return state->lang_switch_depth_.size() == 0
114 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
118 bool isLocalSwitch(OutputState const * state)
120 // Return true if the language was opened by a local command switch.
122 return state->lang_switch_depth_.size()
123 && state->lang_switch_depth_.top() < 0;
127 bool langOpenedAtThisLevel(OutputState const * state)
129 // Return true if the language was opened at the current nesting level.
131 return state->lang_switch_depth_.size()
132 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
136 string const getPolyglossiaEnvName(Language const * lang)
138 string result = lang->polyglossia();
139 if (result == "arabic")
140 // exceptional spelling; see polyglossia docs.
146 string const getPolyglossiaBegin(string const & lang_begin_command,
147 string const & lang, string const & opts,
148 bool const localswitch = false)
152 // we need to revert the upcasing done in getPolyglossiaEnvName()
153 // in case we have a local polyglossia command (\textarabic).
154 string language = localswitch ? ascii_lowercase(lang) : lang;
155 result = subst(lang_begin_command, "$$lang", language);
157 string options = opts.empty() ?
158 string() : "[" + opts + "]";
159 result = subst(result, "$$opts", options);
165 struct TeXEnvironmentData
168 Layout const * style;
169 Language const * par_language;
170 Encoding const * prev_encoding;
171 bool leftindent_open;
175 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
177 ParagraphList::const_iterator pit,
179 OutputParams const & runparams)
181 TeXEnvironmentData data;
183 BufferParams const & bparams = buf.params();
185 // FIXME This test should not be necessary.
186 // We should perhaps issue an error if it is.
187 Layout const & style = text.inset().forcePlainLayout() ?
188 bparams.documentClass().plainLayout() : pit->layout();
190 ParagraphList const & paragraphs = text.paragraphs();
191 ParagraphList::const_iterator const priorpit =
192 pit == paragraphs.begin() ? pit : prev(pit, 1);
194 OutputState * state = getOutputState();
195 bool const use_prev_env_language = state->prev_env_language_ != 0
196 && priorpit->layout().isEnvironment()
197 && (priorpit->getDepth() > pit->getDepth()
198 || (priorpit->getDepth() == pit->getDepth()
199 && priorpit->layout() != pit->layout()));
201 data.prev_encoding = runparams.encoding;
202 data.par_language = pit->getParLanguage(bparams);
203 Language const * const doc_language = bparams.language;
204 Language const * const prev_par_language =
205 (pit != paragraphs.begin())
206 ? (use_prev_env_language ? state->prev_env_language_
207 : priorpit->getParLanguage(bparams))
210 bool const use_polyglossia = runparams.use_polyglossia;
211 string const par_lang = use_polyglossia ?
212 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
213 string const prev_par_lang = use_polyglossia ?
214 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
215 string const doc_lang = use_polyglossia ?
216 getPolyglossiaEnvName(doc_language) : doc_language->babel();
217 string const lang_begin_command = use_polyglossia ?
218 "\\begin{$$lang}" : lyxrc.language_command_begin;
219 string const lang_end_command = use_polyglossia ?
220 "\\end{$$lang}" : lyxrc.language_command_end;
221 bool const using_begin_end = use_polyglossia ||
222 !lang_end_command.empty();
224 // For polyglossia, switch language outside of environment, if possible.
225 if (par_lang != prev_par_lang) {
226 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
227 !lang_end_command.empty() &&
228 prev_par_lang != doc_lang &&
229 !prev_par_lang.empty()) {
230 os << from_ascii(subst(
234 // the '%' is necessary to prevent unwanted whitespace
240 // If no language was explicitly opened and we are using
241 // polyglossia or begin/end commands, then the current
242 // language is the document language.
243 string const & cur_lang = using_begin_end
244 && state->lang_switch_depth_.size()
245 ? openLanguageName(state)
248 if ((lang_end_command.empty() ||
249 par_lang != doc_lang ||
250 par_lang != cur_lang) &&
252 string bc = use_polyglossia ?
253 getPolyglossiaBegin(lang_begin_command, par_lang,
254 data.par_language->polyglossiaOpts())
255 : subst(lang_begin_command, "$$lang", par_lang);
257 // the '%' is necessary to prevent unwanted whitespace
260 pushLanguageName(par_lang);
264 data.leftindent_open = false;
265 if (!pit->params().leftIndent().zero()) {
266 os << "\\begin{LyXParagraphLeftIndent}{"
267 << from_ascii(pit->params().leftIndent().asLatexString())
269 data.leftindent_open = true;
272 if (style.isEnvironment())
273 state->nest_level_ += 1;
275 if (style.isEnvironment() && !style.latexname().empty()) {
276 os << "\\begin{" << from_ascii(style.latexname()) << '}';
277 if (!style.latexargs().empty()) {
278 OutputParams rp = runparams;
279 rp.local_font = &pit->getFirstFontSettings(bparams);
280 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
282 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
284 << pit->params().labelWidthString()
286 } else if (style.labeltype == LABEL_BIBLIO) {
287 if (pit->params().labelWidthString().empty())
288 os << '{' << bibitemWidest(buf, runparams) << "}\n";
291 << pit->params().labelWidthString()
294 os << from_ascii(style.latexparam()) << '\n';
298 // in multilingual environments, the CJK tags have to be nested properly
299 data.cjk_nested = false;
300 if (data.par_language->encoding()->package() == Encoding::CJK &&
301 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
302 if (prev_par_language->encoding()->package() == Encoding::CJK) {
303 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
304 && LaTeXFeatures::isAvailable("CJKutf8")) ?
306 : from_ascii(data.par_language->encoding()->latexName());
307 os << "\\begin{CJK}{" << cjkenc
308 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
310 state->open_encoding_ = CJK;
311 data.cjk_nested = true;
317 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
318 TeXEnvironmentData const & data)
320 OutputState * state = getOutputState();
321 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
322 if (state->open_encoding_ == CJK && data.cjk_nested) {
323 // We need to close the encoding even if it does not change
324 // to do correct environment nesting
325 os << "\\end{CJK}\n";
326 state->open_encoding_ = none;
329 if (data.style->isEnvironment()) {
331 bool const using_begin_end =
332 runparams.use_polyglossia ||
333 !lyxrc.language_command_end.empty();
334 // Close any language opened at this nest level
335 if (using_begin_end) {
336 while (langOpenedAtThisLevel(state)) {
337 if (isLocalSwitch(state)) {
341 << openLanguageName(state)
347 state->nest_level_ -= 1;
348 string const & name = data.style->latexname();
350 os << "\\end{" << from_ascii(name) << "}\n";
351 state->prev_env_language_ = data.par_language;
352 if (runparams.encoding != data.prev_encoding) {
353 runparams.encoding = data.prev_encoding;
354 os << setEncoding(data.prev_encoding->iconvName());
358 if (data.leftindent_open) {
359 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
360 state->prev_env_language_ = data.par_language;
361 if (runparams.encoding != data.prev_encoding) {
362 runparams.encoding = data.prev_encoding;
363 os << setEncoding(data.prev_encoding->iconvName());
367 // Check whether we should output a blank line after the environment
368 if (!data.style->nextnoindent)
373 void TeXEnvironment(Buffer const & buf, Text const & text,
374 OutputParams const & runparams,
375 pit_type & pit, otexstream & os)
377 ParagraphList const & paragraphs = text.paragraphs();
378 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
379 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
381 Layout const & current_layout = par->layout();
382 depth_type const current_depth = par->params().depth();
383 Length const & current_left_indent = par->params().leftIndent();
385 // This is for debugging purpose at the end.
386 pit_type const par_begin = pit;
387 for (; pit < runparams.par_end; ++pit) {
388 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
390 // check first if this is an higher depth paragraph.
391 bool go_out = (par->params().depth() < current_depth);
392 if (par->params().depth() == current_depth) {
393 // This environment is finished.
394 go_out |= (par->layout() != current_layout);
395 go_out |= (par->params().leftIndent() != current_left_indent);
398 // nothing to do here, restore pit and go out.
403 if (par->layout() == current_layout
404 && par->params().depth() == current_depth
405 && par->params().leftIndent() == current_left_indent) {
406 // We are still in the same environment so TeXOnePar and continue;
407 TeXOnePar(buf, text, pit, os, runparams);
411 // We are now in a deeper environment.
412 // Either par->layout() != current_layout
413 // Or par->params().depth() > current_depth
414 // Or par->params().leftIndent() != current_left_indent)
416 // FIXME This test should not be necessary.
417 // We should perhaps issue an error if it is.
418 bool const force_plain_layout = text.inset().forcePlainLayout();
419 Layout const & style = force_plain_layout
420 ? buf.params().documentClass().plainLayout()
423 if (!style.isEnvironment()) {
424 // This is a standard paragraph, no need to call TeXEnvironment.
425 TeXOnePar(buf, text, pit, os, runparams);
429 // This is a new environment.
430 TeXEnvironmentData const data =
431 prepareEnvironment(buf, text, par, os, runparams);
432 // Recursive call to TeXEnvironment!
433 TeXEnvironment(buf, text, runparams, pit, os);
434 finishEnvironment(os, runparams, data);
437 if (pit != runparams.par_end)
438 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
442 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
443 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
445 unsigned int const argnr = latexargs.size();
449 // Default and preset args are always output, so if they require
450 // other arguments, consider this.
451 Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
452 Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
453 for (; lit != lend; ++lit) {
454 Layout::latexarg arg = (*lit).second;
455 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
456 vector<string> req = getVectorFromString(arg.requires);
457 required.insert(required.end(), req.begin(), req.end());
461 for (unsigned int i = 1; i <= argnr; ++i) {
462 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
463 bool inserted = false;
464 if (lit != ilist.end()) {
465 InsetArgument const * ins = (*lit).second;
467 Layout::LaTeXArgMap::const_iterator const lait =
468 latexargs.find(ins->name());
469 if (lait != latexargs.end()) {
470 Layout::latexarg arg = (*lait).second;
471 docstring ldelim = arg.mandatory ?
472 from_ascii("{") : from_ascii("[");
473 docstring rdelim = arg.mandatory ?
474 from_ascii("}") : from_ascii("]");
475 if (!arg.ldelim.empty())
477 if (!arg.rdelim.empty())
479 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
485 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
486 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
487 for (; lait != laend; ++lait) {
488 string const name = prefix + convert<string>(i);
489 if ((*lait).first == name) {
490 Layout::latexarg arg = (*lait).second;
491 docstring preset = arg.presetarg;
492 if (!arg.defaultarg.empty()) {
495 preset += arg.defaultarg;
498 docstring ldelim = arg.ldelim.empty() ?
499 from_ascii("{") : arg.ldelim;
500 docstring rdelim = arg.rdelim.empty() ?
501 from_ascii("}") : arg.rdelim;
502 os << ldelim << preset << rdelim;
503 } else if (!preset.empty()) {
504 docstring ldelim = arg.ldelim.empty() ?
505 from_ascii("[") : arg.ldelim;
506 docstring rdelim = arg.rdelim.empty() ?
507 from_ascii("]") : arg.rdelim;
508 os << ldelim << preset << rdelim;
509 } else if (find(required.begin(), required.end(),
510 (*lait).first) != required.end()) {
511 docstring ldelim = arg.ldelim.empty() ?
512 from_ascii("[") : arg.ldelim;
513 docstring rdelim = arg.rdelim.empty() ?
514 from_ascii("]") : arg.rdelim;
515 os << ldelim << rdelim;
528 void pushLanguageName(string const & lang_name, bool localswitch)
530 OutputState * state = getOutputState();
532 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
533 state->lang_switch_depth_.push(nest_level);
534 state->open_polyglossia_lang_.push(lang_name);
538 void popLanguageName()
540 OutputState * state = getOutputState();
542 state->lang_switch_depth_.pop();
543 state->open_polyglossia_lang_.pop();
547 string const & openLanguageName()
549 OutputState * state = getOutputState();
551 return openLanguageName(state);
557 void addArgInsets(Paragraph const & par, string const & prefix,
558 Layout::LaTeXArgMap const & latexargs,
559 map<int, InsetArgument const *> & ilist,
560 vector<string> & required)
562 for (auto const & table : par.insetList()) {
563 InsetArgument const * arg = table.inset->asInsetArgument();
566 if (arg->name().empty()) {
567 LYXERR0("Error: Unnamed argument inset!");
570 string const name = prefix.empty() ?
571 arg->name() : split(arg->name(), ':');
572 // why converting into an integer?
573 unsigned int const nr = convert<unsigned int>(name);
574 if (ilist.find(nr) == ilist.end())
576 Layout::LaTeXArgMap::const_iterator const lit =
577 latexargs.find(arg->name());
578 if (lit != latexargs.end()) {
579 Layout::latexarg const & larg = lit->second;
580 vector<string> req = getVectorFromString(larg.requires);
581 move(req.begin(), req.end(), back_inserter(required));
589 void latexArgInsets(Paragraph const & par, otexstream & os,
590 OutputParams const & runparams,
591 Layout::LaTeXArgMap const & latexargs,
592 string const & prefix)
594 map<int, InsetArgument const *> ilist;
595 vector<string> required;
596 addArgInsets(par, prefix, latexargs, ilist, required);
597 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
601 void latexArgInsets(ParagraphList const & pars,
602 ParagraphList::const_iterator pit,
603 otexstream & os, OutputParams const & runparams,
604 Layout::LaTeXArgMap const & latexargs,
605 string const & prefix)
607 map<int, InsetArgument const *> ilist;
608 vector<string> required;
610 depth_type const current_depth = pit->params().depth();
611 Layout const current_layout = pit->layout();
613 // get the first paragraph in sequence with this layout and depth
616 if (lyx::prev(pit, offset) == pars.begin())
618 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
619 if (priorpit->layout() == current_layout
620 && priorpit->params().depth() == current_depth)
626 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
628 for (; spit != pars.end(); ++spit) {
629 if (spit->layout() != current_layout ||
630 spit->params().depth() < current_depth)
632 if (spit->params().depth() > current_depth)
634 addArgInsets(*spit, prefix, latexargs, ilist, required);
636 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
640 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
641 OutputParams const & runparams,
642 Layout::LaTeXArgMap const & latexargs,
643 string const & prefix)
645 map<int, InsetArgument const *> ilist;
646 vector<string> required;
648 for (Paragraph const & par : pars) {
649 if (par.layout().hasArgs())
650 // The InsetArguments inside this paragraph refer to this paragraph
652 addArgInsets(par, prefix, latexargs, ilist, required);
654 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
660 // output the proper paragraph start according to latextype.
661 void parStartCommand(Paragraph const & par, otexstream & os,
662 OutputParams const & runparams, Layout const & style)
664 switch (style.latextype) {
666 os << '\\' << from_ascii(style.latexname());
669 if (!style.latexargs().empty())
670 latexArgInsets(par, os, runparams, style.latexargs());
671 os << from_ascii(style.latexparam());
673 case LATEX_ITEM_ENVIRONMENT:
674 case LATEX_LIST_ENVIRONMENT:
675 os << "\\" + style.itemcommand();
677 if (!style.itemargs().empty())
678 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
681 case LATEX_BIB_ENVIRONMENT:
682 // ignore this, the inset will write itself
691 // FIXME: this should be anonymous
692 void TeXOnePar(Buffer const & buf,
696 OutputParams const & runparams_in,
697 string const & everypar,
698 int start_pos, int end_pos,
701 BufferParams const & bparams = runparams_in.is_child
702 ? buf.masterParams() : buf.params();
703 ParagraphList const & paragraphs = text.paragraphs();
704 Paragraph const & par = paragraphs.at(pit);
705 // FIXME This check should not really be needed.
706 // Perhaps we should issue an error if it is.
707 Layout const & style = text.inset().forcePlainLayout() ?
708 bparams.documentClass().plainLayout() : par.layout();
710 if (style.inpreamble && !force)
713 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
716 OutputParams runparams = runparams_in;
717 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
718 // We reinitialze par begin and end to be on the safe side
719 // with embedded inset as we don't know if they set those
721 runparams.par_begin = 0;
722 runparams.par_end = 0;
724 bool const maintext = text.isMainText();
725 // we are at the beginning of an inset and CJK is already open;
726 // we count inheritation levels to get the inset nesting right.
727 OutputState * state = getOutputState();
728 if (pit == 0 && !maintext
729 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
730 state->cjk_inherited_ += 1;
731 state->open_encoding_ = none;
734 if (text.inset().isPassThru()) {
735 Font const outerfont = text.outerFont(pit);
737 // No newline before first paragraph in this lyxtext
740 if (!text.inset().getLayout().parbreakIsNewline())
744 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
748 Paragraph const * nextpar = runparams.isLastPar
749 ? 0 : ¶graphs.at(pit + 1);
751 bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
753 if (style.pass_thru) {
754 Font const outerfont = text.outerFont(pit);
755 parStartCommand(par, os, runparams, style);
759 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
761 // I did not create a parEndCommand for this minuscule
762 // task because in the other user of parStartCommand
763 // the code is different (JMarc)
764 if (style.isCommand())
768 if (!style.parbreak_is_newline) {
770 } else if (nextpar && !style.isEnvironment()) {
771 Layout const nextstyle = text.inset().forcePlainLayout()
772 ? bparams.documentClass().plainLayout()
774 if (nextstyle.name() != style.name())
781 // This paragraph's language
782 Language const * const par_language = par.getParLanguage(bparams);
783 Language const * const nextpar_language = nextpar ?
784 nextpar->getParLanguage(bparams) : 0;
785 // The document's language
786 Language const * const doc_language = bparams.language;
787 // The language that was in effect when the environment this paragraph is
788 // inside of was opened
789 Language const * const outer_language =
790 (runparams.local_font != 0) ?
791 runparams.local_font->language() : doc_language;
793 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
795 // The previous language that was in effect is the language of the
796 // previous paragraph, unless the previous paragraph is inside an
797 // environment with nesting depth greater than (or equal to, but with
798 // a different layout) the current one. If there is no previous
799 // paragraph, the previous language is the outer language.
800 // Note further that we take the outer language also if the prior par
801 // is PassThru, since in that case it has latex_language, and all secondary
802 // languages have been closed (#10793).
803 bool const use_prev_env_language = state->prev_env_language_ != 0
805 && priorpar->layout().isEnvironment()
806 && (priorpar->getDepth() > par.getDepth()
807 || (priorpar->getDepth() == par.getDepth()
808 && priorpar->layout() != par.layout()));
810 // We need to ignore previous intitle commands since languages
811 // are switched locally there (# 11514)
812 // There might be paragraphs before the title, so we check this.
813 Paragraph * prior_nontitle_par = nullptr;
814 if (!intitle_command) {
818 Paragraph const * tmppar = ¶graphs.at(ppit);
819 if (tmppar->layout().intitle && tmppar->layout().isCommand())
821 prior_nontitle_par = const_cast<Paragraph*>(tmppar);
825 Language const * const prev_language =
826 runparams_in.for_search
827 ? languages.getLanguage("ignore")
828 : (prior_nontitle_par && !prior_nontitle_par->isPassThru())
829 ? (use_prev_env_language
830 ? state->prev_env_language_
831 : prior_nontitle_par->getParLanguage(bparams))
834 bool const use_polyglossia = runparams.use_polyglossia;
835 string const par_lang = use_polyglossia ?
836 getPolyglossiaEnvName(par_language): par_language->babel();
837 string const prev_lang = use_polyglossia ?
838 getPolyglossiaEnvName(prev_language) : prev_language->babel();
839 string const outer_lang = use_polyglossia ?
840 getPolyglossiaEnvName(outer_language) : outer_language->babel();
841 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
842 getPolyglossiaEnvName(nextpar_language) :
843 nextpar_language->babel()) : string();
844 string lang_begin_command = use_polyglossia ?
845 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
846 string lang_end_command = use_polyglossia ?
847 "\\end{$$lang}" : lyxrc.language_command_end;
848 // the '%' is necessary to prevent unwanted whitespace
849 string lang_command_termination = "%\n";
850 bool const using_begin_end = use_polyglossia ||
851 !lang_end_command.empty();
853 // For InTitle commands, we need to switch the language inside the command
854 // (see #10849); thus open the command here.
855 if (intitle_command) {
856 parStartCommand(par, os, runparams, style);
860 // In some insets (such as Arguments), we cannot use \selectlanguage.
861 // Also, if an RTL language is set via environment in polyglossia,
862 // only a nested \\text<lang> command will reset the direction for LTR
863 // languages (see # 10111).
864 bool const in_polyglossia_rtl_env =
866 && runparams.local_font != 0
867 && outer_language->rightToLeft()
868 && !par_language->rightToLeft();
869 bool const localswitch = text.inset().forceLocalFontSwitch()
870 || (using_begin_end && text.inset().forcePlainLayout())
871 || in_polyglossia_rtl_env;
873 lang_begin_command = use_polyglossia ?
874 "\\text$$lang$$opts{" : lyxrc.language_command_local;
875 lang_end_command = "}";
876 lang_command_termination.clear();
879 bool const localswitch_needed = localswitch && par_lang != outer_lang;
881 // localswitches need to be closed and reopened at each par
882 if ((par_lang != prev_lang || localswitch_needed)
883 // check if we already put language command in TeXEnvironment()
884 && !(style.isEnvironment()
885 && (pit == 0 || (priorpar->layout() != par.layout()
886 && priorpar->getDepth() <= par.getDepth())
887 || priorpar->getDepth() < par.getDepth()))) {
889 && (!using_begin_end || langOpenedAtThisLevel(state))
890 && !lang_end_command.empty()
891 && prev_lang != outer_lang
892 && !prev_lang.empty()
893 && (!using_begin_end || !style.isEnvironment())) {
894 os << from_ascii(subst(lang_end_command,
897 << lang_command_termination;
902 // We need to open a new language if we couldn't close the previous
903 // one (because there's no language_command_end); and even if we closed
904 // the previous one, if the current language is different than the
905 // outer_language (which is currently in effect once the previous one
907 if ((lang_end_command.empty() || par_lang != outer_lang
909 || (style.isEnvironment() && par_lang != prev_lang)))
910 && !par_lang.empty()) {
911 // If we're inside an inset, and that inset is within an \L or \R
912 // (or equivalents), then within the inset, too, any opposite
913 // language paragraph should appear within an \L or \R (in addition
914 // to, outside of, the normal language switch commands).
915 // This behavior is not correct for ArabTeX, though.
918 && par_language->lang() != "arabic_arabtex"
919 && outer_language->lang() != "arabic_arabtex"
920 // are we in an inset?
921 && runparams.local_font != 0
922 // is the inset within an \L or \R?
924 // FIXME: currently, we don't check this; this means that
925 // we'll have unnnecessary \L and \R commands, but that
926 // doesn't seem to hurt (though latex will complain)
928 // is this paragraph in the opposite direction?
929 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
930 // FIXME: I don't have a working copy of the Arabi package, so
931 // I'm not sure if the farsi and arabic_arabi stuff is correct
933 if (par_language->lang() == "farsi")
935 else if (outer_language->lang() == "farsi")
937 else if (par_language->lang() == "arabic_arabi")
939 else if (outer_language->lang() == "arabic_arabi")
941 // remaining RTL languages currently is hebrew
942 else if (par_language->rightToLeft())
947 // With CJK, the CJK tag has to be closed first (see below)
948 if (runparams.encoding->package() != Encoding::CJK
949 && (par_lang != openLanguageName(state) || localswitch || intitle_command)
950 && !par_lang.empty()) {
951 string bc = use_polyglossia ?
952 getPolyglossiaBegin(lang_begin_command, par_lang,
953 par_language->polyglossiaOpts(),
955 : subst(lang_begin_command, "$$lang", par_lang);
957 os << lang_command_termination;
959 pushLanguageName(par_lang, localswitch);
964 // Switch file encoding if necessary; no need to do this for "default"
965 // encoding, since this only affects the position of the outputted
966 // \inputencoding command; the encoding switch will occur when necessary
967 if (bparams.inputenc == "auto"
968 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
969 && runparams.encoding->package() != Encoding::none) {
970 // Look ahead for future encoding changes.
971 // We try to output them at the beginning of the paragraph,
972 // since the \inputencoding command is not allowed e.g. in
973 // sections. For this reason we only set runparams.moving_arg
974 // after checking for the encoding change, otherwise the
975 // change would be always avoided by switchEncoding().
976 for (pos_type i = 0; i < par.size(); ++i) {
977 char_type const c = par.getChar(i);
978 Encoding const * const encoding =
979 par.getFontSettings(bparams, i).language()->encoding();
980 if (encoding->package() != Encoding::CJK
981 && runparams.encoding->package() == Encoding::inputenc
986 // All characters before c are in the ASCII range, and
987 // c is non-ASCII (but no inset), so change the
988 // encoding to that required by the language of c.
989 // With CJK, only add switch if we have CJK content at the beginning
991 if (i != 0 && encoding->package() == Encoding::CJK)
994 pair<bool, int> enc_switch = switchEncoding(os.os(),
995 bparams, runparams, *encoding);
996 // the following is necessary after a CJK environment in a multilingual
997 // context (nesting issue).
998 if (par_language->encoding()->package() == Encoding::CJK
999 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1000 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1001 && LaTeXFeatures::isAvailable("CJKutf8")) ?
1003 : from_ascii(par_language->encoding()->latexName());
1004 os << "\\begin{CJK}{" << cjkenc
1005 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1006 state->open_encoding_ = CJK;
1008 if (encoding->package() != Encoding::none && enc_switch.first) {
1009 if (enc_switch.second > 0) {
1010 // the '%' is necessary to prevent unwanted whitespace
1013 // With CJK, the CJK tag had to be closed first (see above)
1014 if (runparams.encoding->package() == Encoding::CJK
1015 && par_lang != openLanguageName(state)
1016 && !par_lang.empty()) {
1017 string bc = use_polyglossia ?
1018 getPolyglossiaBegin(lang_begin_command, par_lang,
1019 par_language->polyglossiaOpts(),
1021 : subst(lang_begin_command, "$$lang", par_lang);
1023 << lang_command_termination;
1024 if (using_begin_end)
1025 pushLanguageName(par_lang, localswitch);
1027 runparams.encoding = encoding;
1033 runparams.moving_arg |= style.needprotect;
1034 Encoding const * const prev_encoding = runparams.encoding;
1036 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1037 if (par.allowParagraphCustomization()) {
1038 if (par.params().startOfAppendix()) {
1039 os << "\n\\appendix\n";
1042 // InTitle commands must use switches (not environments)
1043 // inside the commands (see #9332)
1044 if (style.intitle) {
1045 if (!par.params().spacing().isDefault())
1047 if (runparams.moving_arg)
1049 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1052 if (!par.params().spacing().isDefault()
1053 && (pit == 0 || !priorpar->hasSameLayout(par)))
1055 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1059 if (style.isCommand()) {
1065 // For InTitle commands, we already started the command before
1066 // the language switch
1067 if (!intitle_command)
1068 parStartCommand(par, os, runparams, style);
1070 Font const outerfont = text.outerFont(pit);
1073 os << from_utf8(everypar);
1074 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1076 Font const font = par.empty()
1077 ? par.getLayoutFont(bparams, outerfont)
1078 : par.getFont(bparams, par.size() - 1, outerfont);
1080 bool const is_command = style.isCommand();
1082 // InTitle commands need to be closed after the language has been closed.
1083 if (!intitle_command) {
1086 if (!style.postcommandargs().empty())
1087 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1088 if (runparams.encoding != prev_encoding) {
1089 runparams.encoding = prev_encoding;
1090 os << setEncoding(prev_encoding->iconvName());
1095 bool pending_newline = false;
1096 bool unskip_newline = false;
1097 bool close_lang_switch = false;
1098 switch (style.latextype) {
1099 case LATEX_ITEM_ENVIRONMENT:
1100 case LATEX_LIST_ENVIRONMENT:
1101 if ((nextpar && par_lang != nextpar_lang
1102 && nextpar->getDepth() == par.getDepth())
1103 || (atSameLastLangSwitchDepth(state) && nextpar
1104 && nextpar->getDepth() < par.getDepth()))
1105 close_lang_switch = using_begin_end;
1106 if (nextpar && par.params().depth() < nextpar->params().depth())
1107 pending_newline = true;
1109 case LATEX_ENVIRONMENT: {
1110 // if its the last paragraph of the current environment
1111 // skip it otherwise fall through
1113 && ((nextpar->layout() != par.layout()
1114 || nextpar->params().depth() != par.params().depth())
1115 || (!using_begin_end || par_lang != nextpar_lang)))
1117 close_lang_switch = using_begin_end;
1124 // we don't need it for the last paragraph and in InTitle commands!!!
1125 if (nextpar && !intitle_command)
1126 pending_newline = true;
1129 // InTitle commands use switches (not environments) for space settings
1130 if (par.allowParagraphCustomization() && !style.intitle) {
1131 if (!par.params().spacing().isDefault()
1132 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1133 if (pending_newline)
1136 string const endtag =
1137 par.params().spacing().writeEnvirEnd(useSetSpace);
1138 if (prefixIs(endtag, "\\end{"))
1141 os << from_ascii(endtag);
1142 pending_newline = true;
1146 // Closing the language is needed for the last paragraph in a given language
1147 // as well as for any InTitleCommand (since these set the language locally);
1148 // it is also needed if we're within an \L or \R that we may have opened above
1149 // (not necessarily in this paragraph) and are about to close.
1150 bool closing_rtl_ltr_environment = !using_begin_end
1152 && (par_language->lang() != "arabic_arabtex"
1153 && outer_language->lang() != "arabic_arabtex")
1154 // have we opened an \L or \R environment?
1155 && runparams.local_font != 0
1156 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1157 // are we about to close the language?
1158 &&((nextpar && par_lang != nextpar_lang)
1159 || (runparams.isLastPar && par_lang != outer_lang));
1161 if (localswitch_needed
1162 || (intitle_command && using_begin_end)
1163 || closing_rtl_ltr_environment
1164 || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1165 && (par_lang != outer_lang || (using_begin_end
1166 && style.isEnvironment()
1167 && par_lang != nextpar_lang)))) {
1168 // Since \selectlanguage write the language to the aux file,
1169 // we need to reset the language at the end of footnote or
1172 if (!localswitch && (pending_newline || close_lang_switch))
1175 // when the paragraph uses CJK, the language has to be closed earlier
1176 if (font.language()->encoding()->package() != Encoding::CJK) {
1177 if (lang_end_command.empty()) {
1178 // If this is a child, we should restore the
1179 // master language after the last paragraph.
1180 Language const * const current_language =
1181 (runparams.isLastPar && runparams.master_language)
1182 ? runparams.master_language
1184 string const current_lang = use_polyglossia
1185 ? getPolyglossiaEnvName(current_language)
1186 : current_language->babel();
1187 if (!current_lang.empty()
1188 && current_lang != openLanguageName(state)) {
1189 string bc = use_polyglossia ?
1190 getPolyglossiaBegin(lang_begin_command, current_lang,
1191 current_language->polyglossiaOpts(),
1193 : subst(lang_begin_command, "$$lang", current_lang);
1195 pending_newline = !localswitch;
1196 unskip_newline = !localswitch;
1197 if (using_begin_end)
1198 pushLanguageName(current_lang, localswitch);
1200 } else if ((!using_begin_end ||
1201 langOpenedAtThisLevel(state)) &&
1202 !par_lang.empty()) {
1203 // If we are in an environment, we have to
1204 // close the "outer" language afterwards
1205 string const & cur_lang = openLanguageName(state);
1206 if (!style.isEnvironment()
1207 || (close_lang_switch
1208 && atSameLastLangSwitchDepth(state)
1209 && par_lang != outer_lang
1210 && (par_lang != cur_lang
1211 || (cur_lang != outer_lang
1213 && style != nextpar->layout())))
1214 || (atSameLastLangSwitchDepth(state)
1215 && state->lang_switch_depth_.size()
1216 && cur_lang != par_lang)
1217 || in_polyglossia_rtl_env)
1219 if (using_begin_end && !localswitch)
1221 os << from_ascii(subst(
1225 pending_newline = !localswitch;
1226 unskip_newline = !localswitch;
1227 if (using_begin_end)
1233 if (closing_rtl_ltr_environment)
1236 // InTitle commands need to be closed after the language has been closed.
1237 if (intitle_command) {
1240 if (!style.postcommandargs().empty())
1241 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1242 if (runparams.encoding != prev_encoding) {
1243 runparams.encoding = prev_encoding;
1244 os << setEncoding(prev_encoding->iconvName());
1249 bool const last_was_separator =
1250 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1252 if (pending_newline) {
1254 // prevent unwanted whitespace
1256 if (!os.afterParbreak() && !last_was_separator)
1260 // if this is a CJK-paragraph and the next isn't, close CJK
1261 // also if the next paragraph is a multilingual environment (because of nesting)
1263 && state->open_encoding_ == CJK
1264 && (nextpar_language->encoding()->package() != Encoding::CJK
1265 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1266 // inbetween environments, CJK has to be closed later (nesting!)
1267 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1268 os << "\\end{CJK}\n";
1269 state->open_encoding_ = none;
1272 // If this is the last paragraph, close the CJK environment
1273 // if necessary. If it's an environment, we'll have to \end that first.
1274 if (runparams.isLastPar && !style.isEnvironment()) {
1275 switch (state->open_encoding_) {
1277 // do nothing at the end of child documents
1278 if (maintext && buf.masterBuffer() != &buf)
1282 os << "\n\\end{CJK}\n";
1286 state->open_encoding_ = none;
1291 state->open_encoding_ = none;
1301 // If this is the last paragraph, and a local_font was set upon entering
1302 // the inset, and we're using "auto" or "default" encoding, and not
1303 // compiling with XeTeX or LuaTeX, the encoding
1304 // should be set back to that local_font's encoding.
1305 if (runparams.isLastPar && runparams_in.local_font != 0
1306 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1307 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1308 && !runparams.isFullUnicode()
1310 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1311 os << setEncoding(runparams_in.encoding->iconvName());
1313 // Otherwise, the current encoding should be set for the next paragraph.
1315 runparams_in.encoding = runparams.encoding;
1318 // we don't need a newline for the last paragraph!!!
1319 // Note from JMarc: we will re-add a \n explicitly in
1320 // TeXEnvironment, because it is needed in this case
1321 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1322 // Make sure to start a new line
1324 Layout const & next_layout = nextpar->layout();
1325 // A newline '\n' is always output before a command,
1326 // so avoid doubling it.
1327 if (!next_layout.isCommand()) {
1328 // Here we now try to avoid spurious empty lines by
1329 // outputting a paragraph break only if: (case 1) the
1330 // paragraph style allows parbreaks and no \begin, \end
1331 // or \item tags are going to follow (i.e., if the next
1332 // isn't the first or the current isn't the last
1333 // paragraph of an environment or itemize) and the
1334 // depth and alignment of the following paragraph is
1335 // unchanged, or (case 2) the following is a
1336 // non-environment paragraph whose depth is increased
1337 // but whose alignment is unchanged, or (case 3) the
1338 // paragraph is not an environment and the next one is a
1339 // non-itemize-like env at lower depth, or (case 4) the
1340 // paragraph is a command not followed by an environment
1341 // and the alignment of the current and next paragraph
1342 // is unchanged, or (case 5) the current alignment is
1343 // changed and a standard paragraph follows.
1344 DocumentClass const & tclass = bparams.documentClass();
1345 if ((style == next_layout
1346 && !style.parbreak_is_newline
1347 && !text.inset().getLayout().parbreakIsNewline()
1348 && style.latextype != LATEX_ITEM_ENVIRONMENT
1349 && style.latextype != LATEX_LIST_ENVIRONMENT
1350 && style.align == par.getAlign(bparams)
1351 && nextpar->getDepth() == par.getDepth()
1352 && nextpar->getAlign(bparams) == par.getAlign(bparams))
1353 || (!next_layout.isEnvironment()
1354 && nextpar->getDepth() > par.getDepth()
1355 && nextpar->getAlign(bparams) == next_layout.align)
1356 || (!style.isEnvironment()
1357 && next_layout.latextype == LATEX_ENVIRONMENT
1358 && nextpar->getDepth() < par.getDepth())
1359 || (style.isCommand()
1360 && !next_layout.isEnvironment()
1361 && style.align == par.getAlign(bparams)
1362 && next_layout.align == nextpar->getAlign(bparams))
1363 || (style.align != par.getAlign(bparams)
1364 && tclass.isDefaultLayout(next_layout))) {
1370 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1371 << &par << " next " << nextpar);
1377 // LaTeX all paragraphs
1378 void latexParagraphs(Buffer const & buf,
1381 OutputParams const & runparams,
1382 string const & everypar)
1384 LASSERT(runparams.par_begin <= runparams.par_end,
1385 { os << "% LaTeX Output Error\n"; return; } );
1387 BufferParams const & bparams = buf.params();
1388 BufferParams const & mparams = buf.masterParams();
1390 bool const maintext = text.isMainText();
1391 bool const is_child = buf.masterBuffer() != &buf;
1392 bool const multibib_child = maintext && is_child
1393 && mparams.multibib == "child";
1395 if (multibib_child && mparams.useBiblatex())
1396 os << "\\newrefsection";
1397 else if (multibib_child && mparams.useBibtopic()
1398 && !buf.masterBibInfo().empty()) {
1399 os << "\\begin{btUnit}\n";
1400 runparams.openbtUnit = true;
1403 // Open a CJK environment at the beginning of the main buffer
1404 // if the document's language is a CJK language
1405 // (but not in child documents)
1406 OutputState * state = getOutputState();
1407 if (maintext && !is_child && !bparams.useNonTeXFonts
1408 && bparams.language->encoding()->package() == Encoding::CJK
1409 && (bparams.encoding().name() == "utf8-cjk"
1410 || bparams.encoding().iconvName() != "UTF-8")) {
1411 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1412 && LaTeXFeatures::isAvailable("CJKutf8")) ?
1414 : from_ascii(bparams.encoding().latexName());
1415 os << "\\begin{CJK}{" << cjkenc
1416 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1417 state->open_encoding_ = CJK;
1419 // if "auto begin" is switched off, explicitly switch the
1420 // language on at start
1421 string const mainlang = runparams.use_polyglossia
1422 ? getPolyglossiaEnvName(bparams.language)
1423 : bparams.language->babel();
1424 string const lang_begin_command = runparams.use_polyglossia ?
1425 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1426 string const lang_end_command = runparams.use_polyglossia ?
1427 "\\end{$$lang}" : lyxrc.language_command_end;
1428 bool const using_begin_end = runparams.use_polyglossia ||
1429 !lang_end_command.empty();
1431 if (maintext && !lyxrc.language_auto_begin &&
1432 !mainlang.empty()) {
1434 string bc = runparams.use_polyglossia ?
1435 getPolyglossiaBegin(lang_begin_command, mainlang,
1436 bparams.language->polyglossiaOpts())
1437 : subst(lang_begin_command, "$$lang", mainlang);
1440 if (using_begin_end)
1441 pushLanguageName(mainlang);
1444 ParagraphList const & paragraphs = text.paragraphs();
1446 if (runparams.par_begin == runparams.par_end) {
1447 // The full doc will be exported but it is easier to just rely on
1448 // runparams range parameters that will be passed TeXEnvironment.
1449 runparams.par_begin = 0;
1450 runparams.par_end = paragraphs.size();
1453 pit_type pit = runparams.par_begin;
1454 // lastpit is for the language check after the loop.
1455 pit_type lastpit = pit;
1456 // variables used in the loop:
1457 bool was_title = false;
1458 bool already_title = false;
1459 DocumentClass const & tclass = bparams.documentClass();
1461 // Did we already warn about inTitle layout mixing? (we only warn once)
1462 bool gave_layout_warning = false;
1463 for (; pit < runparams.par_end; ++pit) {
1465 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1467 // FIXME This check should not be needed. We should
1468 // perhaps issue an error if it is.
1469 Layout const & layout = text.inset().forcePlainLayout() ?
1470 tclass.plainLayout() : par->layout();
1472 if (layout.intitle) {
1473 if (already_title) {
1474 if (!gave_layout_warning && !runparams.dryrun) {
1475 gave_layout_warning = true;
1476 frontend::Alert::warning(_("Error in latexParagraphs"),
1477 bformat(_("You are using at least one "
1478 "layout (%1$s) intended for the title, "
1479 "after using non-title layouts. This "
1480 "could lead to missing or incorrect output."
1483 } else if (!was_title) {
1485 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1487 << from_ascii(tclass.titlename())
1491 } else if (was_title && !already_title && !layout.inpreamble) {
1492 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1493 os << "\\end{" << from_ascii(tclass.titlename())
1497 os << "\\" << from_ascii(tclass.titlename())
1500 already_title = true;
1504 if (layout.isCommand() && !layout.latexname().empty()
1505 && layout.latexname() == bparams.multibib) {
1506 if (runparams.openbtUnit)
1507 os << "\\end{btUnit}\n";
1508 if (!bparams.useBiblatex()
1509 && !buf.masterBibInfo().empty()) {
1510 os << '\n' << "\\begin{btUnit}\n";
1511 runparams.openbtUnit = true;
1515 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1516 // This is a standard top level paragraph, TeX it and continue.
1517 TeXOnePar(buf, text, pit, os, runparams, everypar);
1521 TeXEnvironmentData const data =
1522 prepareEnvironment(buf, text, par, os, runparams);
1523 // pit can be changed in TeXEnvironment.
1524 TeXEnvironment(buf, text, runparams, pit, os);
1525 finishEnvironment(os, runparams, data);
1528 if (pit == runparams.par_end) {
1529 // Make sure that the last paragraph is
1530 // correctly terminated (because TeXOnePar does
1531 // not add a \n in this case)
1535 // It might be that we only have a title in this document
1536 if (was_title && !already_title) {
1537 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1538 os << "\\end{" << from_ascii(tclass.titlename())
1541 os << "\\" << from_ascii(tclass.titlename())
1546 if (maintext && !is_child && runparams.openbtUnit)
1547 os << "\\end{btUnit}\n";
1549 // if "auto end" is switched off, explicitly close the language at the end
1550 // but only if the last par is in a babel or polyglossia language
1551 Language const * const lastpar_language =
1552 paragraphs.at(lastpit).getParLanguage(bparams);
1553 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1554 lastpar_language->encoding()->package() != Encoding::CJK) {
1555 os << from_utf8(subst(lang_end_command,
1559 if (using_begin_end)
1563 // If the last paragraph is an environment, we'll have to close
1564 // CJK at the very end to do proper nesting.
1565 if (maintext && !is_child && state->open_encoding_ == CJK) {
1566 os << "\\end{CJK}\n";
1567 state->open_encoding_ = none;
1569 // Likewise for polyglossia or when using begin/end commands
1570 // or at the very end of an active branch inset with a language switch
1571 Language const * const outer_language = (runparams.local_font != 0)
1572 ? runparams.local_font->language() : bparams.language;
1573 string const & prev_lang = runparams.use_polyglossia
1574 ? getPolyglossiaEnvName(outer_language)
1575 : outer_language->babel();
1576 string const lastpar_lang = runparams.use_polyglossia ?
1577 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1578 string const & cur_lang = openLanguageName(state);
1579 if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1580 || (maintext && !is_child)) && !cur_lang.empty()) {
1581 os << from_utf8(subst(lang_end_command,
1585 if (using_begin_end)
1587 } else if (runparams.inbranch && !using_begin_end
1588 && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1589 // with !using_begin_end, cur_lang is empty, so we need to
1590 // compare against the paragraph language (and we are in the
1591 // last paragraph at this point)
1592 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1595 // reset inherited encoding
1596 if (state->cjk_inherited_ > 0) {
1597 state->cjk_inherited_ -= 1;
1598 if (state->cjk_inherited_ == 0)
1599 state->open_encoding_ = CJK;
1602 if (multibib_child && mparams.useBibtopic()) {
1603 os << "\\end{btUnit}\n";
1604 runparams.openbtUnit = false;
1609 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1610 OutputParams const & runparams, Encoding const & newEnc,
1613 // XeTeX/LuaTeX use only one encoding per document:
1614 // * with useNonTeXFonts: "utf8plain",
1615 // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1616 // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1617 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1618 return make_pair(false, 0);
1620 Encoding const & oldEnc = *runparams.encoding;
1621 bool moving_arg = runparams.moving_arg;
1622 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc,
1623 // except if we use CJKutf8
1624 bool const from_to_cjk =
1625 ((oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1626 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK))
1627 && (bparams.encoding().name() != "utf8-cjk" || !LaTeXFeatures::isAvailable("CJKutf8"));
1628 if (!force && !from_to_cjk
1629 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1630 return make_pair(false, 0);
1632 // Do nothing if the encoding is unchanged.
1633 if (oldEnc.name() == newEnc.name())
1634 return make_pair(false, 0);
1636 // FIXME We ignore encoding switches from/to encodings that do
1637 // neither support the inputenc package nor the CJK package here.
1638 // This does of course only work in special cases (e.g. switch from
1639 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1640 // but it is the best we can do
1641 if (oldEnc.package() == Encoding::none
1642 || newEnc.package() == Encoding::none)
1643 return make_pair(false, 0);
1645 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1646 << oldEnc.name() << " to " << newEnc.name());
1647 os << setEncoding(newEnc.iconvName());
1648 if (bparams.inputenc == "default")
1649 return make_pair(true, 0);
1651 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1652 OutputState * state = getOutputState();
1653 switch (newEnc.package()) {
1654 case Encoding::none:
1655 case Encoding::japanese:
1656 // shouldn't ever reach here, see above
1657 return make_pair(true, 0);
1658 case Encoding::inputenc: {
1659 int count = inputenc_arg.length();
1660 if (oldEnc.package() == Encoding::CJK &&
1661 state->open_encoding_ == CJK) {
1663 state->open_encoding_ = none;
1666 else if (oldEnc.package() == Encoding::inputenc &&
1667 state->open_encoding_ == inputenc) {
1669 state->open_encoding_ = none;
1672 if (runparams.local_font != 0
1673 && oldEnc.package() == Encoding::CJK) {
1674 // within insets, \inputenc switches need
1675 // to be embraced within \bgroup...\egroup;
1679 state->open_encoding_ = inputenc;
1681 // with the japanese option, inputenc is omitted.
1682 if (runparams.use_japanese)
1683 return make_pair(true, count);
1684 os << "\\inputencoding{" << inputenc_arg << '}';
1685 return make_pair(true, count + 16);
1687 case Encoding::CJK: {
1688 int count = inputenc_arg.length();
1689 if (oldEnc.package() == Encoding::CJK &&
1690 state->open_encoding_ == CJK) {
1694 if (oldEnc.package() == Encoding::inputenc &&
1695 state->open_encoding_ == inputenc) {
1699 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1700 && LaTeXFeatures::isAvailable("CJKutf8")) ?
1702 : from_ascii(bparams.encoding().latexName());
1703 os << "\\begin{CJK}{" << cjkenc << "}{"
1704 << from_ascii(bparams.fonts_cjk) << "}";
1705 state->open_encoding_ = CJK;
1706 return make_pair(true, count + 15);
1709 // Dead code to avoid a warning:
1710 return make_pair(true, 0);