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"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "texstream.h"
27 #include "TextClass.h"
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetArgument.h"
32 #include "frontends/alert.h"
34 #include "support/lassert.h"
35 #include "support/convert.h"
36 #include "support/debug.h"
37 #include "support/lstrings.h"
38 #include "support/lyxalgo.h"
39 #include "support/textutils.h"
40 #include "support/gettext.h"
42 #include <QThreadStorage>
48 using namespace lyx::support;
64 OutputState() : prev_env_language_(nullptr), open_encoding_(none),
65 cjk_inherited_(0), nest_level_(0)
68 Language const * prev_env_language_;
69 stack<int> lang_switch_depth_; // Both are always empty when
70 stack<string> open_polyglossia_lang_; // not using polyglossia
71 OpenEncoding open_encoding_;
77 OutputState * getOutputState()
79 // FIXME An instance of OutputState should be kept around for each export
80 // instead of using local thread storage
81 static QThreadStorage<OutputState *> outputstate;
82 if (!outputstate.hasLocalData())
83 outputstate.setLocalData(new OutputState);
84 return outputstate.localData();
88 string const & openLanguageName(OutputState const * state)
90 // Return a reference to the last active language opened with
91 // polyglossia or when using begin/end commands. If none or when
92 // using babel with only a begin command, return a reference to
95 static string const empty;
97 return state->open_polyglossia_lang_.empty()
99 : state->open_polyglossia_lang_.top();
103 bool atSameLastLangSwitchDepth(OutputState const * state)
105 // Return true if the actual nest level is the same at which the
106 // language was switched when using polyglossia or begin/end
107 // commands. Instead, return always true when using babel with
108 // only a begin command.
110 return state->lang_switch_depth_.empty()
112 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
116 bool isLocalSwitch(OutputState const * state)
118 // Return true if the language was opened by a local command switch.
120 return !state->lang_switch_depth_.empty()
121 && state->lang_switch_depth_.top() < 0;
125 bool langOpenedAtThisLevel(OutputState const * state)
127 // Return true if the language was opened at the current nesting level.
129 return !state->lang_switch_depth_.empty()
130 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
134 string const getPolyglossiaEnvName(Language const * lang)
136 string result = lang->polyglossia();
137 if (result == "arabic")
138 // exceptional spelling; see polyglossia docs.
144 string const getPolyglossiaBegin(string const & lang_begin_command,
145 string const & lang, string const & opts,
146 bool const localswitch = false)
150 // we need to revert the upcasing done in getPolyglossiaEnvName()
151 // in case we have a local polyglossia command (\textarabic).
152 string language = localswitch ? ascii_lowercase(lang) : lang;
153 result = subst(lang_begin_command, "$$lang", language);
155 string options = opts.empty() ?
156 string() : "[" + opts + "]";
157 result = subst(result, "$$opts", options);
163 struct TeXEnvironmentData
165 Layout const * style;
166 Language const * par_language;
167 Encoding const * prev_encoding;
169 bool leftindent_open;
173 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
175 ParagraphList::const_iterator pit,
177 OutputParams const & runparams)
179 TeXEnvironmentData data;
181 BufferParams const & bparams = buf.params();
183 // FIXME This test should not be necessary.
184 // We should perhaps issue an error if it is.
185 Layout const & style = text.inset().forcePlainLayout() ?
186 bparams.documentClass().plainLayout() : pit->layout();
188 ParagraphList const & paragraphs = text.paragraphs();
189 ParagraphList::const_iterator const priorpit =
190 pit == paragraphs.begin() ? pit : prev(pit, 1);
192 OutputState * state = getOutputState();
193 bool const use_prev_env_language = state->prev_env_language_ != nullptr
194 && priorpit->layout().isEnvironment()
195 && (priorpit->getDepth() > pit->getDepth()
196 || (priorpit->getDepth() == pit->getDepth()
197 && priorpit->layout() != pit->layout()));
199 data.prev_encoding = runparams.encoding;
200 data.par_language = pit->getParLanguage(bparams);
201 Language const * const doc_language = bparams.language;
202 Language const * const prev_par_language =
203 (pit != paragraphs.begin())
204 ? (use_prev_env_language ? state->prev_env_language_
205 : priorpit->getParLanguage(bparams))
208 bool const use_polyglossia = runparams.use_polyglossia;
209 string const par_lang = use_polyglossia ?
210 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
211 string const prev_par_lang = use_polyglossia ?
212 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
213 string const doc_lang = use_polyglossia ?
214 getPolyglossiaEnvName(doc_language) : doc_language->babel();
215 string const lang_begin_command = use_polyglossia ?
216 "\\begin{$$lang}" : lyxrc.language_command_begin;
217 string const lang_end_command = use_polyglossia ?
218 "\\end{$$lang}" : lyxrc.language_command_end;
219 bool const using_begin_end = use_polyglossia ||
220 !lang_end_command.empty();
222 // For polyglossia, switch language outside of environment, if possible.
223 if (par_lang != prev_par_lang) {
224 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
225 !lang_end_command.empty() &&
226 prev_par_lang != doc_lang &&
227 !prev_par_lang.empty()) {
228 os << from_ascii(subst(
232 // the '%' is necessary to prevent unwanted whitespace
238 // If no language was explicitly opened and we are using
239 // polyglossia or begin/end commands, then the current
240 // language is the document language.
241 string const & cur_lang = using_begin_end
242 && !state->lang_switch_depth_.empty()
243 ? openLanguageName(state)
246 if ((lang_end_command.empty() ||
247 par_lang != doc_lang ||
248 par_lang != cur_lang) &&
250 string bc = use_polyglossia ?
251 getPolyglossiaBegin(lang_begin_command, par_lang,
252 data.par_language->polyglossiaOpts())
253 : subst(lang_begin_command, "$$lang", par_lang);
255 // the '%' is necessary to prevent unwanted whitespace
258 pushLanguageName(par_lang);
262 data.leftindent_open = false;
263 if (!pit->params().leftIndent().zero()) {
264 os << "\\begin{LyXParagraphLeftIndent}{"
265 << from_ascii(pit->params().leftIndent().asLatexString())
267 data.leftindent_open = true;
270 if (style.isEnvironment())
271 state->nest_level_ += 1;
273 if (style.isEnvironment() && !style.latexname().empty()) {
274 os << "\\begin{" << from_ascii(style.latexname()) << '}';
275 if (!style.latexargs().empty()) {
276 OutputParams rp = runparams;
277 rp.local_font = &pit->getFirstFontSettings(bparams);
278 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
280 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
282 << pit->params().labelWidthString()
284 } else if (style.labeltype == LABEL_BIBLIO) {
285 if (pit->params().labelWidthString().empty())
286 os << '{' << bibitemWidest(buf, runparams) << "}\n";
289 << pit->params().labelWidthString()
292 os << from_ascii(style.latexparam()) << '\n';
293 if (style.latextype == LATEX_BIB_ENVIRONMENT
294 || style.latextype == LATEX_ITEM_ENVIRONMENT
295 || style.latextype == LATEX_LIST_ENVIRONMENT) {
296 OutputParams rp = runparams;
297 rp.local_font = &pit->getFirstFontSettings(bparams);
298 latexArgInsets(paragraphs, pit, os, rp, style.listpreamble(),
304 // in multilingual environments, the CJK tags have to be nested properly
305 data.cjk_nested = false;
306 if (!bparams.useNonTeXFonts
307 && (bparams.inputenc == "auto-legacy"
308 || bparams.inputenc == "auto-legacy-plain")
309 && data.par_language->encoding()->package() == Encoding::CJK
310 && state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
311 if (prev_par_language->encoding()->package() == Encoding::CJK) {
312 os << "\\begin{CJK}{"
313 << from_ascii(data.par_language->encoding()->latexName())
314 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
316 state->open_encoding_ = CJK;
317 data.cjk_nested = true;
323 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
324 TeXEnvironmentData const & data)
326 OutputState * state = getOutputState();
327 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
328 if (state->open_encoding_ == CJK && data.cjk_nested) {
329 // We need to close the encoding even if it does not change
330 // to do correct environment nesting
331 os << "\\end{CJK}\n";
332 state->open_encoding_ = none;
335 if (data.style->isEnvironment()) {
337 bool const using_begin_end =
338 runparams.use_polyglossia ||
339 !lyxrc.language_command_end.empty();
340 // Close any language opened at this nest level
341 if (using_begin_end) {
342 while (langOpenedAtThisLevel(state)) {
343 if (isLocalSwitch(state)) {
347 << openLanguageName(state)
353 state->nest_level_ -= 1;
354 string const & name = data.style->latexname();
356 os << "\\end{" << from_ascii(name) << "}\n";
357 state->prev_env_language_ = data.par_language;
358 if (runparams.encoding != data.prev_encoding) {
359 runparams.encoding = data.prev_encoding;
360 os << setEncoding(data.prev_encoding->iconvName());
364 if (data.leftindent_open) {
365 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
366 state->prev_env_language_ = data.par_language;
367 if (runparams.encoding != data.prev_encoding) {
368 runparams.encoding = data.prev_encoding;
369 os << setEncoding(data.prev_encoding->iconvName());
373 // Check whether we should output a blank line after the environment
374 if (!data.style->nextnoindent)
379 void TeXEnvironment(Buffer const & buf, Text const & text,
380 OutputParams const & runparams,
381 pit_type & pit, otexstream & os)
383 ParagraphList const & paragraphs = text.paragraphs();
384 ParagraphList::const_iterator ipar = paragraphs.iterator_at(pit);
385 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
387 Layout const & current_layout = ipar->layout();
388 depth_type const current_depth = ipar->params().depth();
389 Length const & current_left_indent = ipar->params().leftIndent();
391 // This is for debugging purpose at the end.
392 pit_type const par_begin = pit;
393 for (; pit < runparams.par_end; ++pit) {
394 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
396 // check first if this is an higher depth paragraph.
397 bool go_out = (par->params().depth() < current_depth);
398 if (par->params().depth() == current_depth) {
399 // This environment is finished.
400 go_out |= (par->layout() != current_layout);
401 go_out |= (par->params().leftIndent() != current_left_indent);
404 // nothing to do here, restore pit and go out.
409 if (par->layout() == current_layout
410 && par->params().depth() == current_depth
411 && par->params().leftIndent() == current_left_indent) {
412 // We are still in the same environment so TeXOnePar and continue;
413 TeXOnePar(buf, text, pit, os, runparams);
417 // We are now in a deeper environment.
418 // Either par->layout() != current_layout
419 // Or par->params().depth() > current_depth
420 // Or par->params().leftIndent() != current_left_indent)
422 // FIXME This test should not be necessary.
423 // We should perhaps issue an error if it is.
424 bool const force_plain_layout = text.inset().forcePlainLayout();
425 Layout const & style = force_plain_layout
426 ? buf.params().documentClass().plainLayout()
429 if (!style.isEnvironment()) {
430 // This is a standard paragraph, no need to call TeXEnvironment.
431 TeXOnePar(buf, text, pit, os, runparams);
435 // Do not output empty environments if the whole paragraph has
436 // been deleted with ct and changes are not output.
437 if (size_t(pit + 1) < paragraphs.size()) {
438 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
439 Paragraph const & cpar = paragraphs.at(pit);
440 if ((par->layout() != nextpar->layout()
441 || par->params().depth() == nextpar->params().depth()
442 || par->params().leftIndent() == nextpar->params().leftIndent())
443 && !runparams.for_search && !cpar.empty()
444 && cpar.isDeleted(0, cpar.size()) && !buf.params().output_changes) {
445 if (!buf.params().output_changes && !cpar.parEndChange().deleted())
451 // This is a new environment.
452 TeXEnvironmentData const data =
453 prepareEnvironment(buf, text, par, os, runparams);
454 // Recursive call to TeXEnvironment!
455 TeXEnvironment(buf, text, runparams, pit, os);
456 finishEnvironment(os, runparams, data);
459 if (pit != runparams.par_end)
460 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
464 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
465 map<size_t, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
467 size_t const argnr = latexargs.size();
471 // Default and preset args are always output, so if they require
472 // other arguments, consider this.
473 for (auto const & larg : latexargs) {
474 Layout::latexarg const & arg = larg.second;
475 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.required.empty()) {
476 vector<string> req = getVectorFromString(arg.required);
477 required.insert(required.end(), req.begin(), req.end());
481 for (size_t i = 1; i <= argnr; ++i) {
482 map<size_t, InsetArgument const *>::const_iterator lit = ilist.find(i);
483 bool inserted = false;
484 if (lit != ilist.end()) {
485 InsetArgument const * ins = lit->second;
487 Layout::LaTeXArgMap::const_iterator const lait =
488 latexargs.find(ins->name());
489 if (lait != latexargs.end()) {
490 Layout::latexarg arg = lait->second;
494 ldelim = arg.mandatory ?
495 from_ascii("{") : from_ascii("[");
496 rdelim = arg.mandatory ?
497 from_ascii("}") : from_ascii("]");
499 if (!arg.ldelim.empty())
501 if (!arg.rdelim.empty())
503 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
504 if (prefix == "listpreamble:")
511 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
512 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
513 for (; lait != laend; ++lait) {
514 string const name = prefix + convert<string>(i);
515 if ((*lait).first == name) {
516 Layout::latexarg arg = (*lait).second;
517 docstring preset = arg.presetarg;
518 if (!arg.defaultarg.empty()) {
521 preset += arg.defaultarg;
524 docstring ldelim = arg.ldelim.empty() ?
525 from_ascii("{") : arg.ldelim;
526 docstring rdelim = arg.rdelim.empty() ?
527 from_ascii("}") : arg.rdelim;
528 os << ldelim << preset << rdelim;
529 } else if (!preset.empty()) {
530 docstring ldelim = arg.ldelim.empty() ?
531 from_ascii("[") : arg.ldelim;
532 docstring rdelim = arg.rdelim.empty() ?
533 from_ascii("]") : arg.rdelim;
534 os << ldelim << preset << rdelim;
535 } else if (find(required.begin(), required.end(),
536 (*lait).first) != required.end()) {
537 docstring ldelim = arg.ldelim.empty() ?
538 from_ascii("[") : arg.ldelim;
539 docstring rdelim = arg.rdelim.empty() ?
540 from_ascii("]") : arg.rdelim;
541 os << ldelim << rdelim;
548 if (runparams.for_search) {
549 // Mark end of arguments for findadv() only
550 os << "\\endarguments{}";
558 void pushLanguageName(string const & lang_name, bool localswitch)
560 OutputState * state = getOutputState();
562 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
563 state->lang_switch_depth_.push(nest_level);
564 state->open_polyglossia_lang_.push(lang_name);
568 void popLanguageName()
570 OutputState * state = getOutputState();
572 state->lang_switch_depth_.pop();
573 state->open_polyglossia_lang_.pop();
577 string const & openLanguageName()
579 OutputState * state = getOutputState();
581 return openLanguageName(state);
587 void addArgInsets(Paragraph const & par, string const & prefix,
588 Layout::LaTeXArgMap const & latexargs,
589 map<size_t, InsetArgument const *> & ilist,
590 vector<string> & required)
592 for (auto const & table : par.insetList()) {
593 InsetArgument const * arg = table.inset->asInsetArgument();
596 if (arg->name().empty()) {
597 LYXERR0("Error: Unnamed argument inset!");
600 string const name = prefix.empty() ?
601 arg->name() : split(arg->name(), ':');
602 size_t const nr = convert<size_t>(name);
603 if (ilist.find(nr) == ilist.end())
605 Layout::LaTeXArgMap::const_iterator const lit =
606 latexargs.find(arg->name());
607 if (lit != latexargs.end()) {
608 Layout::latexarg const & larg = lit->second;
609 vector<string> req = getVectorFromString(larg.required);
610 move(req.begin(), req.end(), back_inserter(required));
618 void latexArgInsets(Paragraph const & par, otexstream & os,
619 OutputParams const & runparams,
620 Layout::LaTeXArgMap const & latexargs,
621 string const & prefix)
623 map<size_t, InsetArgument const *> ilist;
624 vector<string> required;
625 addArgInsets(par, prefix, latexargs, ilist, required);
626 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
630 void latexArgInsets(ParagraphList const & pars,
631 ParagraphList::const_iterator pit,
632 otexstream & os, OutputParams const & runparams,
633 Layout::LaTeXArgMap const & latexargs,
634 string const & prefix)
636 map<size_t, InsetArgument const *> ilist;
637 vector<string> required;
639 depth_type const current_depth = pit->params().depth();
640 Layout const current_layout = pit->layout();
642 // get the first paragraph in sequence with this layout and depth
643 ptrdiff_t offset = 0;
645 if (prev(pit, offset) == pars.begin())
647 ParagraphList::const_iterator priorpit = prev(pit, offset + 1);
648 if (priorpit->layout() == current_layout
649 && priorpit->params().depth() == current_depth)
655 ParagraphList::const_iterator spit = prev(pit, offset);
656 for (; spit != pars.end(); ++spit) {
657 if (spit->layout() != current_layout ||
658 spit->params().depth() < current_depth)
660 if (spit->params().depth() > current_depth)
662 addArgInsets(*spit, prefix, latexargs, ilist, required);
664 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
668 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
669 OutputParams const & runparams,
670 Layout::LaTeXArgMap const & latexargs,
671 string const & prefix)
673 map<size_t, InsetArgument const *> ilist;
674 vector<string> required;
676 for (Paragraph const & par : pars) {
677 if (par.layout().hasArgs())
678 // The InsetArguments inside this paragraph refer to this paragraph
680 addArgInsets(par, prefix, latexargs, ilist, required);
682 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
688 // output the proper paragraph start according to latextype.
689 void parStartCommand(Paragraph const & par, otexstream & os,
690 OutputParams const & runparams, Layout const & style)
692 switch (style.latextype) {
694 if (par.needsCProtection(runparams.moving_arg)) {
695 if (contains(runparams.active_chars, '^'))
696 // cprotect relies on ^ being on catcode 7
697 os << "\\begingroup\\catcode`\\^=7";
700 os << '\\' << from_ascii(style.latexname());
703 if (!style.latexargs().empty())
704 latexArgInsets(par, os, runparams, style.latexargs());
705 os << from_ascii(style.latexparam());
707 case LATEX_ITEM_ENVIRONMENT:
708 case LATEX_LIST_ENVIRONMENT:
709 if (runparams.for_search) {
710 os << "\\" + style.itemcommand() << "{" << style.latexname() << "}";
713 os << "\\" + style.itemcommand();
715 if (!style.itemargs().empty())
716 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
720 case LATEX_ENVIRONMENT:
721 if (runparams.for_search) {
722 os << "\\latexenvironment{" << style.latexname() << "}{";
725 case LATEX_BIB_ENVIRONMENT:
726 // ignore this, the inset will write itself
735 // FIXME: this should be anonymous
736 void TeXOnePar(Buffer const & buf,
740 OutputParams const & runparams_in,
741 string const & everypar,
742 int start_pos, int end_pos,
745 BufferParams const & bparams = runparams_in.is_child
746 ? buf.masterParams() : buf.params();
747 ParagraphList const & paragraphs = text.paragraphs();
748 Paragraph const & par = paragraphs.at(pit);
749 // FIXME This check should not really be needed.
750 // Perhaps we should issue an error if it is.
751 Layout const & style = text.inset().forcePlainLayout() ?
752 bparams.documentClass().plainLayout() : par.layout();
754 if (style.inpreamble && !force)
757 // Do not output empty commands if the whole paragraph has
758 // been deleted with ct and changes are not output.
759 if (!runparams_in.for_search && style.latextype != LATEX_ENVIRONMENT
760 && !par.empty() && par.isDeleted(0, par.size()) && !bparams.output_changes)
763 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
766 OutputParams runparams = runparams_in;
767 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
768 // We reinitialize par begin and end to be on the safe side
769 // with embedded inset as we don't know if they set those
771 runparams.par_begin = 0;
772 runparams.par_end = 0;
774 bool const maintext = text.isMainText();
775 // we are at the beginning of an inset and CJK is already open;
776 // we count inheritation levels to get the inset nesting right.
777 OutputState * state = getOutputState();
778 if (pit == 0 && !maintext
779 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
780 state->cjk_inherited_ += 1;
781 state->open_encoding_ = none;
784 // This paragraph is merged and we do not show changes in the output
785 bool const merged_par = !bparams.output_changes && par.parEndChange().deleted();
787 if (text.inset().isPassThru()) {
788 Font const outerfont = text.outerFont(pit);
790 // No newline before first paragraph in this lyxtext
791 if (pit > 0 && !text.inset().getLayout().parbreakIgnored() && !merged_par) {
793 if (!text.inset().getLayout().parbreakIsNewline())
797 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
801 Paragraph const * nextpar = runparams.isLastPar
802 ? nullptr : ¶graphs.at(pit + 1);
804 bool const intitle_command = style.intitle && style.isCommand();
805 // Intitle commands switch languages locally, thus increase
806 // language nesting level
808 state->nest_level_ += 1;
810 if (style.pass_thru) {
811 Font const outerfont = text.outerFont(pit);
812 parStartCommand(par, os, runparams, style);
813 if (style.isCommand() && style.needprotect)
814 // Due to the moving argument, some fragile
815 // commands (labels, index entries)
816 // are output after this command (#2154)
817 runparams.postpone_fragile_stuff =
818 bparams.postpone_fragile_content;
822 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
824 // I did not create a parEndCommand for this minuscule
825 // task because in the other user of parStartCommand
826 // the code is different (JMarc)
827 if (style.isCommand()) {
829 if (par.needsCProtection(runparams.moving_arg)
830 && contains(runparams.active_chars, '^'))
837 else if (!merged_par)
839 if (!style.parbreak_is_newline && !merged_par) {
841 } else if (nextpar && !style.isEnvironment()) {
842 Layout const nextstyle = text.inset().forcePlainLayout()
843 ? bparams.documentClass().plainLayout()
845 if (nextstyle.name() != style.name() && !merged_par)
852 // This paragraph's language
853 Language const * const par_language = par.getParLanguage(bparams);
854 Language const * const nextpar_language = nextpar ?
855 nextpar->getParLanguage(bparams) : nullptr;
856 // The document's language
857 Language const * const doc_language = bparams.language;
858 // The language that was in effect when the environment this paragraph is
859 // inside of was opened
860 Language const * const outer_language =
861 (runparams.local_font != nullptr) ?
862 runparams.local_font->language() : doc_language;
864 Paragraph const * priorpar = (pit == 0) ? nullptr : ¶graphs.at(pit - 1);
866 // The previous language that was in effect is the language of the
867 // previous paragraph, unless the previous paragraph is inside an
868 // environment with nesting depth greater than (or equal to, but with
869 // a different layout) the current one. If there is no previous
870 // paragraph, the previous language is the outer language.
871 // Note further that we take the outer language also if the prior par
872 // is PassThru, since in that case it has latex_language, and all secondary
873 // languages have been closed (#10793).
874 bool const use_prev_env_language = state->prev_env_language_ != nullptr
876 && priorpar->layout().isEnvironment()
877 && (priorpar->getDepth() > par.getDepth()
878 || (priorpar->getDepth() == par.getDepth()
879 && priorpar->layout() != par.layout()));
881 // We need to ignore previous intitle commands since languages
882 // are switched locally there (# 11514)
883 // There might be paragraphs before the title, so we check this.
884 Paragraph * prior_nontitle_par = nullptr;
885 if (!intitle_command) {
889 Paragraph const * tmppar = ¶graphs.at(ppit);
890 if (tmppar->layout().intitle && tmppar->layout().isCommand())
892 prior_nontitle_par = const_cast<Paragraph*>(tmppar);
896 Language const * const prev_language =
897 runparams_in.for_search
898 ? languages.getLanguage("ignore")
899 : (prior_nontitle_par && !prior_nontitle_par->isPassThru())
900 ? (use_prev_env_language
901 ? state->prev_env_language_
902 : prior_nontitle_par->getParLanguage(bparams))
905 bool const use_polyglossia = runparams.use_polyglossia;
906 string const par_lang = use_polyglossia ?
907 getPolyglossiaEnvName(par_language): par_language->babel();
908 string const prev_lang = use_polyglossia ?
909 getPolyglossiaEnvName(prev_language) : prev_language->babel();
910 string const outer_lang = use_polyglossia ?
911 getPolyglossiaEnvName(outer_language) : outer_language->babel();
912 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
913 getPolyglossiaEnvName(nextpar_language) :
914 nextpar_language->babel()) : string();
915 string lang_begin_command = use_polyglossia ?
916 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
917 string lang_end_command = use_polyglossia ?
918 "\\end{$$lang}" : lyxrc.language_command_end;
919 // the '%' is necessary to prevent unwanted whitespace
920 string lang_command_termination = "%\n";
921 bool const using_begin_end = use_polyglossia ||
922 !lang_end_command.empty();
924 // For InTitle commands, we need to switch the language inside the command
925 // (see #10849); thus open the command here.
926 if (intitle_command) {
927 parStartCommand(par, os, runparams, style);
928 if (style.isCommand() && style.needprotect)
929 // Due to the moving argument, some fragile
930 // commands (labels, index entries)
931 // are output after this command (#2154)
932 runparams.postpone_fragile_stuff =
933 bparams.postpone_fragile_content;
937 // In some insets (such as Arguments), we cannot use \selectlanguage.
938 // Also, if an RTL language is set via environment in polyglossia,
939 // only a nested \\text<lang> command will reset the direction for LTR
940 // languages (see # 10111).
941 bool const in_polyglossia_rtl_env =
943 && runparams.local_font != nullptr
944 && outer_language->rightToLeft()
945 && !par_language->rightToLeft();
946 bool const localswitch =
947 (runparams_in.for_search
948 || text.inset().forceLocalFontSwitch()
949 || (using_begin_end && text.inset().forcePlainLayout())
950 || in_polyglossia_rtl_env)
951 && !text.inset().forceParDirectionSwitch();
953 lang_begin_command = use_polyglossia ?
954 "\\text$$lang$$opts{" : lyxrc.language_command_local;
955 lang_end_command = "}";
956 lang_command_termination.clear();
959 bool const localswitch_needed = localswitch && par_lang != outer_lang;
961 // localswitches need to be closed and reopened at each par
962 if (runparams_in.for_search || ((par_lang != prev_lang || localswitch_needed)
963 // check if we already put language command in TeXEnvironment()
964 && !(style.isEnvironment()
965 && (pit == 0 || (priorpar->layout() != par.layout()
966 && priorpar->getDepth() <= par.getDepth())
967 || priorpar->getDepth() < par.getDepth())))) {
969 && (!using_begin_end || langOpenedAtThisLevel(state))
970 && !lang_end_command.empty()
971 && prev_lang != outer_lang
972 && !prev_lang.empty()
973 && (!using_begin_end || !style.isEnvironment())) {
974 os << from_ascii(subst(lang_end_command,
977 << lang_command_termination;
982 // We need to open a new language if we couldn't close the previous
983 // one (because there's no language_command_end); and even if we closed
984 // the previous one, if the current language is different than the
985 // outer_language (which is currently in effect once the previous one
987 if ((lang_end_command.empty() || par_lang != outer_lang
989 || (style.isEnvironment() && par_lang != prev_lang)))
990 && !par_lang.empty()) {
991 // If we're inside an inset, and that inset is within an \L or \R
992 // (or equivalents), then within the inset, too, any opposite
993 // language paragraph should appear within an \L or \R (in addition
994 // to, outside of, the normal language switch commands).
995 // This behavior is not correct for ArabTeX, though.
998 && par_language->lang() != "arabic_arabtex"
999 && outer_language->lang() != "arabic_arabtex"
1000 // are we in an inset?
1001 && runparams.local_font != nullptr
1002 // is the inset within an \L or \R?
1004 // FIXME: currently, we don't check this; this means that
1005 // we'll have unnnecessary \L and \R commands, but that
1006 // doesn't seem to hurt (though latex will complain)
1008 // is this paragraph in the opposite direction?
1009 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
1010 // FIXME: I don't have a working copy of the Arabi package, so
1011 // I'm not sure if the farsi and arabic_arabi stuff is correct
1013 if (par_language->lang() == "farsi")
1015 else if (outer_language->lang() == "farsi")
1017 else if (par_language->lang() == "arabic_arabi")
1019 else if (outer_language->lang() == "arabic_arabi")
1021 // remaining RTL languages currently is hebrew
1022 else if (par_language->rightToLeft())
1027 // With CJK, the CJK tag has to be closed first (see below)
1028 if ((runparams.encoding->package() != Encoding::CJK
1029 || bparams.useNonTeXFonts
1030 || runparams.for_search)
1031 && (par_lang != openLanguageName(state) || localswitch || intitle_command)
1032 && !par_lang.empty()) {
1033 string bc = use_polyglossia ?
1034 getPolyglossiaBegin(lang_begin_command, par_lang,
1035 par_language->polyglossiaOpts(),
1037 : subst(lang_begin_command, "$$lang", par_lang);
1039 os << lang_command_termination;
1040 if (using_begin_end)
1041 pushLanguageName(par_lang, localswitch);
1046 // Switch file encoding if necessary; no need to do this for "auto-legacy-plain"
1047 // encoding, since this only affects the position of the outputted
1048 // \inputencoding command; the encoding switch will occur when necessary
1049 if (bparams.inputenc == "auto-legacy"
1050 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
1051 && runparams.encoding->package() != Encoding::japanese
1052 && runparams.encoding->package() != Encoding::none) {
1053 // Look ahead for future encoding changes.
1054 // We try to output them at the beginning of the paragraph,
1055 // since the \inputencoding command is not allowed e.g. in
1056 // sections. For this reason we only set runparams.moving_arg
1057 // after checking for the encoding change, otherwise the
1058 // change would be always avoided by switchEncoding().
1059 for (pos_type i = 0; i < par.size(); ++i) {
1060 char_type const c = par.getChar(i);
1061 Encoding const * const encoding =
1062 par.getFontSettings(bparams, i).language()->encoding();
1063 if (encoding->package() != Encoding::CJK
1064 && runparams.encoding->package() == Encoding::inputenc
1069 // All characters before c are in the ASCII range, and
1070 // c is non-ASCII (but no inset), so change the
1071 // encoding to that required by the language of c.
1072 // With CJK, only add switch if we have CJK content at the beginning
1074 if (i != 0 && encoding->package() == Encoding::CJK)
1077 pair<bool, int> enc_switch = switchEncoding(os.os(),
1078 bparams, runparams, *encoding);
1079 // the following is necessary after a CJK environment in a multilingual
1080 // context (nesting issue).
1081 if (par_language->encoding()->package() == Encoding::CJK
1082 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1083 os << "\\begin{CJK}{"
1084 << from_ascii(par_language->encoding()->latexName())
1085 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1086 state->open_encoding_ = CJK;
1088 if (encoding->package() != Encoding::none && enc_switch.first) {
1089 if (enc_switch.second > 0) {
1090 // the '%' is necessary to prevent unwanted whitespace
1093 // With CJK, the CJK tag had to be closed first (see above)
1094 if (runparams.encoding->package() == Encoding::CJK
1095 && par_lang != openLanguageName(state)
1096 && !par_lang.empty()) {
1097 os << subst(lang_begin_command, "$$lang", par_lang)
1098 << lang_command_termination;
1099 if (using_begin_end)
1100 pushLanguageName(par_lang, localswitch);
1102 runparams.encoding = encoding;
1108 runparams.moving_arg |= style.needprotect;
1109 if (style.needmboxprotect)
1110 ++runparams.inulemcmd;
1111 Encoding const * const prev_encoding = runparams.encoding;
1113 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1114 if (par.allowParagraphCustomization()) {
1115 if (par.params().startOfAppendix()) {
1116 os << "\n\\appendix\n";
1119 // InTitle commands must use switches (not environments)
1120 // inside the commands (see #9332)
1121 if (style.intitle) {
1122 if (!par.params().spacing().isDefault())
1124 if (runparams.moving_arg)
1126 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1129 if (!par.params().spacing().isDefault()
1130 && (pit == 0 || !priorpar->hasSameLayout(par)))
1132 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1136 if (style.isCommand()) {
1142 // For InTitle commands, we already started the command before
1143 // the language switch
1144 if (!intitle_command) {
1145 parStartCommand(par, os, runparams, style);
1146 if (style.isCommand() && style.needprotect)
1147 // Due to the moving argument, some fragile
1148 // commands (labels, index entries)
1149 // are output after this command (#2154)
1150 runparams.postpone_fragile_stuff =
1151 bparams.postpone_fragile_content;
1154 Font const outerfont = text.outerFont(pit);
1157 os << from_utf8(everypar);
1158 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1160 Font const font = par.empty()
1161 ? par.getLayoutFont(bparams, outerfont)
1162 : par.getFont(bparams, par.size() - 1, outerfont);
1164 bool const is_command = style.isCommand();
1166 // InTitle commands need to be closed after the language has been closed.
1167 if (!intitle_command) {
1170 if (!style.postcommandargs().empty())
1171 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1172 if (!runparams.post_macro.empty()) {
1173 // Output the stored fragile commands (labels, indices etc.)
1174 // that need to be output after the command with moving argument.
1175 os << runparams.post_macro;
1176 runparams.post_macro.clear();
1178 if (par.needsCProtection(runparams.moving_arg)
1179 && contains(runparams.active_chars, '^'))
1181 if (runparams.encoding != prev_encoding) {
1182 runparams.encoding = prev_encoding;
1183 os << setEncoding(prev_encoding->iconvName());
1188 bool pending_newline = false;
1189 bool unskip_newline = false;
1190 bool close_lang_switch = false;
1191 switch (style.latextype) {
1192 case LATEX_ITEM_ENVIRONMENT:
1193 case LATEX_LIST_ENVIRONMENT:
1194 if ((nextpar && par_lang != nextpar_lang
1195 && nextpar->getDepth() == par.getDepth())
1196 || (atSameLastLangSwitchDepth(state) && nextpar
1197 && nextpar->getDepth() < par.getDepth()))
1198 close_lang_switch = using_begin_end;
1199 if (nextpar && par.params().depth() < nextpar->params().depth())
1200 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1202 case LATEX_ENVIRONMENT: {
1203 // if it's the last paragraph of the current environment
1204 // skip it otherwise fall through
1206 && ((nextpar->layout() != par.layout()
1207 || nextpar->params().depth() != par.params().depth())
1208 || (!using_begin_end || par_lang != nextpar_lang)))
1210 close_lang_switch = using_begin_end;
1217 // we don't need it for the last paragraph and in InTitle commands!!!
1218 if (nextpar && !intitle_command)
1219 pending_newline = !text.inset().getLayout().parbreakIgnored() && !merged_par;
1222 // InTitle commands use switches (not environments) for space settings
1223 if (par.allowParagraphCustomization() && !style.intitle) {
1224 if (!par.params().spacing().isDefault()
1225 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1226 if (pending_newline)
1229 string const endtag =
1230 par.params().spacing().writeEnvirEnd(useSetSpace);
1231 if (prefixIs(endtag, "\\end{"))
1234 os << from_ascii(endtag);
1235 pending_newline = true;
1239 // Closing the language is needed for the last paragraph in a given language
1240 // as well as for any InTitleCommand (since these set the language locally);
1241 // it is also needed if we're within an \L or \R that we may have opened above
1242 // (not necessarily in this paragraph) and are about to close.
1243 bool closing_rtl_ltr_environment = !using_begin_end
1245 && (par_language->lang() != "arabic_arabtex"
1246 && outer_language->lang() != "arabic_arabtex")
1247 // have we opened an \L or \R environment?
1248 && runparams.local_font != nullptr
1249 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1250 // are we about to close the language?
1251 &&((nextpar && par_lang != nextpar_lang)
1252 || (runparams.isLastPar && par_lang != outer_lang));
1254 if (localswitch_needed
1255 || (intitle_command && using_begin_end)
1256 || closing_rtl_ltr_environment
1257 || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1258 && (par_lang != outer_lang || (using_begin_end
1259 && style.isEnvironment()
1260 && par_lang != nextpar_lang)))) {
1261 // Since \selectlanguage write the language to the aux file,
1262 // we need to reset the language at the end of footnote or
1265 if (!localswitch && (pending_newline || close_lang_switch))
1268 // when the paragraph uses CJK, the language has to be closed earlier
1269 if ((font.language()->encoding()->package() != Encoding::CJK)
1270 || bparams.useNonTeXFonts
1271 || runparams_in.for_search) {
1272 if (lang_end_command.empty()) {
1273 // If this is a child, we should restore the
1274 // master language after the last paragraph.
1275 Language const * const current_language =
1276 (runparams.isLastPar && runparams.master_language)
1277 ? runparams.master_language
1279 string const current_lang = use_polyglossia
1280 ? getPolyglossiaEnvName(current_language)
1281 : current_language->babel();
1282 if (!current_lang.empty()
1283 && current_lang != openLanguageName(state)) {
1284 string bc = use_polyglossia ?
1285 getPolyglossiaBegin(lang_begin_command, current_lang,
1286 current_language->polyglossiaOpts(),
1288 : subst(lang_begin_command, "$$lang", current_lang);
1290 pending_newline = !localswitch
1291 && !text.inset().getLayout().parbreakIgnored();
1292 unskip_newline = !localswitch;
1293 if (using_begin_end)
1294 pushLanguageName(current_lang, localswitch);
1296 } else if ((!using_begin_end ||
1297 langOpenedAtThisLevel(state)) &&
1298 !par_lang.empty()) {
1299 // If we are in an environment, we have to
1300 // close the "outer" language afterwards
1301 string const & cur_lang = openLanguageName(state);
1302 if (!style.isEnvironment()
1303 || (close_lang_switch
1304 && atSameLastLangSwitchDepth(state)
1305 && par_lang != outer_lang
1306 && (par_lang != cur_lang
1307 || (cur_lang != outer_lang
1309 && style != nextpar->layout())))
1310 || (atSameLastLangSwitchDepth(state)
1311 && !state->lang_switch_depth_.empty()
1312 && cur_lang != par_lang)
1313 || in_polyglossia_rtl_env)
1315 if (using_begin_end && !localswitch)
1317 os << from_ascii(subst(
1321 pending_newline = !localswitch
1322 && !text.inset().getLayout().parbreakIgnored();
1323 unskip_newline = !localswitch;
1324 if (using_begin_end)
1330 if (closing_rtl_ltr_environment)
1333 // InTitle commands need to be closed after the language has been closed.
1334 if (intitle_command) {
1336 if (!style.postcommandargs().empty())
1337 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1338 if (!runparams.post_macro.empty()) {
1339 // Output the stored fragile commands (labels, indices etc.)
1340 // that need to be output after the command with moving argument.
1341 os << runparams.post_macro;
1342 runparams.post_macro.clear();
1344 if (par.needsCProtection(runparams.moving_arg)
1345 && contains(runparams.active_chars, '^'))
1347 if (runparams.encoding != prev_encoding) {
1348 runparams.encoding = prev_encoding;
1349 os << setEncoding(prev_encoding->iconvName());
1353 bool const last_was_separator =
1354 !par.empty() && par.isEnvSeparator(par.size() - 1);
1356 // Signify added/deleted par break in output if show changes in output
1357 if (nextpar && !os.afterParbreak() && !last_was_separator
1358 && bparams.output_changes && par.parEndChange().changed()) {
1359 Changes::latexMarkChange(os, bparams, Change(Change::UNCHANGED),
1360 par.parEndChange(), runparams);
1361 os << bparams.encoding().latexString(docstring(1, 0x00b6)).first << "}";
1364 if (pending_newline) {
1366 // prevent unwanted whitespace
1368 if (!os.afterParbreak() && !last_was_separator)
1372 // if this is a CJK-paragraph and the next isn't, close CJK
1373 // also if the next paragraph is a multilingual environment (because of nesting)
1374 if (nextpar && state->open_encoding_ == CJK
1375 && bparams.encoding().iconvName() != "UTF-8"
1376 && bparams.encoding().package() != Encoding::CJK
1377 && ((nextpar_language &&
1378 nextpar_language->encoding()->package() != Encoding::CJK)
1379 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1380 // inbetween environments, CJK has to be closed later (nesting!)
1381 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1382 os << "\\end{CJK}\n";
1383 state->open_encoding_ = none;
1386 // If this is the last paragraph, close the CJK environment
1387 // if necessary. If it's an environment or nested in an environment,
1388 // we'll have to \end that first.
1389 if (runparams.isLastPar && !style.isEnvironment()
1390 && par.params().depth() < 1) {
1391 switch (state->open_encoding_) {
1393 // do nothing at the end of child documents
1394 if (maintext && buf.masterBuffer() != &buf)
1396 // end of main text: also insert a \clearpage (see #5386)
1398 os << "\n\\clearpage\n\\end{CJK}\n";
1402 state->open_encoding_ = none;
1406 // FIXME: If we are in an inset and the switch happened outside this inset,
1407 // do not switch back at the end of the inset (bug #8479)
1408 // The following attempt does not help with listings-caption in a CJK document:
1409 // if (runparams_in.local_font != 0
1410 // && runparams_in.encoding == runparams_in.local_font->language()->encoding())
1413 state->open_encoding_ = none;
1423 // Information about local language is stored as a font feature.
1424 // If this is the last paragraph of the inset and a local_font was set upon entering
1425 // and we are mixing encodings ("auto-legacy" or "auto-legacy-plain" and no XeTeX or LuaTeX),
1426 // ensure the encoding is set back to the default encoding of the local language.
1427 if (runparams.isLastPar && runparams_in.local_font != nullptr
1428 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1429 && (bparams.inputenc == "auto-legacy" || bparams.inputenc == "auto-legacy-plain")
1430 && !runparams.isFullUnicode()
1432 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1433 os << setEncoding(runparams_in.encoding->iconvName());
1435 // Otherwise, the current encoding should be set for the next paragraph.
1437 runparams_in.encoding = runparams.encoding;
1439 // Also pass the post_macros upstream
1440 runparams_in.post_macro = runparams.post_macro;
1441 // These need to be passed upstream as well
1442 runparams_in.need_maketitle = runparams.need_maketitle;
1443 runparams_in.have_maketitle = runparams.have_maketitle;
1446 // we don't need a newline for the last paragraph!!!
1447 // Note from JMarc: we will re-add a \n explicitly in
1448 // TeXEnvironment, because it is needed in this case
1449 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1450 Layout const & next_layout = nextpar->layout();
1451 if (!text.inset().getLayout().parbreakIgnored() && !merged_par)
1452 // Make sure to start a new line
1454 // A newline '\n' is always output before a command,
1455 // so avoid doubling it.
1456 if (!next_layout.isCommand()) {
1457 // Here we now try to avoid spurious empty lines by
1458 // outputting a paragraph break only if: (case 1) the
1459 // paragraph style allows parbreaks and no \begin, \end
1460 // or \item tags are going to follow (i.e., if the next
1461 // isn't the first or the current isn't the last
1462 // paragraph of an environment or itemize) and the
1463 // depth and alignment of the following paragraph is
1464 // unchanged, or (case 2) the following is a
1465 // non-environment paragraph whose depth is increased
1466 // but whose alignment is unchanged, or (case 3) the
1467 // paragraph is not an environment and the next one is a
1468 // non-itemize-like env at lower depth, or (case 4) the
1469 // paragraph is a command not followed by an environment
1470 // and the alignment of the current and next paragraph
1471 // is unchanged, or (case 5) the current alignment is
1472 // changed and a standard paragraph follows.
1473 DocumentClass const & tclass = bparams.documentClass();
1474 if ((style == next_layout
1475 && !style.parbreak_is_newline
1476 && !text.inset().getLayout().parbreakIsNewline()
1477 && !text.inset().getLayout().parbreakIgnored()
1478 && style.latextype != LATEX_ITEM_ENVIRONMENT
1479 && style.latextype != LATEX_LIST_ENVIRONMENT
1480 && style.align == par.getAlign(bparams)
1481 && nextpar->getDepth() == par.getDepth()
1482 && nextpar->getAlign(bparams) == par.getAlign(bparams))
1483 || (!next_layout.isEnvironment()
1484 && nextpar->getDepth() > par.getDepth()
1485 && nextpar->getAlign(bparams) == next_layout.align)
1486 || (!style.isEnvironment()
1487 && next_layout.latextype == LATEX_ENVIRONMENT
1488 && nextpar->getDepth() < par.getDepth())
1489 || (style.isCommand()
1490 && !next_layout.isEnvironment()
1491 && style.align == par.getAlign(bparams)
1492 && next_layout.align == nextpar->getAlign(bparams))
1493 || (style.align != par.getAlign(bparams)
1494 && tclass.isDefaultLayout(next_layout))) {
1495 // and omit paragraph break if it has been deleted with ct
1496 // and changes are not shown in output
1503 // Reset language nesting level after intitle command
1504 if (intitle_command)
1505 state->nest_level_ -= 1;
1507 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1508 << &par << " next " << nextpar);
1514 // LaTeX all paragraphs
1515 void latexParagraphs(Buffer const & buf,
1518 OutputParams const & runparams,
1519 string const & everypar)
1521 LASSERT(runparams.par_begin <= runparams.par_end,
1522 { os << "% LaTeX Output Error\n"; return; } );
1524 BufferParams const & bparams = buf.params();
1525 BufferParams const & mparams = buf.masterParams();
1527 bool const maintext = text.isMainText();
1528 bool const is_child = buf.masterBuffer() != &buf;
1529 bool const multibib_child = maintext && is_child
1530 && mparams.multibib == "child";
1532 if (multibib_child && mparams.useBiblatex())
1533 os << "\\newrefsection";
1534 else if (multibib_child && mparams.useBibtopic()
1535 && !buf.masterBibInfo().empty()) {
1536 os << "\\begin{btUnit}\n";
1537 runparams.openbtUnit = true;
1540 // Open a CJK environment at the beginning of the main buffer
1541 // if the document's main encoding requires the CJK package
1542 // or the document encoding is utf8 and the CJK package is required
1543 // (but not in child documents or documents using system fonts):
1544 OutputState * state = getOutputState();
1545 if (maintext && !is_child && !bparams.useNonTeXFonts
1546 && (bparams.encoding().package() == Encoding::CJK
1547 || (bparams.encoding().name() == "utf8"
1548 && runparams.use_CJK))
1550 docstring const cjkenc = bparams.encoding().iconvName() == "UTF-8"
1551 ? from_ascii("UTF8")
1552 : from_ascii(bparams.encoding().latexName());
1553 os << "\\begin{CJK}{" << cjkenc
1554 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1555 state->open_encoding_ = CJK;
1557 // if "auto begin" is switched off, explicitly switch the
1558 // language on at start
1559 string const mainlang = runparams.use_polyglossia
1560 ? getPolyglossiaEnvName(bparams.language)
1561 : bparams.language->babel();
1562 string const lang_begin_command = runparams.use_polyglossia ?
1563 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1564 string const lang_end_command = runparams.use_polyglossia ?
1565 "\\end{$$lang}" : lyxrc.language_command_end;
1566 bool const using_begin_end = runparams.use_polyglossia ||
1567 !lang_end_command.empty();
1569 if (maintext && !lyxrc.language_auto_begin &&
1570 !mainlang.empty()) {
1572 string bc = runparams.use_polyglossia ?
1573 getPolyglossiaBegin(lang_begin_command, mainlang,
1574 bparams.language->polyglossiaOpts())
1575 : subst(lang_begin_command, "$$lang", mainlang);
1578 if (using_begin_end)
1579 pushLanguageName(mainlang);
1582 ParagraphList const & paragraphs = text.paragraphs();
1584 if (runparams.par_begin == runparams.par_end) {
1585 // The full doc will be exported but it is easier to just rely on
1586 // runparams range parameters that will be passed TeXEnvironment.
1587 runparams.par_begin = 0;
1588 runparams.par_end = static_cast<int>(paragraphs.size());
1591 pit_type pit = runparams.par_begin;
1592 // lastpit is for the language check after the loop.
1593 pit_type lastpit = pit;
1594 DocumentClass const & tclass = bparams.documentClass();
1596 // Did we already warn about inTitle layout mixing? (we only warn once)
1597 bool gave_layout_warning = false;
1598 for (; pit < runparams.par_end; ++pit) {
1600 ParagraphList::const_iterator par = paragraphs.iterator_at(pit);
1602 // FIXME This check should not be needed. We should
1603 // perhaps issue an error if it is.
1604 Layout const & layout = text.inset().forcePlainLayout() ?
1605 tclass.plainLayout() : par->layout();
1607 if (layout.intitle) {
1608 if (runparams.have_maketitle) {
1609 if (!gave_layout_warning && !runparams.dryrun) {
1610 gave_layout_warning = true;
1611 frontend::Alert::warning(_("Error in latexParagraphs"),
1612 bformat(_("You are using at least one "
1613 "layout (%1$s) intended for the title, "
1614 "after using non-title layouts. This "
1615 "could lead to missing or incorrect output."
1618 } else if (!runparams.need_maketitle) {
1619 runparams.need_maketitle = true;
1620 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1622 << from_ascii(tclass.titlename())
1626 } else if (runparams.need_maketitle && !runparams.have_maketitle
1627 && !layout.inpreamble && !text.inset().isInTitle()) {
1628 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1629 os << "\\end{" << from_ascii(tclass.titlename())
1633 os << "\\" << from_ascii(tclass.titlename())
1636 runparams.have_maketitle = true;
1637 runparams.need_maketitle = false;
1640 if (layout.isCommand() && !layout.latexname().empty()
1641 && layout.latexname() == bparams.multibib) {
1642 if (runparams.openbtUnit)
1643 os << "\\end{btUnit}\n";
1644 if (!bparams.useBiblatex()
1645 && !buf.masterBibInfo().empty()) {
1646 os << '\n' << "\\begin{btUnit}\n";
1647 runparams.openbtUnit = true;
1651 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1652 // This is a standard top level paragraph, TeX it and continue.
1653 TeXOnePar(buf, text, pit, os, runparams, everypar);
1657 // Do not output empty environments if the whole paragraph has
1658 // been deleted with ct and changes are not output.
1659 if (size_t(pit + 1) < paragraphs.size()) {
1660 ParagraphList::const_iterator nextpar = paragraphs.iterator_at(pit + 1);
1661 Paragraph const & cpar = paragraphs.at(pit);
1662 if ((par->layout() != nextpar->layout()
1663 || par->params().depth() == nextpar->params().depth()
1664 || par->params().leftIndent() == nextpar->params().leftIndent())
1665 && !runparams.for_search && !cpar.empty()
1666 && cpar.isDeleted(0, cpar.size()) && !bparams.output_changes) {
1667 if (!cpar.parEndChange().deleted())
1673 TeXEnvironmentData const data =
1674 prepareEnvironment(buf, text, par, os, runparams);
1675 // pit can be changed in TeXEnvironment.
1676 TeXEnvironment(buf, text, runparams, pit, os);
1677 finishEnvironment(os, runparams, data);
1680 // FIXME: uncomment the content or remove this block
1681 if (pit == runparams.par_end) {
1682 // Make sure that the last paragraph is
1683 // correctly terminated (because TeXOnePar does
1684 // not add a \n in this case)
1688 // It might be that we only have a title in this document.
1689 // But if we're in an inset, this is not the end of
1690 // the document. (There may be some other checks of this
1691 // kind that are needed.)
1692 if (runparams.need_maketitle && !runparams.have_maketitle && maintext) {
1693 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1694 os << "\\end{" << from_ascii(tclass.titlename())
1697 os << "\\" << from_ascii(tclass.titlename())
1702 if (maintext && !is_child && runparams.openbtUnit)
1703 os << "\\end{btUnit}\n";
1705 // if "auto end" is switched off, explicitly close the language at the end
1706 // but only if the last par is in a babel or polyglossia language
1707 Language const * const lastpar_language =
1708 paragraphs.at(lastpit).getParLanguage(bparams);
1709 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1710 lastpar_language->encoding()->package() != Encoding::CJK) {
1711 os << from_utf8(subst(lang_end_command,
1715 // If we have language_auto_begin, the stack will
1716 // already be empty, nothing to pop()
1717 if (using_begin_end && !lyxrc.language_auto_begin)
1721 // If the last paragraph is an environment, we'll have to close
1722 // CJK at the very end to do proper nesting.
1723 if (maintext && !is_child && state->open_encoding_ == CJK) {
1724 os << "\\clearpage\n\\end{CJK}\n";
1725 state->open_encoding_ = none;
1727 // Likewise for polyglossia or when using begin/end commands
1728 // or at the very end of an active branch inset with a language switch
1729 Language const * const outer_language = (runparams.local_font != nullptr)
1730 ? runparams.local_font->language() : bparams.language;
1731 string const & prev_lang = runparams.use_polyglossia
1732 ? getPolyglossiaEnvName(outer_language)
1733 : outer_language->babel();
1734 string const lastpar_lang = runparams.use_polyglossia ?
1735 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1736 string const & cur_lang = openLanguageName(state);
1737 if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1738 || (maintext && !is_child)) && !cur_lang.empty()) {
1739 os << from_utf8(subst(lang_end_command,
1743 if (using_begin_end)
1745 } else if (runparams.inbranch && !using_begin_end
1746 && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1747 // with !using_begin_end, cur_lang is empty, so we need to
1748 // compare against the paragraph language (and we are in the
1749 // last paragraph at this point)
1750 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1753 // reset inherited encoding
1754 if (state->cjk_inherited_ > 0) {
1755 state->cjk_inherited_ -= 1;
1756 if (state->cjk_inherited_ == 0)
1757 state->open_encoding_ = CJK;
1760 if (multibib_child && mparams.useBibtopic()) {
1761 os << "\\end{btUnit}\n";
1762 runparams.openbtUnit = false;
1766 // Switch the input encoding for some part(s) of the document.
1767 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1768 OutputParams const & runparams, Encoding const & newEnc,
1769 bool force, bool noswitchmacro)
1771 // Never switch encoding with XeTeX/LuaTeX
1772 // or if we're in a moving argument or inherit the outer encoding.
1773 if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1774 return make_pair(false, 0);
1776 // Only switch for auto-selected legacy encodings (inputenc setting
1777 // "auto-legacy" or "auto-legacy-plain").
1778 // The "listings" environment can force a switch also with other
1779 // encoding settings (it does not support variable width encodings
1780 // (utf8, jis, ...) under 8-bit latex engines).
1781 if (!force && ((bparams.inputenc != "auto-legacy" && bparams.inputenc != "auto-legacy-plain")
1782 || runparams.moving_arg))
1783 return make_pair(false, 0);
1785 Encoding const & oldEnc = *runparams.encoding;
1786 // Do not switch, if the encoding is unchanged or switching is not supported.
1787 if (oldEnc.name() == newEnc.name()
1788 || oldEnc.package() == Encoding::japanese
1789 || oldEnc.package() == Encoding::none
1790 || newEnc.package() == Encoding::none
1791 || runparams.for_search)
1792 return make_pair(false, 0);
1793 // FIXME We ignore encoding switches from/to encodings that do
1794 // neither support the inputenc package nor the CJK package here.
1795 // This may fail for characters not supported by "unicodesymbols"
1796 // or for non-ASCII characters in "listings"
1797 // but it is the best we can do.
1800 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1801 << oldEnc.name() << " to " << newEnc.name());
1802 os << setEncoding(newEnc.iconvName());
1803 if (bparams.inputenc == "auto-legacy-plain")
1804 return make_pair(true, 0);
1806 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1807 OutputState * state = getOutputState();
1808 switch (newEnc.package()) {
1809 case Encoding::none:
1810 case Encoding::japanese:
1811 // shouldn't ever reach here (see above) but avoids warning.
1812 return make_pair(true, 0);
1813 case Encoding::inputenc: {
1814 size_t count = inputenc_arg.length();
1815 if (oldEnc.package() == Encoding::CJK &&
1816 state->open_encoding_ == CJK) {
1818 state->open_encoding_ = none;
1821 else if (oldEnc.package() == Encoding::inputenc &&
1822 state->open_encoding_ == inputenc) {
1824 state->open_encoding_ = none;
1827 if (runparams.local_font != nullptr
1828 && oldEnc.package() == Encoding::CJK) {
1829 // within insets, \inputenc switches need
1830 // to be embraced within \bgroup...\egroup;
1834 state->open_encoding_ = inputenc;
1837 return make_pair(true, count);
1838 os << "\\inputencoding{" << inputenc_arg << '}';
1839 return make_pair(true, count + 16);
1841 case Encoding::CJK: {
1842 size_t count = inputenc_arg.length();
1843 if (oldEnc.package() == Encoding::CJK &&
1844 state->open_encoding_ == CJK) {
1848 if (oldEnc.package() == Encoding::inputenc &&
1849 state->open_encoding_ == inputenc) {
1853 os << "\\begin{CJK}{"
1854 << from_ascii(newEnc.latexName()) << "}{"
1855 << from_ascii(bparams.fonts_cjk) << "}";
1856 state->open_encoding_ = CJK;
1857 return make_pair(true, count + 15);
1860 // Dead code to avoid a warning:
1861 return make_pair(true, 0);