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';
295 if (style.latextype == LATEX_BIB_ENVIRONMENT
296 || style.latextype == LATEX_ITEM_ENVIRONMENT
297 || style.latextype == LATEX_LIST_ENVIRONMENT) {
298 OutputParams rp = runparams;
299 rp.local_font = &pit->getFirstFontSettings(bparams);
300 latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
306 // in multilingual environments, the CJK tags have to be nested properly
307 data.cjk_nested = false;
308 if (data.par_language->encoding()->package() == Encoding::CJK &&
309 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
310 if (prev_par_language->encoding()->package() == Encoding::CJK) {
311 os << "\\begin{CJK}{"
312 << from_ascii(data.par_language->encoding()->latexName())
313 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
315 state->open_encoding_ = CJK;
316 data.cjk_nested = true;
322 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
323 TeXEnvironmentData const & data)
325 OutputState * state = getOutputState();
326 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
327 if (state->open_encoding_ == CJK && data.cjk_nested) {
328 // We need to close the encoding even if it does not change
329 // to do correct environment nesting
330 os << "\\end{CJK}\n";
331 state->open_encoding_ = none;
334 if (data.style->isEnvironment()) {
336 bool const using_begin_end =
337 runparams.use_polyglossia ||
338 !lyxrc.language_command_end.empty();
339 // Close any language opened at this nest level
340 if (using_begin_end) {
341 while (langOpenedAtThisLevel(state)) {
342 if (isLocalSwitch(state)) {
346 << openLanguageName(state)
352 state->nest_level_ -= 1;
353 string const & name = data.style->latexname();
355 os << "\\end{" << from_ascii(name) << "}\n";
356 state->prev_env_language_ = data.par_language;
357 if (runparams.encoding != data.prev_encoding) {
358 runparams.encoding = data.prev_encoding;
359 os << setEncoding(data.prev_encoding->iconvName());
363 if (data.leftindent_open) {
364 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
365 state->prev_env_language_ = data.par_language;
366 if (runparams.encoding != data.prev_encoding) {
367 runparams.encoding = data.prev_encoding;
368 os << setEncoding(data.prev_encoding->iconvName());
372 // Check whether we should output a blank line after the environment
373 if (!data.style->nextnoindent)
378 void TeXEnvironment(Buffer const & buf, Text const & text,
379 OutputParams const & runparams,
380 pit_type & pit, otexstream & os)
382 ParagraphList const & paragraphs = text.paragraphs();
383 ParagraphList::const_iterator ipar = paragraphs.constIterator(pit);
384 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
386 Layout const & current_layout = ipar->layout();
387 depth_type const current_depth = ipar->params().depth();
388 Length const & current_left_indent = ipar->params().leftIndent();
390 // This is for debugging purpose at the end.
391 pit_type const par_begin = pit;
392 for (; pit < runparams.par_end; ++pit) {
393 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
395 // check first if this is an higher depth paragraph.
396 bool go_out = (par->params().depth() < current_depth);
397 if (par->params().depth() == current_depth) {
398 // This environment is finished.
399 go_out |= (par->layout() != current_layout);
400 go_out |= (par->params().leftIndent() != current_left_indent);
403 // nothing to do here, restore pit and go out.
408 if (par->layout() == current_layout
409 && par->params().depth() == current_depth
410 && par->params().leftIndent() == current_left_indent) {
411 // We are still in the same environment so TeXOnePar and continue;
412 TeXOnePar(buf, text, pit, os, runparams);
416 // We are now in a deeper environment.
417 // Either par->layout() != current_layout
418 // Or par->params().depth() > current_depth
419 // Or par->params().leftIndent() != current_left_indent)
421 // FIXME This test should not be necessary.
422 // We should perhaps issue an error if it is.
423 bool const force_plain_layout = text.inset().forcePlainLayout();
424 Layout const & style = force_plain_layout
425 ? buf.params().documentClass().plainLayout()
428 if (!style.isEnvironment()) {
429 // This is a standard paragraph, no need to call TeXEnvironment.
430 TeXOnePar(buf, text, pit, os, runparams);
434 // This is a new environment.
435 TeXEnvironmentData const data =
436 prepareEnvironment(buf, text, par, os, runparams);
437 // Recursive call to TeXEnvironment!
438 TeXEnvironment(buf, text, runparams, pit, os);
439 finishEnvironment(os, runparams, data);
442 if (pit != runparams.par_end)
443 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
447 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
448 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
450 unsigned int const argnr = latexargs.size();
454 // Default and preset args are always output, so if they require
455 // other arguments, consider this.
456 for (auto const & larg : latexargs) {
457 Layout::latexarg const & arg = larg.second;
458 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
459 vector<string> req = getVectorFromString(arg.requires);
460 required.insert(required.end(), req.begin(), req.end());
464 for (unsigned int i = 1; i <= argnr; ++i) {
465 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
466 bool inserted = false;
467 if (lit != ilist.end()) {
468 InsetArgument const * ins = (*lit).second;
470 Layout::LaTeXArgMap::const_iterator const lait =
471 latexargs.find(ins->name());
472 if (lait != latexargs.end()) {
473 Layout::latexarg arg = (*lait).second;
477 ldelim = arg.mandatory ?
478 from_ascii("{") : from_ascii("[");
479 rdelim = arg.mandatory ?
480 from_ascii("}") : from_ascii("]");
482 if (!arg.ldelim.empty())
484 if (!arg.rdelim.empty())
486 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
487 if (prefix == "listpreamble:")
494 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
495 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
496 for (; lait != laend; ++lait) {
497 string const name = prefix + convert<string>(i);
498 if ((*lait).first == name) {
499 Layout::latexarg arg = (*lait).second;
500 docstring preset = arg.presetarg;
501 if (!arg.defaultarg.empty()) {
504 preset += arg.defaultarg;
507 docstring ldelim = arg.ldelim.empty() ?
508 from_ascii("{") : arg.ldelim;
509 docstring rdelim = arg.rdelim.empty() ?
510 from_ascii("}") : arg.rdelim;
511 os << ldelim << preset << rdelim;
512 } else if (!preset.empty()) {
513 docstring ldelim = arg.ldelim.empty() ?
514 from_ascii("[") : arg.ldelim;
515 docstring rdelim = arg.rdelim.empty() ?
516 from_ascii("]") : arg.rdelim;
517 os << ldelim << preset << rdelim;
518 } else if (find(required.begin(), required.end(),
519 (*lait).first) != required.end()) {
520 docstring ldelim = arg.ldelim.empty() ?
521 from_ascii("[") : arg.ldelim;
522 docstring rdelim = arg.rdelim.empty() ?
523 from_ascii("]") : arg.rdelim;
524 os << ldelim << rdelim;
531 if (runparams.for_search) {
532 // Mark end of arguments for findadv() only
533 os << "\\endarguments{}";
541 void pushLanguageName(string const & lang_name, bool localswitch)
543 OutputState * state = getOutputState();
545 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
546 state->lang_switch_depth_.push(nest_level);
547 state->open_polyglossia_lang_.push(lang_name);
551 void popLanguageName()
553 OutputState * state = getOutputState();
555 state->lang_switch_depth_.pop();
556 state->open_polyglossia_lang_.pop();
560 string const & openLanguageName()
562 OutputState * state = getOutputState();
564 return openLanguageName(state);
570 void addArgInsets(Paragraph const & par, string const & prefix,
571 Layout::LaTeXArgMap const & latexargs,
572 map<int, InsetArgument const *> & ilist,
573 vector<string> & required)
575 for (auto const & table : par.insetList()) {
576 InsetArgument const * arg = table.inset->asInsetArgument();
579 if (arg->name().empty()) {
580 LYXERR0("Error: Unnamed argument inset!");
583 string const name = prefix.empty() ?
584 arg->name() : split(arg->name(), ':');
585 // why converting into an integer?
586 unsigned int const nr = convert<unsigned int>(name);
587 if (ilist.find(nr) == ilist.end())
589 Layout::LaTeXArgMap::const_iterator const lit =
590 latexargs.find(arg->name());
591 if (lit != latexargs.end()) {
592 Layout::latexarg const & larg = lit->second;
593 vector<string> req = getVectorFromString(larg.requires);
594 move(req.begin(), req.end(), back_inserter(required));
602 void latexArgInsets(Paragraph const & par, otexstream & os,
603 OutputParams const & runparams,
604 Layout::LaTeXArgMap const & latexargs,
605 string const & prefix)
607 map<int, InsetArgument const *> ilist;
608 vector<string> required;
609 addArgInsets(par, prefix, latexargs, ilist, required);
610 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
614 void latexArgInsets(ParagraphList const & pars,
615 ParagraphList::const_iterator pit,
616 otexstream & os, OutputParams const & runparams,
617 Layout::LaTeXArgMap const & latexargs,
618 string const & prefix)
620 map<int, InsetArgument const *> ilist;
621 vector<string> required;
623 depth_type const current_depth = pit->params().depth();
624 Layout const current_layout = pit->layout();
626 // get the first paragraph in sequence with this layout and depth
629 if (lyx::prev(pit, offset) == pars.begin())
631 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
632 if (priorpit->layout() == current_layout
633 && priorpit->params().depth() == current_depth)
639 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
641 for (; spit != pars.end(); ++spit) {
642 if (spit->layout() != current_layout ||
643 spit->params().depth() < current_depth)
645 if (spit->params().depth() > current_depth)
647 addArgInsets(*spit, prefix, latexargs, ilist, required);
649 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
653 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
654 OutputParams const & runparams,
655 Layout::LaTeXArgMap const & latexargs,
656 string const & prefix)
658 map<int, InsetArgument const *> ilist;
659 vector<string> required;
661 for (Paragraph const & par : pars) {
662 if (par.layout().hasArgs())
663 // The InsetArguments inside this paragraph refer to this paragraph
665 addArgInsets(par, prefix, latexargs, ilist, required);
667 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
673 // output the proper paragraph start according to latextype.
674 void parStartCommand(Paragraph const & par, otexstream & os,
675 OutputParams const & runparams, Layout const & style)
677 switch (style.latextype) {
679 if (par.needsCProtection(runparams.moving_arg))
681 os << '\\' << from_ascii(style.latexname());
684 if (!style.latexargs().empty())
685 latexArgInsets(par, os, runparams, style.latexargs());
686 os << from_ascii(style.latexparam());
688 case LATEX_ITEM_ENVIRONMENT:
689 case LATEX_LIST_ENVIRONMENT:
690 if (runparams.for_search) {
691 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
694 os << "\\" + style.itemcommand();
696 if (!style.itemargs().empty())
697 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
701 case LATEX_ENVIRONMENT:
702 if (runparams.for_search) {
703 os << "\\latexenvironment{" << style.latexname() << "}{";
706 case LATEX_BIB_ENVIRONMENT:
707 // ignore this, the inset will write itself
716 // FIXME: this should be anonymous
717 void TeXOnePar(Buffer const & buf,
721 OutputParams const & runparams_in,
722 string const & everypar,
723 int start_pos, int end_pos,
726 BufferParams const & bparams = runparams_in.is_child
727 ? buf.masterParams() : buf.params();
728 ParagraphList const & paragraphs = text.paragraphs();
729 Paragraph const & par = paragraphs.at(pit);
730 // FIXME This check should not really be needed.
731 // Perhaps we should issue an error if it is.
732 Layout const & style = text.inset().forcePlainLayout() ?
733 bparams.documentClass().plainLayout() : par.layout();
735 if (style.inpreamble && !force)
738 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
741 OutputParams runparams = runparams_in;
742 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
743 // We reinitialze par begin and end to be on the safe side
744 // with embedded inset as we don't know if they set those
746 runparams.par_begin = 0;
747 runparams.par_end = 0;
749 bool const maintext = text.isMainText();
750 // we are at the beginning of an inset and CJK is already open;
751 // we count inheritation levels to get the inset nesting right.
752 OutputState * state = getOutputState();
753 if (pit == 0 && !maintext
754 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
755 state->cjk_inherited_ += 1;
756 state->open_encoding_ = none;
759 if (text.inset().isPassThru()) {
760 Font const outerfont = text.outerFont(pit);
762 // No newline before first paragraph in this lyxtext
765 if (!text.inset().getLayout().parbreakIsNewline())
769 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
773 Paragraph const * nextpar = runparams.isLastPar
774 ? 0 : ¶graphs.at(pit + 1);
776 bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
778 if (style.pass_thru) {
779 Font const outerfont = text.outerFont(pit);
780 parStartCommand(par, os, runparams, style);
781 if (style.isCommand() && style.needprotect)
782 // Due to the moving argument, some fragile
783 // commands (labels, index entries)
784 // are output after this command (#2154)
785 runparams.postpone_fragile_stuff = true;
789 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
791 // I did not create a parEndCommand for this minuscule
792 // task because in the other user of parStartCommand
793 // the code is different (JMarc)
794 if (style.isCommand())
798 if (!style.parbreak_is_newline) {
800 } else if (nextpar && !style.isEnvironment()) {
801 Layout const nextstyle = text.inset().forcePlainLayout()
802 ? bparams.documentClass().plainLayout()
804 if (nextstyle.name() != style.name())
811 // This paragraph's language
812 Language const * const par_language = par.getParLanguage(bparams);
813 Language const * const nextpar_language = nextpar ?
814 nextpar->getParLanguage(bparams) : 0;
815 // The document's language
816 Language const * const doc_language = bparams.language;
817 // The language that was in effect when the environment this paragraph is
818 // inside of was opened
819 Language const * const outer_language =
820 (runparams.local_font != 0) ?
821 runparams.local_font->language() : doc_language;
823 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
825 // The previous language that was in effect is the language of the
826 // previous paragraph, unless the previous paragraph is inside an
827 // environment with nesting depth greater than (or equal to, but with
828 // a different layout) the current one. If there is no previous
829 // paragraph, the previous language is the outer language.
830 // Note further that we take the outer language also if the prior par
831 // is PassThru, since in that case it has latex_language, and all secondary
832 // languages have been closed (#10793).
833 bool const use_prev_env_language = state->prev_env_language_ != 0
835 && priorpar->layout().isEnvironment()
836 && (priorpar->getDepth() > par.getDepth()
837 || (priorpar->getDepth() == par.getDepth()
838 && priorpar->layout() != par.layout()));
839 Language const * const prev_language =
840 runparams_in.for_search ?
841 languages.getLanguage("ignore")
842 :(priorpar && !priorpar->isPassThru())
843 ? (use_prev_env_language ? state->prev_env_language_
844 : priorpar->getParLanguage(bparams))
847 bool const use_polyglossia = runparams.use_polyglossia;
848 string const par_lang = use_polyglossia ?
849 getPolyglossiaEnvName(par_language): par_language->babel();
850 string const prev_lang = use_polyglossia ?
851 getPolyglossiaEnvName(prev_language) : prev_language->babel();
852 string const outer_lang = use_polyglossia ?
853 getPolyglossiaEnvName(outer_language) : outer_language->babel();
854 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
855 getPolyglossiaEnvName(nextpar_language) :
856 nextpar_language->babel()) : string();
857 string lang_begin_command = use_polyglossia ?
858 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
859 string lang_end_command = use_polyglossia ?
860 "\\end{$$lang}" : lyxrc.language_command_end;
861 // the '%' is necessary to prevent unwanted whitespace
862 string lang_command_termination = "%\n";
863 bool const using_begin_end = use_polyglossia ||
864 !lang_end_command.empty();
866 // For InTitle commands, we need to switch the language inside the command
867 // (see #10849); thus open the command here.
868 if (intitle_command) {
869 parStartCommand(par, os, runparams, style);
870 if (style.isCommand() && style.needprotect)
871 // Due to the moving argument, some fragile
872 // commands (labels, index entries)
873 // are output after this command (#2154)
874 runparams.postpone_fragile_stuff = true;
878 // In some insets (such as Arguments), we cannot use \selectlanguage.
879 // Also, if an RTL language is set via environment in polyglossia,
880 // only a nested \\text<lang> command will reset the direction for LTR
881 // languages (see # 10111).
882 bool const in_polyglossia_rtl_env =
884 && runparams.local_font != 0
885 && outer_language->rightToLeft()
886 && !par_language->rightToLeft();
887 bool const localswitch = runparams_in.for_search
888 || text.inset().forceLocalFontSwitch()
889 || (using_begin_end && text.inset().forcePlainLayout())
890 || in_polyglossia_rtl_env;
892 lang_begin_command = use_polyglossia ?
893 "\\text$$lang$$opts{" : lyxrc.language_command_local;
894 lang_end_command = "}";
895 lang_command_termination.clear();
898 bool const localswitch_needed = localswitch && par_lang != outer_lang;
900 // localswitches need to be closed and reopened at each par
901 if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
902 // check if we already put language command in TeXEnvironment()
903 && !(style.isEnvironment()
904 && (pit == 0 || (priorpar->layout() != par.layout()
905 && priorpar->getDepth() <= par.getDepth())
906 || priorpar->getDepth() < par.getDepth())))) {
908 && (!using_begin_end || langOpenedAtThisLevel(state))
909 && !lang_end_command.empty()
910 && prev_lang != outer_lang
911 && !prev_lang.empty()
912 && (!using_begin_end || !style.isEnvironment())) {
913 os << from_ascii(subst(lang_end_command,
916 << lang_command_termination;
921 // We need to open a new language if we couldn't close the previous
922 // one (because there's no language_command_end); and even if we closed
923 // the previous one, if the current language is different than the
924 // outer_language (which is currently in effect once the previous one
926 if ((lang_end_command.empty() || par_lang != outer_lang
928 || (style.isEnvironment() && par_lang != prev_lang)))
929 && !par_lang.empty()) {
930 // If we're inside an inset, and that inset is within an \L or \R
931 // (or equivalents), then within the inset, too, any opposite
932 // language paragraph should appear within an \L or \R (in addition
933 // to, outside of, the normal language switch commands).
934 // This behavior is not correct for ArabTeX, though.
937 && par_language->lang() != "arabic_arabtex"
938 && outer_language->lang() != "arabic_arabtex"
939 // are we in an inset?
940 && runparams.local_font != 0
941 // is the inset within an \L or \R?
943 // FIXME: currently, we don't check this; this means that
944 // we'll have unnnecessary \L and \R commands, but that
945 // doesn't seem to hurt (though latex will complain)
947 // is this paragraph in the opposite direction?
948 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
949 // FIXME: I don't have a working copy of the Arabi package, so
950 // I'm not sure if the farsi and arabic_arabi stuff is correct
952 if (par_language->lang() == "farsi")
954 else if (outer_language->lang() == "farsi")
956 else if (par_language->lang() == "arabic_arabi")
958 else if (outer_language->lang() == "arabic_arabi")
960 // remaining RTL languages currently is hebrew
961 else if (par_language->rightToLeft())
966 // With CJK, the CJK tag has to be closed first (see below)
967 if ((runparams.encoding->package() != Encoding::CJK || runparams.for_search)
968 && (par_lang != openLanguageName(state) || localswitch)
969 && !par_lang.empty()) {
970 string bc = use_polyglossia ?
971 getPolyglossiaBegin(lang_begin_command, par_lang,
972 par_language->polyglossiaOpts(),
974 : subst(lang_begin_command, "$$lang", par_lang);
976 os << lang_command_termination;
978 pushLanguageName(par_lang, localswitch);
983 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
984 // encoding, since this only affects the position of the outputted
985 // \inputencoding command; the encoding switch will occur when necessary
986 if (bparams.inputenc == "auto-legacy"
987 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
988 && runparams.encoding->package() != Encoding::japanese
989 && runparams.encoding->package() != Encoding::none) {
990 // Look ahead for future encoding changes.
991 // We try to output them at the beginning of the paragraph,
992 // since the \inputencoding command is not allowed e.g. in
993 // sections. For this reason we only set runparams.moving_arg
994 // after checking for the encoding change, otherwise the
995 // change would be always avoided by switchEncoding().
996 for (pos_type i = 0; i < par.size(); ++i) {
997 char_type const c = par.getChar(i);
998 Encoding const * const encoding =
999 par.getFontSettings(bparams, i).language()->encoding();
1000 if (encoding->package() != Encoding::CJK
1001 && runparams.encoding->package() == Encoding::inputenc
1006 // All characters before c are in the ASCII range, and
1007 // c is non-ASCII (but no inset), so change the
1008 // encoding to that required by the language of c.
1009 // With CJK, only add switch if we have CJK content at the beginning
1011 if (i != 0 && encoding->package() == Encoding::CJK)
1014 pair<bool, int> enc_switch = switchEncoding(os.os(),
1015 bparams, runparams, *encoding);
1016 // the following is necessary after a CJK environment in a multilingual
1017 // context (nesting issue).
1018 if (par_language->encoding()->package() == Encoding::CJK
1019 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1020 os << "\\begin{CJK}{"
1021 << from_ascii(par_language->encoding()->latexName())
1022 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1023 state->open_encoding_ = CJK;
1025 if (encoding->package() != Encoding::none && enc_switch.first) {
1026 if (enc_switch.second > 0) {
1027 // the '%' is necessary to prevent unwanted whitespace
1030 // With CJK, the CJK tag had to be closed first (see above)
1031 if (runparams.encoding->package() == Encoding::CJK
1032 && par_lang != openLanguageName(state)
1033 && !par_lang.empty()) {
1034 string bc = use_polyglossia ?
1035 getPolyglossiaBegin(lang_begin_command, par_lang,
1036 par_language->polyglossiaOpts(),
1038 : subst(lang_begin_command, "$$lang", par_lang);
1040 << lang_command_termination;
1041 if (using_begin_end)
1042 pushLanguageName(par_lang, localswitch);
1044 runparams.encoding = encoding;
1050 runparams.moving_arg |= style.needprotect;
1051 if (style.needmboxprotect)
1052 ++runparams.inulemcmd;
1053 Encoding const * const prev_encoding = runparams.encoding;
1055 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1056 if (par.allowParagraphCustomization()) {
1057 if (par.params().startOfAppendix()) {
1058 os << "\n\\appendix\n";
1061 // InTitle commands must use switches (not environments)
1062 // inside the commands (see #9332)
1063 if (style.intitle) {
1064 if (!par.params().spacing().isDefault())
1066 if (runparams.moving_arg)
1068 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1071 if (!par.params().spacing().isDefault()
1072 && (pit == 0 || !priorpar->hasSameLayout(par)))
1074 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1078 if (style.isCommand()) {
1084 // For InTitle commands, we already started the command before
1085 // the language switch
1086 if (!intitle_command) {
1087 parStartCommand(par, os, runparams, style);
1088 if (style.isCommand() && style.needprotect)
1089 // Due to the moving argument, some fragile
1090 // commands (labels, index entries)
1091 // are output after this command (#2154)
1092 runparams.postpone_fragile_stuff = true;
1095 Font const outerfont = text.outerFont(pit);
1098 os << from_utf8(everypar);
1099 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1101 Font const font = par.empty()
1102 ? par.getLayoutFont(bparams, outerfont)
1103 : par.getFont(bparams, par.size() - 1, outerfont);
1105 bool const is_command = style.isCommand();
1107 // InTitle commands need to be closed after the language has been closed.
1108 if (!intitle_command) {
1111 if (!style.postcommandargs().empty())
1112 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1113 if (!runparams.post_macro.empty()) {
1114 // Output the stored fragile commands (labels, indices etc.)
1115 // that need to be output after the command with moving argument.
1116 os << runparams.post_macro;
1117 runparams.post_macro.clear();
1119 if (runparams.encoding != prev_encoding) {
1120 runparams.encoding = prev_encoding;
1121 os << setEncoding(prev_encoding->iconvName());
1126 bool pending_newline = false;
1127 bool unskip_newline = false;
1128 bool close_lang_switch = false;
1129 switch (style.latextype) {
1130 case LATEX_ITEM_ENVIRONMENT:
1131 case LATEX_LIST_ENVIRONMENT:
1132 if ((nextpar && par_lang != nextpar_lang
1133 && nextpar->getDepth() == par.getDepth())
1134 || (atSameLastLangSwitchDepth(state) && nextpar
1135 && nextpar->getDepth() < par.getDepth()))
1136 close_lang_switch = using_begin_end;
1137 if (nextpar && par.params().depth() < nextpar->params().depth())
1138 pending_newline = true;
1140 case LATEX_ENVIRONMENT: {
1141 // if it's the last paragraph of the current environment
1142 // skip it otherwise fall through
1144 && ((nextpar->layout() != par.layout()
1145 || nextpar->params().depth() != par.params().depth())
1146 || (!using_begin_end || par_lang != nextpar_lang)))
1148 close_lang_switch = using_begin_end;
1155 // we don't need it for the last paragraph and in InTitle commands!!!
1156 if (nextpar && !intitle_command)
1157 pending_newline = true;
1160 // InTitle commands use switches (not environments) for space settings
1161 if (par.allowParagraphCustomization() && !style.intitle) {
1162 if (!par.params().spacing().isDefault()
1163 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1164 if (pending_newline)
1167 string const endtag =
1168 par.params().spacing().writeEnvirEnd(useSetSpace);
1169 if (prefixIs(endtag, "\\end{"))
1172 os << from_ascii(endtag);
1173 pending_newline = true;
1177 // Closing the language is needed for the last paragraph in a given language
1178 // as well as for any InTitleCommand (since these set the language locally);
1179 // it is also needed if we're within an \L or \R that we may have opened above
1180 // (not necessarily in this paragraph) and are about to close.
1181 bool closing_rtl_ltr_environment = !using_begin_end
1183 && (par_language->lang() != "arabic_arabtex"
1184 && outer_language->lang() != "arabic_arabtex")
1185 // have we opened an \L or \R environment?
1186 && runparams.local_font != 0
1187 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1188 // are we about to close the language?
1189 &&((nextpar && par_lang != nextpar_lang)
1190 || (runparams.isLastPar && par_lang != outer_lang));
1192 if (localswitch_needed
1193 || (intitle_command && using_begin_end)
1194 || closing_rtl_ltr_environment
1195 || ((runparams.isLastPar || close_lang_switch)
1196 && (par_lang != outer_lang || (using_begin_end
1197 && style.isEnvironment()
1198 && par_lang != nextpar_lang)))) {
1199 // Since \selectlanguage write the language to the aux file,
1200 // we need to reset the language at the end of footnote or
1203 if (!localswitch && (pending_newline || close_lang_switch))
1206 // when the paragraph uses CJK, the language has to be closed earlier
1207 if ((font.language()->encoding()->package() != Encoding::CJK) || runparams_in.for_search) {
1208 if (lang_end_command.empty()) {
1209 // If this is a child, we should restore the
1210 // master language after the last paragraph.
1211 Language const * const current_language =
1212 (runparams.isLastPar && runparams.master_language)
1213 ? runparams.master_language
1215 string const current_lang = use_polyglossia
1216 ? getPolyglossiaEnvName(current_language)
1217 : current_language->babel();
1218 if (!current_lang.empty()
1219 && current_lang != openLanguageName(state)) {
1220 string bc = use_polyglossia ?
1221 getPolyglossiaBegin(lang_begin_command, current_lang,
1222 current_language->polyglossiaOpts(),
1224 : subst(lang_begin_command, "$$lang", current_lang);
1226 pending_newline = !localswitch;
1227 unskip_newline = !localswitch;
1228 if (using_begin_end)
1229 pushLanguageName(current_lang, localswitch);
1231 } else if ((!using_begin_end ||
1232 langOpenedAtThisLevel(state)) &&
1233 !par_lang.empty()) {
1234 // If we are in an environment, we have to
1235 // close the "outer" language afterwards
1236 string const & cur_lang = openLanguageName(state);
1237 if (!style.isEnvironment()
1238 || (close_lang_switch
1239 && atSameLastLangSwitchDepth(state)
1240 && par_lang != outer_lang
1241 && (par_lang != cur_lang
1242 || (cur_lang != outer_lang
1244 && style != nextpar->layout())))
1245 || (atSameLastLangSwitchDepth(state)
1246 && state->lang_switch_depth_.size()
1247 && cur_lang != par_lang)
1248 || in_polyglossia_rtl_env)
1250 if (using_begin_end && !localswitch)
1252 os << from_ascii(subst(
1256 pending_newline = !localswitch;
1257 unskip_newline = !localswitch;
1258 if (using_begin_end)
1264 if (closing_rtl_ltr_environment)
1267 // InTitle commands need to be closed after the language has been closed.
1268 if (intitle_command) {
1271 if (!style.postcommandargs().empty())
1272 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1273 if (!runparams.post_macro.empty()) {
1274 // Output the stored fragile commands (labels, indices etc.)
1275 // that need to be output after the command with moving argument.
1276 os << runparams.post_macro;
1277 runparams.post_macro.clear();
1279 if (runparams.encoding != prev_encoding) {
1280 runparams.encoding = prev_encoding;
1281 os << setEncoding(prev_encoding->iconvName());
1286 bool const last_was_separator =
1287 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1289 if (pending_newline) {
1291 // prevent unwanted whitespace
1293 if (!os.afterParbreak() && !last_was_separator)
1297 // if this is a CJK-paragraph and the next isn't, close CJK
1298 // also if the next paragraph is a multilingual environment (because of nesting)
1300 && (state->open_encoding_ == CJK && bparams.encoding().iconvName() != "UTF-8"
1301 && bparams.encoding().package() != Encoding::CJK )
1302 && (nextpar_language->encoding()->package() != Encoding::CJK
1303 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1304 // inbetween environments, CJK has to be closed later (nesting!)
1305 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1306 os << "\\end{CJK}\n";
1307 state->open_encoding_ = none;
1310 // If this is the last paragraph, close the CJK environment
1311 // if necessary. If it's an environment or nested in an environment,
1312 // we'll have to \end that first.
1313 if (runparams.isLastPar && !style.isEnvironment()
1314 && par.params().depth() < 1) {
1315 switch (state->open_encoding_) {
1317 // do nothing at the end of child documents
1318 if (maintext && buf.masterBuffer() != &buf)
1320 // end of main text: also insert a \clearpage (see #5386)
1322 os << "\n\\clearpage\n\\end{CJK}\n";
1326 state->open_encoding_ = none;
1331 state->open_encoding_ = none;
1341 // Information about local language is stored as a font feature.
1342 // If this is the last paragraph of the inset and a local_font was set upon entering
1343 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1344 // ensure the encoding is set back to the default encoding of the local language.
1345 if (runparams.isLastPar && runparams_in.local_font != 0
1346 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1347 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1348 && !runparams.isFullUnicode()
1350 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1351 os << setEncoding(runparams_in.encoding->iconvName());
1353 // Otherwise, the current encoding should be set for the next paragraph.
1355 runparams_in.encoding = runparams.encoding;
1357 // Also pass the post_macros upstream
1358 runparams_in.post_macro = runparams.post_macro;
1361 // we don't need a newline for the last paragraph!!!
1362 // Note from JMarc: we will re-add a \n explicitly in
1363 // TeXEnvironment, because it is needed in this case
1364 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1365 // Make sure to start a new line
1367 Layout const & next_layout = nextpar->layout();
1368 // A newline '\n' is always output before a command,
1369 // so avoid doubling it.
1370 if (!next_layout.isCommand()) {
1371 // Here we now try to avoid spurious empty lines by
1372 // outputting a paragraph break only if: (case 1) the
1373 // paragraph style allows parbreaks and no \begin, \end
1374 // or \item tags are going to follow (i.e., if the next
1375 // isn't the first or the current isn't the last
1376 // paragraph of an environment or itemize) and the
1377 // depth and alignment of the following paragraph is
1378 // unchanged, or (case 2) the following is a
1379 // non-environment paragraph whose depth is increased
1380 // but whose alignment is unchanged, or (case 3) the
1381 // paragraph is not an environment and the next one is a
1382 // non-itemize-like env at lower depth, or (case 4) the
1383 // paragraph is a command not followed by an environment
1384 // and the alignment of the current and next paragraph
1385 // is unchanged, or (case 5) the current alignment is
1386 // changed and a standard paragraph follows.
1387 DocumentClass const & tclass = bparams.documentClass();
1388 if ((style == next_layout
1389 && !style.parbreak_is_newline
1390 && !text.inset().getLayout().parbreakIsNewline()
1391 && style.latextype != LATEX_ITEM_ENVIRONMENT
1392 && style.latextype != LATEX_LIST_ENVIRONMENT
1393 && style.align == par.getAlign()
1394 && nextpar->getDepth() == par.getDepth()
1395 && nextpar->getAlign() == par.getAlign())
1396 || (!next_layout.isEnvironment()
1397 && nextpar->getDepth() > par.getDepth()
1398 && nextpar->getAlign() == next_layout.align)
1399 || (!style.isEnvironment()
1400 && next_layout.latextype == LATEX_ENVIRONMENT
1401 && nextpar->getDepth() < par.getDepth())
1402 || (style.isCommand()
1403 && !next_layout.isEnvironment()
1404 && style.align == par.getAlign()
1405 && next_layout.align == nextpar->getAlign())
1406 || (style.align != par.getAlign()
1407 && tclass.isDefaultLayout(next_layout))) {
1413 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1414 << &par << " next " << nextpar);
1420 // LaTeX all paragraphs
1421 void latexParagraphs(Buffer const & buf,
1424 OutputParams const & runparams,
1425 string const & everypar)
1427 LASSERT(runparams.par_begin <= runparams.par_end,
1428 { os << "% LaTeX Output Error\n"; return; } );
1430 BufferParams const & bparams = buf.params();
1431 BufferParams const & mparams = buf.masterParams();
1433 bool const maintext = text.isMainText();
1434 bool const is_child = buf.masterBuffer() != &buf;
1435 bool const multibib_child = maintext && is_child
1436 && mparams.multibib == "child";
1438 if (multibib_child && mparams.useBiblatex())
1439 os << "\\newrefsection";
1440 else if (multibib_child && mparams.useBibtopic()
1441 && !buf.masterBibInfo().empty()) {
1442 os << "\\begin{btUnit}\n";
1443 runparams.openbtUnit = true;
1446 // Open a CJK environment at the beginning of the main buffer
1447 // if the document's main encoding requires the CJK package
1448 // or the document encoding is utf8 and the CJK package is required
1449 // (but not in child documents or documents using system fonts):
1450 OutputState * state = getOutputState();
1451 if (maintext && !is_child && !bparams.useNonTeXFonts
1452 && (bparams.encoding().package() == Encoding::CJK
1453 || (bparams.encoding().name() == "utf8"
1454 && runparams.use_CJK))
1456 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1457 ? from_ascii("UTF8") : from_ascii(bparams.encoding().latexName());
1458 os << "\\begin{CJK}{" << cjkenc
1459 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1460 state->open_encoding_ = CJK;
1462 // if "auto begin" is switched off, explicitly switch the
1463 // language on at start
1464 string const mainlang = runparams.use_polyglossia
1465 ? getPolyglossiaEnvName(bparams.language)
1466 : bparams.language->babel();
1467 string const lang_begin_command = runparams.use_polyglossia ?
1468 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1469 string const lang_end_command = runparams.use_polyglossia ?
1470 "\\end{$$lang}" : lyxrc.language_command_end;
1471 bool const using_begin_end = runparams.use_polyglossia ||
1472 !lang_end_command.empty();
1474 if (maintext && !lyxrc.language_auto_begin &&
1475 !mainlang.empty()) {
1477 string bc = runparams.use_polyglossia ?
1478 getPolyglossiaBegin(lang_begin_command, mainlang,
1479 bparams.language->polyglossiaOpts())
1480 : subst(lang_begin_command, "$$lang", mainlang);
1483 if (using_begin_end)
1484 pushLanguageName(mainlang);
1487 ParagraphList const & paragraphs = text.paragraphs();
1489 if (runparams.par_begin == runparams.par_end) {
1490 // The full doc will be exported but it is easier to just rely on
1491 // runparams range parameters that will be passed TeXEnvironment.
1492 runparams.par_begin = 0;
1493 runparams.par_end = paragraphs.size();
1496 pit_type pit = runparams.par_begin;
1497 // lastpit is for the language check after the loop.
1498 pit_type lastpit = pit;
1499 // variables used in the loop:
1500 bool was_title = false;
1501 bool already_title = false;
1502 DocumentClass const & tclass = bparams.documentClass();
1504 // Did we already warn about inTitle layout mixing? (we only warn once)
1505 bool gave_layout_warning = false;
1506 for (; pit < runparams.par_end; ++pit) {
1508 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1510 // FIXME This check should not be needed. We should
1511 // perhaps issue an error if it is.
1512 Layout const & layout = text.inset().forcePlainLayout() ?
1513 tclass.plainLayout() : par->layout();
1515 if (layout.intitle) {
1516 if (already_title) {
1517 if (!gave_layout_warning && !runparams.dryrun) {
1518 gave_layout_warning = true;
1519 frontend::Alert::warning(_("Error in latexParagraphs"),
1520 bformat(_("You are using at least one "
1521 "layout (%1$s) intended for the title, "
1522 "after using non-title layouts. This "
1523 "could lead to missing or incorrect output."
1526 } else if (!was_title) {
1528 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1530 << from_ascii(tclass.titlename())
1534 } else if (was_title && !already_title && !layout.inpreamble) {
1535 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1536 os << "\\end{" << from_ascii(tclass.titlename())
1540 os << "\\" << from_ascii(tclass.titlename())
1543 already_title = true;
1547 if (layout.isCommand() && !layout.latexname().empty()
1548 && layout.latexname() == bparams.multibib) {
1549 if (runparams.openbtUnit)
1550 os << "\\end{btUnit}\n";
1551 if (!bparams.useBiblatex()
1552 && !buf.masterBibInfo().empty()) {
1553 os << '\n' << "\\begin{btUnit}\n";
1554 runparams.openbtUnit = true;
1558 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1559 // This is a standard top level paragraph, TeX it and continue.
1560 TeXOnePar(buf, text, pit, os, runparams, everypar);
1564 TeXEnvironmentData const data =
1565 prepareEnvironment(buf, text, par, os, runparams);
1566 // pit can be changed in TeXEnvironment.
1567 TeXEnvironment(buf, text, runparams, pit, os);
1568 finishEnvironment(os, runparams, data);
1571 if (pit == runparams.par_end) {
1572 // Make sure that the last paragraph is
1573 // correctly terminated (because TeXOnePar does
1574 // not add a \n in this case)
1578 // It might be that we only have a title in this document
1579 if (was_title && !already_title) {
1580 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1581 os << "\\end{" << from_ascii(tclass.titlename())
1584 os << "\\" << from_ascii(tclass.titlename())
1589 if (maintext && !is_child && runparams.openbtUnit)
1590 os << "\\end{btUnit}\n";
1592 // if "auto end" is switched off, explicitly close the language at the end
1593 // but only if the last par is in a babel or polyglossia language
1594 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1595 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1596 os << from_utf8(subst(lang_end_command,
1600 if (using_begin_end)
1604 // If the last paragraph is an environment, we'll have to close
1605 // CJK at the very end to do proper nesting.
1606 if (maintext && !is_child && state->open_encoding_ == CJK) {
1607 os << "\\clearpage\n\\end{CJK}\n";
1608 state->open_encoding_ = none;
1610 // Likewise for polyglossia or when using begin/end commands
1611 string const & cur_lang = openLanguageName(state);
1612 if (maintext && !is_child && !cur_lang.empty()) {
1613 os << from_utf8(subst(lang_end_command,
1617 if (using_begin_end)
1621 // reset inherited encoding
1622 if (state->cjk_inherited_ > 0) {
1623 state->cjk_inherited_ -= 1;
1624 if (state->cjk_inherited_ == 0)
1625 state->open_encoding_ = CJK;
1628 if (multibib_child && mparams.useBibtopic()) {
1629 os << "\\end{btUnit}\n";
1630 runparams.openbtUnit = false;
1634 // Switch the input encoding for some part(s) of the document.
1635 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1636 OutputParams const & runparams, Encoding const & newEnc,
1637 bool force, bool noswitchmacro)
1639 // Never switch encoding with non-TeX fonts (always "utf8plain"),
1640 // with LuaTeX and TeX fonts (only one encoding accepted by luainputenc),
1641 // or if we're in a moving argument or inherit the outer encoding.
1642 if (bparams.useNonTeXFonts
1643 || runparams.flavor == OutputParams::LUATEX
1644 || runparams.flavor == OutputParams::DVILUATEX
1645 || newEnc.name() == "inherit")
1646 return make_pair(false, 0);
1648 // Only switch for auto-selected legacy encodings (inputenc setting
1649 // "auto-legacy" or "auto-legacy-plain").
1650 // The "listings" environment can force a switch also with other
1651 // encoding settings (it does not support variable width encodings
1652 // (utf8, jis, ...) under 8-bit latex engines).
1653 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1654 || runparams.moving_arg))
1655 return make_pair(false, 0);
1657 Encoding const & oldEnc = *runparams.encoding;
1658 // Do not switch, if the encoding is unchanged or switching is not supported.
1659 if (oldEnc.name() == newEnc.name()
1660 || oldEnc.package() == Encoding::japanese
1661 || oldEnc.package() == Encoding::none
1662 || newEnc.package() == Encoding::none
1663 || runparams.for_search)
1664 return make_pair(false, 0);
1665 // FIXME We ignore encoding switches from/to encodings that do
1666 // neither support the inputenc package nor the CJK package here.
1667 // This may fail for characters not supported by "unicodesymbols"
1668 // or for non-ASCII characters in "listings"
1669 // but it is the best we can do.
1672 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1673 << oldEnc.name() << " to " << newEnc.name());
1674 os << setEncoding(newEnc.iconvName());
1675 if (bparams.inputenc == "auto-legacy-plain")
1676 return make_pair(true, 0);
1678 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1679 OutputState * state = getOutputState();
1680 switch (newEnc.package()) {
1681 case Encoding::none:
1682 case Encoding::japanese:
1683 // shouldn't ever reach here (see above) but avoids warning.
1684 return make_pair(true, 0);
1685 case Encoding::inputenc: {
1686 int count = inputenc_arg.length();
1687 if (oldEnc.package() == Encoding::CJK &&
1688 state->open_encoding_ == CJK) {
1690 state->open_encoding_ = none;
1693 else if (oldEnc.package() == Encoding::inputenc &&
1694 state->open_encoding_ == inputenc) {
1696 state->open_encoding_ = none;
1699 if (runparams.local_font != 0
1700 && oldEnc.package() == Encoding::CJK) {
1701 // within insets, \inputenc switches need
1702 // to be embraced within \bgroup...\egroup;
1706 state->open_encoding_ = inputenc;
1709 return make_pair(true, count);
1710 os << "\\inputencoding{" << inputenc_arg << '}';
1711 return make_pair(true, count + 16);
1713 case Encoding::CJK: {
1714 int count = inputenc_arg.length();
1715 if (oldEnc.package() == Encoding::CJK &&
1716 state->open_encoding_ == CJK) {
1720 if (oldEnc.package() == Encoding::inputenc &&
1721 state->open_encoding_ == inputenc) {
1725 os << "\\begin{CJK}{"
1726 << from_ascii(newEnc.latexName()) << "}{"
1727 << from_ascii(bparams.fonts_cjk) << "}";
1728 state->open_encoding_ = CJK;
1729 return make_pair(true, count + 15);
1732 // Dead code to avoid a warning:
1733 return make_pair(true, 0);