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 (!bparams.useNonTeXFonts && (bparams.inputenc == "auto-legacy"
309 || bparams.inputenc == "auto-legacy-plain")
310 && data.par_language->encoding()->package() == Encoding::CJK
311 && state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
312 if (prev_par_language->encoding()->package() == Encoding::CJK) {
313 os << "\\begin{CJK}{"
314 << from_ascii(data.par_language->encoding()->latexName())
315 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
317 state->open_encoding_ = CJK;
318 data.cjk_nested = true;
324 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
325 TeXEnvironmentData const & data)
327 OutputState * state = getOutputState();
328 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
329 if (state->open_encoding_ == CJK && data.cjk_nested) {
330 // We need to close the encoding even if it does not change
331 // to do correct environment nesting
332 os << "\\end{CJK}\n";
333 state->open_encoding_ = none;
336 if (data.style->isEnvironment()) {
338 bool const using_begin_end =
339 runparams.use_polyglossia ||
340 !lyxrc.language_command_end.empty();
341 // Close any language opened at this nest level
342 if (using_begin_end) {
343 while (langOpenedAtThisLevel(state)) {
344 if (isLocalSwitch(state)) {
348 << openLanguageName(state)
354 state->nest_level_ -= 1;
355 string const & name = data.style->latexname();
357 os << "\\end{" << from_ascii(name) << "}\n";
358 state->prev_env_language_ = data.par_language;
359 if (runparams.encoding != data.prev_encoding) {
360 runparams.encoding = data.prev_encoding;
361 os << setEncoding(data.prev_encoding->iconvName());
365 if (data.leftindent_open) {
366 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
367 state->prev_env_language_ = data.par_language;
368 if (runparams.encoding != data.prev_encoding) {
369 runparams.encoding = data.prev_encoding;
370 os << setEncoding(data.prev_encoding->iconvName());
374 // Check whether we should output a blank line after the environment
375 if (!data.style->nextnoindent)
380 void TeXEnvironment(Buffer const & buf, Text const & text,
381 OutputParams const & runparams,
382 pit_type & pit, otexstream & os)
384 ParagraphList const & paragraphs = text.paragraphs();
385 ParagraphList::const_iterator ipar = paragraphs.constIterator(pit);
386 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
388 Layout const & current_layout = ipar->layout();
389 depth_type const current_depth = ipar->params().depth();
390 Length const & current_left_indent = ipar->params().leftIndent();
392 // This is for debugging purpose at the end.
393 pit_type const par_begin = pit;
394 for (; pit < runparams.par_end; ++pit) {
395 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
397 // check first if this is an higher depth paragraph.
398 bool go_out = (par->params().depth() < current_depth);
399 if (par->params().depth() == current_depth) {
400 // This environment is finished.
401 go_out |= (par->layout() != current_layout);
402 go_out |= (par->params().leftIndent() != current_left_indent);
405 // nothing to do here, restore pit and go out.
410 if (par->layout() == current_layout
411 && par->params().depth() == current_depth
412 && par->params().leftIndent() == current_left_indent) {
413 // We are still in the same environment so TeXOnePar and continue;
414 TeXOnePar(buf, text, pit, os, runparams);
418 // We are now in a deeper environment.
419 // Either par->layout() != current_layout
420 // Or par->params().depth() > current_depth
421 // Or par->params().leftIndent() != current_left_indent)
423 // FIXME This test should not be necessary.
424 // We should perhaps issue an error if it is.
425 bool const force_plain_layout = text.inset().forcePlainLayout();
426 Layout const & style = force_plain_layout
427 ? buf.params().documentClass().plainLayout()
430 if (!style.isEnvironment()) {
431 // This is a standard paragraph, no need to call TeXEnvironment.
432 TeXOnePar(buf, text, pit, os, runparams);
436 // This is a new environment.
437 TeXEnvironmentData const data =
438 prepareEnvironment(buf, text, par, os, runparams);
439 // Recursive call to TeXEnvironment!
440 TeXEnvironment(buf, text, runparams, pit, os);
441 finishEnvironment(os, runparams, data);
444 if (pit != runparams.par_end)
445 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
449 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
450 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
452 unsigned int const argnr = latexargs.size();
456 // Default and preset args are always output, so if they require
457 // other arguments, consider this.
458 for (auto const & larg : latexargs) {
459 Layout::latexarg const & arg = larg.second;
460 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
461 vector<string> req = getVectorFromString(arg.requires);
462 required.insert(required.end(), req.begin(), req.end());
466 for (unsigned int i = 1; i <= argnr; ++i) {
467 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
468 bool inserted = false;
469 if (lit != ilist.end()) {
470 InsetArgument const * ins = (*lit).second;
472 Layout::LaTeXArgMap::const_iterator const lait =
473 latexargs.find(ins->name());
474 if (lait != latexargs.end()) {
475 Layout::latexarg arg = (*lait).second;
479 ldelim = arg.mandatory ?
480 from_ascii("{") : from_ascii("[");
481 rdelim = arg.mandatory ?
482 from_ascii("}") : from_ascii("]");
484 if (!arg.ldelim.empty())
486 if (!arg.rdelim.empty())
488 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
489 if (prefix == "listpreamble:")
496 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
497 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
498 for (; lait != laend; ++lait) {
499 string const name = prefix + convert<string>(i);
500 if ((*lait).first == name) {
501 Layout::latexarg arg = (*lait).second;
502 docstring preset = arg.presetarg;
503 if (!arg.defaultarg.empty()) {
506 preset += arg.defaultarg;
509 docstring ldelim = arg.ldelim.empty() ?
510 from_ascii("{") : arg.ldelim;
511 docstring rdelim = arg.rdelim.empty() ?
512 from_ascii("}") : arg.rdelim;
513 os << ldelim << preset << rdelim;
514 } else if (!preset.empty()) {
515 docstring ldelim = arg.ldelim.empty() ?
516 from_ascii("[") : arg.ldelim;
517 docstring rdelim = arg.rdelim.empty() ?
518 from_ascii("]") : arg.rdelim;
519 os << ldelim << preset << rdelim;
520 } else if (find(required.begin(), required.end(),
521 (*lait).first) != required.end()) {
522 docstring ldelim = arg.ldelim.empty() ?
523 from_ascii("[") : arg.ldelim;
524 docstring rdelim = arg.rdelim.empty() ?
525 from_ascii("]") : arg.rdelim;
526 os << ldelim << rdelim;
533 if (runparams.for_search) {
534 // Mark end of arguments for findadv() only
535 os << "\\endarguments{}";
543 void pushLanguageName(string const & lang_name, bool localswitch)
545 OutputState * state = getOutputState();
547 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
548 state->lang_switch_depth_.push(nest_level);
549 state->open_polyglossia_lang_.push(lang_name);
553 void popLanguageName()
555 OutputState * state = getOutputState();
557 state->lang_switch_depth_.pop();
558 state->open_polyglossia_lang_.pop();
562 string const & openLanguageName()
564 OutputState * state = getOutputState();
566 return openLanguageName(state);
572 void addArgInsets(Paragraph const & par, string const & prefix,
573 Layout::LaTeXArgMap const & latexargs,
574 map<int, InsetArgument const *> & ilist,
575 vector<string> & required)
577 for (auto const & table : par.insetList()) {
578 InsetArgument const * arg = table.inset->asInsetArgument();
581 if (arg->name().empty()) {
582 LYXERR0("Error: Unnamed argument inset!");
585 string const name = prefix.empty() ?
586 arg->name() : split(arg->name(), ':');
587 // why converting into an integer?
588 unsigned int const nr = convert<unsigned int>(name);
589 if (ilist.find(nr) == ilist.end())
591 Layout::LaTeXArgMap::const_iterator const lit =
592 latexargs.find(arg->name());
593 if (lit != latexargs.end()) {
594 Layout::latexarg const & larg = lit->second;
595 vector<string> req = getVectorFromString(larg.requires);
596 move(req.begin(), req.end(), back_inserter(required));
604 void latexArgInsets(Paragraph const & par, otexstream & os,
605 OutputParams const & runparams,
606 Layout::LaTeXArgMap const & latexargs,
607 string const & prefix)
609 map<int, InsetArgument const *> ilist;
610 vector<string> required;
611 addArgInsets(par, prefix, latexargs, ilist, required);
612 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
616 void latexArgInsets(ParagraphList const & pars,
617 ParagraphList::const_iterator pit,
618 otexstream & os, OutputParams const & runparams,
619 Layout::LaTeXArgMap const & latexargs,
620 string const & prefix)
622 map<int, InsetArgument const *> ilist;
623 vector<string> required;
625 depth_type const current_depth = pit->params().depth();
626 Layout const current_layout = pit->layout();
628 // get the first paragraph in sequence with this layout and depth
631 if (lyx::prev(pit, offset) == pars.begin())
633 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
634 if (priorpit->layout() == current_layout
635 && priorpit->params().depth() == current_depth)
641 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
643 for (; spit != pars.end(); ++spit) {
644 if (spit->layout() != current_layout ||
645 spit->params().depth() < current_depth)
647 if (spit->params().depth() > current_depth)
649 addArgInsets(*spit, prefix, latexargs, ilist, required);
651 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
655 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
656 OutputParams const & runparams,
657 Layout::LaTeXArgMap const & latexargs,
658 string const & prefix)
660 map<int, InsetArgument const *> ilist;
661 vector<string> required;
663 for (Paragraph const & par : pars) {
664 if (par.layout().hasArgs())
665 // The InsetArguments inside this paragraph refer to this paragraph
667 addArgInsets(par, prefix, latexargs, ilist, required);
669 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
675 // output the proper paragraph start according to latextype.
676 void parStartCommand(Paragraph const & par, otexstream & os,
677 OutputParams const & runparams, Layout const & style)
679 switch (style.latextype) {
681 if (par.needsCProtection(runparams.moving_arg))
683 os << '\\' << from_ascii(style.latexname());
686 if (!style.latexargs().empty())
687 latexArgInsets(par, os, runparams, style.latexargs());
688 os << from_ascii(style.latexparam());
690 case LATEX_ITEM_ENVIRONMENT:
691 case LATEX_LIST_ENVIRONMENT:
692 if (runparams.for_search) {
693 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
696 os << "\\" + style.itemcommand();
698 if (!style.itemargs().empty())
699 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
703 case LATEX_ENVIRONMENT:
704 if (runparams.for_search) {
705 os << "\\latexenvironment{" << style.latexname() << "}{";
708 case LATEX_BIB_ENVIRONMENT:
709 // ignore this, the inset will write itself
718 // FIXME: this should be anonymous
719 void TeXOnePar(Buffer const & buf,
723 OutputParams const & runparams_in,
724 string const & everypar,
725 int start_pos, int end_pos,
728 BufferParams const & bparams = runparams_in.is_child
729 ? buf.masterParams() : buf.params();
730 ParagraphList const & paragraphs = text.paragraphs();
731 Paragraph const & par = paragraphs.at(pit);
732 // FIXME This check should not really be needed.
733 // Perhaps we should issue an error if it is.
734 Layout const & style = text.inset().forcePlainLayout() ?
735 bparams.documentClass().plainLayout() : par.layout();
737 if (style.inpreamble && !force)
740 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
743 OutputParams runparams = runparams_in;
744 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
745 // We reinitialze par begin and end to be on the safe side
746 // with embedded inset as we don't know if they set those
748 runparams.par_begin = 0;
749 runparams.par_end = 0;
751 bool const maintext = text.isMainText();
752 // we are at the beginning of an inset and CJK is already open;
753 // we count inheritation levels to get the inset nesting right.
754 OutputState * state = getOutputState();
755 if (pit == 0 && !maintext
756 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
757 state->cjk_inherited_ += 1;
758 state->open_encoding_ = none;
761 if (text.inset().isPassThru()) {
762 Font const outerfont = text.outerFont(pit);
764 // No newline before first paragraph in this lyxtext
767 if (!text.inset().getLayout().parbreakIsNewline())
771 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
775 Paragraph const * nextpar = runparams.isLastPar
776 ? 0 : ¶graphs.at(pit + 1);
778 bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
780 if (style.pass_thru) {
781 Font const outerfont = text.outerFont(pit);
782 parStartCommand(par, os, runparams, style);
783 if (style.isCommand() && style.needprotect)
784 // Due to the moving argument, some fragile
785 // commands (labels, index entries)
786 // are output after this command (#2154)
787 runparams.postpone_fragile_stuff = true;
791 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
793 // I did not create a parEndCommand for this minuscule
794 // task because in the other user of parStartCommand
795 // the code is different (JMarc)
796 if (style.isCommand())
800 if (!style.parbreak_is_newline) {
802 } else if (nextpar && !style.isEnvironment()) {
803 Layout const nextstyle = text.inset().forcePlainLayout()
804 ? bparams.documentClass().plainLayout()
806 if (nextstyle.name() != style.name())
813 // This paragraph's language
814 Language const * const par_language = par.getParLanguage(bparams);
815 Language const * const nextpar_language = nextpar ?
816 nextpar->getParLanguage(bparams) : 0;
817 // The document's language
818 Language const * const doc_language = bparams.language;
819 // The language that was in effect when the environment this paragraph is
820 // inside of was opened
821 Language const * const outer_language =
822 (runparams.local_font != 0) ?
823 runparams.local_font->language() : doc_language;
825 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
827 // The previous language that was in effect is the language of the
828 // previous paragraph, unless the previous paragraph is inside an
829 // environment with nesting depth greater than (or equal to, but with
830 // a different layout) the current one. If there is no previous
831 // paragraph, the previous language is the outer language.
832 // Note further that we take the outer language also if the prior par
833 // is PassThru, since in that case it has latex_language, and all secondary
834 // languages have been closed (#10793).
835 bool const use_prev_env_language = state->prev_env_language_ != 0
837 && priorpar->layout().isEnvironment()
838 && (priorpar->getDepth() > par.getDepth()
839 || (priorpar->getDepth() == par.getDepth()
840 && priorpar->layout() != par.layout()));
841 Language const * const prev_language =
842 runparams_in.for_search ?
843 languages.getLanguage("ignore")
844 :(priorpar && !priorpar->isPassThru())
845 ? (use_prev_env_language ? state->prev_env_language_
846 : priorpar->getParLanguage(bparams))
849 bool const use_polyglossia = runparams.use_polyglossia;
850 string const par_lang = use_polyglossia ?
851 getPolyglossiaEnvName(par_language): par_language->babel();
852 string const prev_lang = use_polyglossia ?
853 getPolyglossiaEnvName(prev_language) : prev_language->babel();
854 string const outer_lang = use_polyglossia ?
855 getPolyglossiaEnvName(outer_language) : outer_language->babel();
856 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
857 getPolyglossiaEnvName(nextpar_language) :
858 nextpar_language->babel()) : string();
859 string lang_begin_command = use_polyglossia ?
860 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
861 string lang_end_command = use_polyglossia ?
862 "\\end{$$lang}" : lyxrc.language_command_end;
863 // the '%' is necessary to prevent unwanted whitespace
864 string lang_command_termination = "%\n";
865 bool const using_begin_end = use_polyglossia ||
866 !lang_end_command.empty();
868 // For InTitle commands, we need to switch the language inside the command
869 // (see #10849); thus open the command here.
870 if (intitle_command) {
871 parStartCommand(par, os, runparams, style);
872 if (style.isCommand() && style.needprotect)
873 // Due to the moving argument, some fragile
874 // commands (labels, index entries)
875 // are output after this command (#2154)
876 runparams.postpone_fragile_stuff = true;
880 // In some insets (such as Arguments), we cannot use \selectlanguage.
881 // Also, if an RTL language is set via environment in polyglossia,
882 // only a nested \\text<lang> command will reset the direction for LTR
883 // languages (see # 10111).
884 bool const in_polyglossia_rtl_env =
886 && runparams.local_font != 0
887 && outer_language->rightToLeft()
888 && !par_language->rightToLeft();
889 bool const localswitch = runparams_in.for_search
890 || text.inset().forceLocalFontSwitch()
891 || (using_begin_end && text.inset().forcePlainLayout())
892 || in_polyglossia_rtl_env;
894 lang_begin_command = use_polyglossia ?
895 "\\text$$lang$$opts{" : lyxrc.language_command_local;
896 lang_end_command = "}";
897 lang_command_termination.clear();
900 bool const localswitch_needed = localswitch && par_lang != outer_lang;
902 // localswitches need to be closed and reopened at each par
903 if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
904 // check if we already put language command in TeXEnvironment()
905 && !(style.isEnvironment()
906 && (pit == 0 || (priorpar->layout() != par.layout()
907 && priorpar->getDepth() <= par.getDepth())
908 || priorpar->getDepth() < par.getDepth())))) {
910 && (!using_begin_end || langOpenedAtThisLevel(state))
911 && !lang_end_command.empty()
912 && prev_lang != outer_lang
913 && !prev_lang.empty()
914 && (!using_begin_end || !style.isEnvironment())) {
915 os << from_ascii(subst(lang_end_command,
918 << lang_command_termination;
923 // We need to open a new language if we couldn't close the previous
924 // one (because there's no language_command_end); and even if we closed
925 // the previous one, if the current language is different than the
926 // outer_language (which is currently in effect once the previous one
928 if ((lang_end_command.empty() || par_lang != outer_lang
930 || (style.isEnvironment() && par_lang != prev_lang)))
931 && !par_lang.empty()) {
932 // If we're inside an inset, and that inset is within an \L or \R
933 // (or equivalents), then within the inset, too, any opposite
934 // language paragraph should appear within an \L or \R (in addition
935 // to, outside of, the normal language switch commands).
936 // This behavior is not correct for ArabTeX, though.
939 && par_language->lang() != "arabic_arabtex"
940 && outer_language->lang() != "arabic_arabtex"
941 // are we in an inset?
942 && runparams.local_font != 0
943 // is the inset within an \L or \R?
945 // FIXME: currently, we don't check this; this means that
946 // we'll have unnnecessary \L and \R commands, but that
947 // doesn't seem to hurt (though latex will complain)
949 // is this paragraph in the opposite direction?
950 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
951 // FIXME: I don't have a working copy of the Arabi package, so
952 // I'm not sure if the farsi and arabic_arabi stuff is correct
954 if (par_language->lang() == "farsi")
956 else if (outer_language->lang() == "farsi")
958 else if (par_language->lang() == "arabic_arabi")
960 else if (outer_language->lang() == "arabic_arabi")
962 // remaining RTL languages currently is hebrew
963 else if (par_language->rightToLeft())
968 // With CJK, the CJK tag has to be closed first (see below)
969 if ((runparams.encoding->package() != Encoding::CJK || runparams.for_search)
970 && (par_lang != openLanguageName(state) || localswitch)
971 && !par_lang.empty()) {
972 string bc = use_polyglossia ?
973 getPolyglossiaBegin(lang_begin_command, par_lang,
974 par_language->polyglossiaOpts(),
976 : subst(lang_begin_command, "$$lang", par_lang);
978 os << lang_command_termination;
980 pushLanguageName(par_lang, localswitch);
985 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
986 // encoding, since this only affects the position of the outputted
987 // \inputencoding command; the encoding switch will occur when necessary
988 if (bparams.inputenc == "auto-legacy"
989 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
990 && runparams.encoding->package() != Encoding::japanese
991 && runparams.encoding->package() != Encoding::none) {
992 // Look ahead for future encoding changes.
993 // We try to output them at the beginning of the paragraph,
994 // since the \inputencoding command is not allowed e.g. in
995 // sections. For this reason we only set runparams.moving_arg
996 // after checking for the encoding change, otherwise the
997 // change would be always avoided by switchEncoding().
998 for (pos_type i = 0; i < par.size(); ++i) {
999 char_type const c = par.getChar(i);
1000 Encoding const * const encoding =
1001 par.getFontSettings(bparams, i).language()->encoding();
1002 if (encoding->package() != Encoding::CJK
1003 && runparams.encoding->package() == Encoding::inputenc
1008 // All characters before c are in the ASCII range, and
1009 // c is non-ASCII (but no inset), so change the
1010 // encoding to that required by the language of c.
1011 // With CJK, only add switch if we have CJK content at the beginning
1013 if (i != 0 && encoding->package() == Encoding::CJK)
1016 pair<bool, int> enc_switch = switchEncoding(os.os(),
1017 bparams, runparams, *encoding);
1018 // the following is necessary after a CJK environment in a multilingual
1019 // context (nesting issue).
1020 if (par_language->encoding()->package() == Encoding::CJK
1021 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1022 os << "\\begin{CJK}{"
1023 << from_ascii(par_language->encoding()->latexName())
1024 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1025 state->open_encoding_ = CJK;
1027 if (encoding->package() != Encoding::none && enc_switch.first) {
1028 if (enc_switch.second > 0) {
1029 // the '%' is necessary to prevent unwanted whitespace
1032 // With CJK, the CJK tag had to be closed first (see above)
1033 if (runparams.encoding->package() == Encoding::CJK
1034 && par_lang != openLanguageName(state)
1035 && !par_lang.empty()) {
1036 string bc = use_polyglossia ?
1037 getPolyglossiaBegin(lang_begin_command, par_lang,
1038 par_language->polyglossiaOpts(),
1040 : subst(lang_begin_command, "$$lang", par_lang);
1042 << lang_command_termination;
1043 if (using_begin_end)
1044 pushLanguageName(par_lang, localswitch);
1046 runparams.encoding = encoding;
1052 runparams.moving_arg |= style.needprotect;
1053 if (style.needmboxprotect)
1054 ++runparams.inulemcmd;
1055 Encoding const * const prev_encoding = runparams.encoding;
1057 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1058 if (par.allowParagraphCustomization()) {
1059 if (par.params().startOfAppendix()) {
1060 os << "\n\\appendix\n";
1063 // InTitle commands must use switches (not environments)
1064 // inside the commands (see #9332)
1065 if (style.intitle) {
1066 if (!par.params().spacing().isDefault())
1068 if (runparams.moving_arg)
1070 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1073 if (!par.params().spacing().isDefault()
1074 && (pit == 0 || !priorpar->hasSameLayout(par)))
1076 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1080 if (style.isCommand()) {
1086 // For InTitle commands, we already started the command before
1087 // the language switch
1088 if (!intitle_command) {
1089 parStartCommand(par, os, runparams, style);
1090 if (style.isCommand() && style.needprotect)
1091 // Due to the moving argument, some fragile
1092 // commands (labels, index entries)
1093 // are output after this command (#2154)
1094 runparams.postpone_fragile_stuff = true;
1097 Font const outerfont = text.outerFont(pit);
1100 os << from_utf8(everypar);
1101 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1103 Font const font = par.empty()
1104 ? par.getLayoutFont(bparams, outerfont)
1105 : par.getFont(bparams, par.size() - 1, outerfont);
1107 bool const is_command = style.isCommand();
1109 // InTitle commands need to be closed after the language has been closed.
1110 if (!intitle_command) {
1113 if (!style.postcommandargs().empty())
1114 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1115 if (!runparams.post_macro.empty()) {
1116 // Output the stored fragile commands (labels, indices etc.)
1117 // that need to be output after the command with moving argument.
1118 os << runparams.post_macro;
1119 runparams.post_macro.clear();
1121 if (runparams.encoding != prev_encoding) {
1122 runparams.encoding = prev_encoding;
1123 os << setEncoding(prev_encoding->iconvName());
1128 bool pending_newline = false;
1129 bool unskip_newline = false;
1130 bool close_lang_switch = false;
1131 switch (style.latextype) {
1132 case LATEX_ITEM_ENVIRONMENT:
1133 case LATEX_LIST_ENVIRONMENT:
1134 if ((nextpar && par_lang != nextpar_lang
1135 && nextpar->getDepth() == par.getDepth())
1136 || (atSameLastLangSwitchDepth(state) && nextpar
1137 && nextpar->getDepth() < par.getDepth()))
1138 close_lang_switch = using_begin_end;
1139 if (nextpar && par.params().depth() < nextpar->params().depth())
1140 pending_newline = true;
1142 case LATEX_ENVIRONMENT: {
1143 // if it's the last paragraph of the current environment
1144 // skip it otherwise fall through
1146 && ((nextpar->layout() != par.layout()
1147 || nextpar->params().depth() != par.params().depth())
1148 || (!using_begin_end || par_lang != nextpar_lang)))
1150 close_lang_switch = using_begin_end;
1157 // we don't need it for the last paragraph and in InTitle commands!!!
1158 if (nextpar && !intitle_command)
1159 pending_newline = true;
1162 // InTitle commands use switches (not environments) for space settings
1163 if (par.allowParagraphCustomization() && !style.intitle) {
1164 if (!par.params().spacing().isDefault()
1165 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1166 if (pending_newline)
1169 string const endtag =
1170 par.params().spacing().writeEnvirEnd(useSetSpace);
1171 if (prefixIs(endtag, "\\end{"))
1174 os << from_ascii(endtag);
1175 pending_newline = true;
1179 // Closing the language is needed for the last paragraph in a given language
1180 // as well as for any InTitleCommand (since these set the language locally);
1181 // it is also needed if we're within an \L or \R that we may have opened above
1182 // (not necessarily in this paragraph) and are about to close.
1183 bool closing_rtl_ltr_environment = !using_begin_end
1185 && (par_language->lang() != "arabic_arabtex"
1186 && outer_language->lang() != "arabic_arabtex")
1187 // have we opened an \L or \R environment?
1188 && runparams.local_font != 0
1189 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1190 // are we about to close the language?
1191 &&((nextpar && par_lang != nextpar_lang)
1192 || (runparams.isLastPar && par_lang != outer_lang));
1194 if (localswitch_needed
1195 || (intitle_command && using_begin_end)
1196 || closing_rtl_ltr_environment
1197 || ((runparams.isLastPar || close_lang_switch)
1198 && (par_lang != outer_lang || (using_begin_end
1199 && style.isEnvironment()
1200 && par_lang != nextpar_lang)))) {
1201 // Since \selectlanguage write the language to the aux file,
1202 // we need to reset the language at the end of footnote or
1205 if (!localswitch && (pending_newline || close_lang_switch))
1208 // when the paragraph uses CJK, the language has to be closed earlier
1209 if ((font.language()->encoding()->package() != Encoding::CJK) || runparams_in.for_search) {
1210 if (lang_end_command.empty()) {
1211 // If this is a child, we should restore the
1212 // master language after the last paragraph.
1213 Language const * const current_language =
1214 (runparams.isLastPar && runparams.master_language)
1215 ? runparams.master_language
1217 string const current_lang = use_polyglossia
1218 ? getPolyglossiaEnvName(current_language)
1219 : current_language->babel();
1220 if (!current_lang.empty()
1221 && current_lang != openLanguageName(state)) {
1222 string bc = use_polyglossia ?
1223 getPolyglossiaBegin(lang_begin_command, current_lang,
1224 current_language->polyglossiaOpts(),
1226 : subst(lang_begin_command, "$$lang", current_lang);
1228 pending_newline = !localswitch;
1229 unskip_newline = !localswitch;
1230 if (using_begin_end)
1231 pushLanguageName(current_lang, localswitch);
1233 } else if ((!using_begin_end ||
1234 langOpenedAtThisLevel(state)) &&
1235 !par_lang.empty()) {
1236 // If we are in an environment, we have to
1237 // close the "outer" language afterwards
1238 string const & cur_lang = openLanguageName(state);
1239 if (!style.isEnvironment()
1240 || (close_lang_switch
1241 && atSameLastLangSwitchDepth(state)
1242 && par_lang != outer_lang
1243 && (par_lang != cur_lang
1244 || (cur_lang != outer_lang
1246 && style != nextpar->layout())))
1247 || (atSameLastLangSwitchDepth(state)
1248 && state->lang_switch_depth_.size()
1249 && cur_lang != par_lang)
1250 || in_polyglossia_rtl_env)
1252 if (using_begin_end && !localswitch)
1254 os << from_ascii(subst(
1258 pending_newline = !localswitch;
1259 unskip_newline = !localswitch;
1260 if (using_begin_end)
1266 if (closing_rtl_ltr_environment)
1269 // InTitle commands need to be closed after the language has been closed.
1270 if (intitle_command) {
1273 if (!style.postcommandargs().empty())
1274 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1275 if (!runparams.post_macro.empty()) {
1276 // Output the stored fragile commands (labels, indices etc.)
1277 // that need to be output after the command with moving argument.
1278 os << runparams.post_macro;
1279 runparams.post_macro.clear();
1281 if (runparams.encoding != prev_encoding) {
1282 runparams.encoding = prev_encoding;
1283 os << setEncoding(prev_encoding->iconvName());
1288 bool const last_was_separator =
1289 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1291 if (pending_newline) {
1293 // prevent unwanted whitespace
1295 if (!os.afterParbreak() && !last_was_separator)
1299 // if this is a CJK-paragraph and the next isn't, close CJK
1300 // also if the next paragraph is a multilingual environment (because of nesting)
1302 && (state->open_encoding_ == CJK && bparams.encoding().iconvName() != "UTF-8"
1303 && bparams.encoding().package() != Encoding::CJK )
1304 && (nextpar_language->encoding()->package() != Encoding::CJK
1305 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1306 // inbetween environments, CJK has to be closed later (nesting!)
1307 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1308 os << "\\end{CJK}\n";
1309 state->open_encoding_ = none;
1312 // If this is the last paragraph, close the CJK environment
1313 // if necessary. If it's an environment or nested in an environment,
1314 // we'll have to \end that first.
1315 if (runparams.isLastPar && !style.isEnvironment()
1316 && par.params().depth() < 1) {
1317 switch (state->open_encoding_) {
1319 // do nothing at the end of child documents
1320 if (maintext && buf.masterBuffer() != &buf)
1322 // end of main text: also insert a \clearpage (see #5386)
1324 os << "\n\\clearpage\n\\end{CJK}\n";
1328 state->open_encoding_ = none;
1333 state->open_encoding_ = none;
1343 // Information about local language is stored as a font feature.
1344 // If this is the last paragraph of the inset and a local_font was set upon entering
1345 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1346 // ensure the encoding is set back to the default encoding of the local language.
1347 if (runparams.isLastPar && runparams_in.local_font != 0
1348 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1349 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1350 && !runparams.isFullUnicode()
1352 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1353 os << setEncoding(runparams_in.encoding->iconvName());
1355 // Otherwise, the current encoding should be set for the next paragraph.
1357 runparams_in.encoding = runparams.encoding;
1359 // Also pass the post_macros upstream
1360 runparams_in.post_macro = runparams.post_macro;
1363 // we don't need a newline for the last paragraph!!!
1364 // Note from JMarc: we will re-add a \n explicitly in
1365 // TeXEnvironment, because it is needed in this case
1366 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1367 // Make sure to start a new line
1369 Layout const & next_layout = nextpar->layout();
1370 // A newline '\n' is always output before a command,
1371 // so avoid doubling it.
1372 if (!next_layout.isCommand()) {
1373 // Here we now try to avoid spurious empty lines by
1374 // outputting a paragraph break only if: (case 1) the
1375 // paragraph style allows parbreaks and no \begin, \end
1376 // or \item tags are going to follow (i.e., if the next
1377 // isn't the first or the current isn't the last
1378 // paragraph of an environment or itemize) and the
1379 // depth and alignment of the following paragraph is
1380 // unchanged, or (case 2) the following is a
1381 // non-environment paragraph whose depth is increased
1382 // but whose alignment is unchanged, or (case 3) the
1383 // paragraph is not an environment and the next one is a
1384 // non-itemize-like env at lower depth, or (case 4) the
1385 // paragraph is a command not followed by an environment
1386 // and the alignment of the current and next paragraph
1387 // is unchanged, or (case 5) the current alignment is
1388 // changed and a standard paragraph follows.
1389 DocumentClass const & tclass = bparams.documentClass();
1390 if ((style == next_layout
1391 && !style.parbreak_is_newline
1392 && !text.inset().getLayout().parbreakIsNewline()
1393 && style.latextype != LATEX_ITEM_ENVIRONMENT
1394 && style.latextype != LATEX_LIST_ENVIRONMENT
1395 && style.align == par.getAlign()
1396 && nextpar->getDepth() == par.getDepth()
1397 && nextpar->getAlign() == par.getAlign())
1398 || (!next_layout.isEnvironment()
1399 && nextpar->getDepth() > par.getDepth()
1400 && nextpar->getAlign() == next_layout.align)
1401 || (!style.isEnvironment()
1402 && next_layout.latextype == LATEX_ENVIRONMENT
1403 && nextpar->getDepth() < par.getDepth())
1404 || (style.isCommand()
1405 && !next_layout.isEnvironment()
1406 && style.align == par.getAlign()
1407 && next_layout.align == nextpar->getAlign())
1408 || (style.align != par.getAlign()
1409 && tclass.isDefaultLayout(next_layout))) {
1415 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1416 << &par << " next " << nextpar);
1422 // LaTeX all paragraphs
1423 void latexParagraphs(Buffer const & buf,
1426 OutputParams const & runparams,
1427 string const & everypar)
1429 LASSERT(runparams.par_begin <= runparams.par_end,
1430 { os << "% LaTeX Output Error\n"; return; } );
1432 BufferParams const & bparams = buf.params();
1433 BufferParams const & mparams = buf.masterParams();
1435 bool const maintext = text.isMainText();
1436 bool const is_child = buf.masterBuffer() != &buf;
1437 bool const multibib_child = maintext && is_child
1438 && mparams.multibib == "child";
1440 if (multibib_child && mparams.useBiblatex())
1441 os << "\\newrefsection";
1442 else if (multibib_child && mparams.useBibtopic()
1443 && !buf.masterBibInfo().empty()) {
1444 os << "\\begin{btUnit}\n";
1445 runparams.openbtUnit = true;
1448 // Open a CJK environment at the beginning of the main buffer
1449 // if the document's main encoding requires the CJK package
1450 // or the document encoding is utf8 and the CJK package is required
1451 // (but not in child documents or documents using system fonts):
1452 OutputState * state = getOutputState();
1453 if (maintext && !is_child && !bparams.useNonTeXFonts
1454 && (bparams.encoding().package() == Encoding::CJK
1455 || (bparams.encoding().name() == "utf8"
1456 && runparams.use_CJK))
1458 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1459 ? from_ascii("UTF8") : from_ascii(bparams.encoding().latexName());
1460 os << "\\begin{CJK}{" << cjkenc
1461 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1462 state->open_encoding_ = CJK;
1464 // if "auto begin" is switched off, explicitly switch the
1465 // language on at start
1466 string const mainlang = runparams.use_polyglossia
1467 ? getPolyglossiaEnvName(bparams.language)
1468 : bparams.language->babel();
1469 string const lang_begin_command = runparams.use_polyglossia ?
1470 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1471 string const lang_end_command = runparams.use_polyglossia ?
1472 "\\end{$$lang}" : lyxrc.language_command_end;
1473 bool const using_begin_end = runparams.use_polyglossia ||
1474 !lang_end_command.empty();
1476 if (maintext && !lyxrc.language_auto_begin &&
1477 !mainlang.empty()) {
1479 string bc = runparams.use_polyglossia ?
1480 getPolyglossiaBegin(lang_begin_command, mainlang,
1481 bparams.language->polyglossiaOpts())
1482 : subst(lang_begin_command, "$$lang", mainlang);
1485 if (using_begin_end)
1486 pushLanguageName(mainlang);
1489 ParagraphList const & paragraphs = text.paragraphs();
1491 if (runparams.par_begin == runparams.par_end) {
1492 // The full doc will be exported but it is easier to just rely on
1493 // runparams range parameters that will be passed TeXEnvironment.
1494 runparams.par_begin = 0;
1495 runparams.par_end = paragraphs.size();
1498 pit_type pit = runparams.par_begin;
1499 // lastpit is for the language check after the loop.
1500 pit_type lastpit = pit;
1501 // variables used in the loop:
1502 bool was_title = false;
1503 bool already_title = false;
1504 DocumentClass const & tclass = bparams.documentClass();
1506 // Did we already warn about inTitle layout mixing? (we only warn once)
1507 bool gave_layout_warning = false;
1508 for (; pit < runparams.par_end; ++pit) {
1510 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1512 // FIXME This check should not be needed. We should
1513 // perhaps issue an error if it is.
1514 Layout const & layout = text.inset().forcePlainLayout() ?
1515 tclass.plainLayout() : par->layout();
1517 if (layout.intitle) {
1518 if (already_title) {
1519 if (!gave_layout_warning && !runparams.dryrun) {
1520 gave_layout_warning = true;
1521 frontend::Alert::warning(_("Error in latexParagraphs"),
1522 bformat(_("You are using at least one "
1523 "layout (%1$s) intended for the title, "
1524 "after using non-title layouts. This "
1525 "could lead to missing or incorrect output."
1528 } else if (!was_title) {
1530 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1532 << from_ascii(tclass.titlename())
1536 } else if (was_title && !already_title && !layout.inpreamble) {
1537 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1538 os << "\\end{" << from_ascii(tclass.titlename())
1542 os << "\\" << from_ascii(tclass.titlename())
1545 already_title = true;
1549 if (layout.isCommand() && !layout.latexname().empty()
1550 && layout.latexname() == bparams.multibib) {
1551 if (runparams.openbtUnit)
1552 os << "\\end{btUnit}\n";
1553 if (!bparams.useBiblatex()
1554 && !buf.masterBibInfo().empty()) {
1555 os << '\n' << "\\begin{btUnit}\n";
1556 runparams.openbtUnit = true;
1560 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1561 // This is a standard top level paragraph, TeX it and continue.
1562 TeXOnePar(buf, text, pit, os, runparams, everypar);
1566 TeXEnvironmentData const data =
1567 prepareEnvironment(buf, text, par, os, runparams);
1568 // pit can be changed in TeXEnvironment.
1569 TeXEnvironment(buf, text, runparams, pit, os);
1570 finishEnvironment(os, runparams, data);
1573 if (pit == runparams.par_end) {
1574 // Make sure that the last paragraph is
1575 // correctly terminated (because TeXOnePar does
1576 // not add a \n in this case)
1580 // It might be that we only have a title in this document
1581 if (was_title && !already_title) {
1582 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1583 os << "\\end{" << from_ascii(tclass.titlename())
1586 os << "\\" << from_ascii(tclass.titlename())
1591 if (maintext && !is_child && runparams.openbtUnit)
1592 os << "\\end{btUnit}\n";
1594 // if "auto end" is switched off, explicitly close the language at the end
1595 // but only if the last par is in a babel or polyglossia language
1596 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1597 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1598 os << from_utf8(subst(lang_end_command,
1602 if (using_begin_end)
1606 // If the last paragraph is an environment, we'll have to close
1607 // CJK at the very end to do proper nesting.
1608 if (maintext && !is_child && state->open_encoding_ == CJK) {
1609 os << "\\clearpage\n\\end{CJK}\n";
1610 state->open_encoding_ = none;
1612 // Likewise for polyglossia or when using begin/end commands
1613 string const & cur_lang = openLanguageName(state);
1614 if (maintext && !is_child && !cur_lang.empty()) {
1615 os << from_utf8(subst(lang_end_command,
1619 if (using_begin_end)
1623 // reset inherited encoding
1624 if (state->cjk_inherited_ > 0) {
1625 state->cjk_inherited_ -= 1;
1626 if (state->cjk_inherited_ == 0)
1627 state->open_encoding_ = CJK;
1630 if (multibib_child && mparams.useBibtopic()) {
1631 os << "\\end{btUnit}\n";
1632 runparams.openbtUnit = false;
1636 // Switch the input encoding for some part(s) of the document.
1637 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1638 OutputParams const & runparams, Encoding const & newEnc,
1639 bool force, bool noswitchmacro)
1641 // Never switch encoding with non-TeX fonts (always "utf8plain"),
1642 // with LuaTeX and TeX fonts (only one encoding accepted by luainputenc),
1643 // or if we're in a moving argument or inherit the outer encoding.
1644 if (bparams.useNonTeXFonts
1645 || runparams.flavor == OutputParams::LUATEX
1646 || runparams.flavor == OutputParams::DVILUATEX
1647 || newEnc.name() == "inherit")
1648 return make_pair(false, 0);
1650 // Only switch for auto-selected legacy encodings (inputenc setting
1651 // "auto-legacy" or "auto-legacy-plain").
1652 // The "listings" environment can force a switch also with other
1653 // encoding settings (it does not support variable width encodings
1654 // (utf8, jis, ...) under 8-bit latex engines).
1655 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1656 || runparams.moving_arg))
1657 return make_pair(false, 0);
1659 Encoding const & oldEnc = *runparams.encoding;
1660 // Do not switch, if the encoding is unchanged or switching is not supported.
1661 if (oldEnc.name() == newEnc.name()
1662 || oldEnc.package() == Encoding::japanese
1663 || oldEnc.package() == Encoding::none
1664 || newEnc.package() == Encoding::none
1665 || runparams.for_search)
1666 return make_pair(false, 0);
1667 // FIXME We ignore encoding switches from/to encodings that do
1668 // neither support the inputenc package nor the CJK package here.
1669 // This may fail for characters not supported by "unicodesymbols"
1670 // or for non-ASCII characters in "listings"
1671 // but it is the best we can do.
1674 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1675 << oldEnc.name() << " to " << newEnc.name());
1676 os << setEncoding(newEnc.iconvName());
1677 if (bparams.inputenc == "auto-legacy-plain")
1678 return make_pair(true, 0);
1680 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1681 OutputState * state = getOutputState();
1682 switch (newEnc.package()) {
1683 case Encoding::none:
1684 case Encoding::japanese:
1685 // shouldn't ever reach here (see above) but avoids warning.
1686 return make_pair(true, 0);
1687 case Encoding::inputenc: {
1688 int count = inputenc_arg.length();
1689 if (oldEnc.package() == Encoding::CJK &&
1690 state->open_encoding_ == CJK) {
1692 state->open_encoding_ = none;
1695 else if (oldEnc.package() == Encoding::inputenc &&
1696 state->open_encoding_ == inputenc) {
1698 state->open_encoding_ = none;
1701 if (runparams.local_font != 0
1702 && oldEnc.package() == Encoding::CJK) {
1703 // within insets, \inputenc switches need
1704 // to be embraced within \bgroup...\egroup;
1708 state->open_encoding_ = inputenc;
1711 return make_pair(true, count);
1712 os << "\\inputencoding{" << inputenc_arg << '}';
1713 return make_pair(true, count + 16);
1715 case Encoding::CJK: {
1716 int count = inputenc_arg.length();
1717 if (oldEnc.package() == Encoding::CJK &&
1718 state->open_encoding_ == CJK) {
1722 if (oldEnc.package() == Encoding::inputenc &&
1723 state->open_encoding_ == inputenc) {
1727 os << "\\begin{CJK}{"
1728 << from_ascii(newEnc.latexName()) << "}{"
1729 << from_ascii(bparams.fonts_cjk) << "}";
1730 state->open_encoding_ = CJK;
1731 return make_pair(true, count + 15);
1734 // Dead code to avoid a warning:
1735 return make_pair(true, 0);