2 * \file output_latex.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
13 #include "output_latex.h"
16 #include "BufferParams.h"
19 #include "InsetList.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "TextClass.h"
28 #include "insets/InsetBibitem.h"
29 #include "insets/InsetArgument.h"
31 #include "frontends/alert.h"
33 #include "support/lassert.h"
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/lstrings.h"
37 #include "support/lyxalgo.h"
38 #include "support/textutils.h"
39 #include "support/gettext.h"
41 #include <QThreadStorage>
47 using namespace lyx::support;
63 OutputState() : open_encoding_(none), cjk_inherited_(0),
64 prev_env_language_(0), nest_level_(0)
67 OpenEncoding open_encoding_;
69 Language const * prev_env_language_;
71 stack<int> lang_switch_depth_; // Both are always empty when
72 stack<string> open_polyglossia_lang_; // not using polyglossia
76 OutputState * getOutputState()
78 // FIXME An instance of OutputState should be kept around for each export
79 // instead of using local thread storage
80 static QThreadStorage<OutputState *> outputstate;
81 if (!outputstate.hasLocalData())
82 outputstate.setLocalData(new OutputState);
83 return outputstate.localData();
87 string const & openPolyglossiaLang(OutputState const * state)
89 // Return a reference to the last active language opened with
90 // polyglossia. If none or when using babel, return a reference
91 // to an empty string.
93 static string const empty;
95 return state->open_polyglossia_lang_.empty()
97 : state->open_polyglossia_lang_.top();
101 bool atSameLastLangSwitchDepth(OutputState const * state)
103 // Return true if the actual nest level is the same at which the
104 // language was switched when using polyglossia. Instead, return
105 // always true when using babel.
107 return state->lang_switch_depth_.size() == 0
109 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
113 bool isLocalSwitch(OutputState const * state)
115 // Return true if the language was opened by the \text<lang> command.
117 return state->lang_switch_depth_.size()
118 && state->lang_switch_depth_.top() < 0;
122 bool langOpenedAtThisLevel(OutputState const * state)
124 // Return true if the language was opened at the current nesting level.
126 return state->lang_switch_depth_.size()
127 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
131 string const getPolyglossiaEnvName(Language const * lang)
133 string result = lang->polyglossia();
134 if (result == "arabic")
135 // exceptional spelling; see polyglossia docs.
141 string const getPolyglossiaBegin(string const & lang_begin_command,
142 string const & lang, string const & opts)
146 result = subst(lang_begin_command, "$$lang", lang);
147 string options = opts.empty() ?
148 string() : "[" + opts + "]";
149 result = subst(result, "$$opts", options);
155 struct TeXEnvironmentData
158 Layout const * style;
159 Language const * par_language;
160 Encoding const * prev_encoding;
161 bool leftindent_open;
165 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
167 ParagraphList::const_iterator pit,
169 OutputParams const & runparams)
171 TeXEnvironmentData data;
173 BufferParams const & bparams = buf.params();
175 // FIXME This test should not be necessary.
176 // We should perhaps issue an error if it is.
177 Layout const & style = text.inset().forcePlainLayout() ?
178 bparams.documentClass().plainLayout() : pit->layout();
180 ParagraphList const & paragraphs = text.paragraphs();
181 ParagraphList::const_iterator const priorpit =
182 pit == paragraphs.begin() ? pit : prev(pit, 1);
184 OutputState * state = getOutputState();
185 bool const use_prev_env_language = state->prev_env_language_ != 0
186 && priorpit->layout().isEnvironment()
187 && (priorpit->getDepth() > pit->getDepth()
188 || (priorpit->getDepth() == pit->getDepth()
189 && priorpit->layout() != pit->layout()));
191 data.prev_encoding = runparams.encoding;
192 data.par_language = pit->getParLanguage(bparams);
193 Language const * const doc_language = bparams.language;
194 Language const * const prev_par_language =
195 (pit != paragraphs.begin())
196 ? (use_prev_env_language ? state->prev_env_language_
197 : priorpit->getParLanguage(bparams))
200 bool const use_polyglossia = runparams.use_polyglossia;
201 string const par_lang = use_polyglossia ?
202 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
203 string const prev_par_lang = use_polyglossia ?
204 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
205 string const doc_lang = use_polyglossia ?
206 getPolyglossiaEnvName(doc_language) : doc_language->babel();
207 string const lang_begin_command = use_polyglossia ?
208 "\\begin{$$lang}" : lyxrc.language_command_begin;
209 string const lang_end_command = use_polyglossia ?
210 "\\end{$$lang}" : lyxrc.language_command_end;
212 // For polyglossia, switch language outside of environment, if possible.
213 if (par_lang != prev_par_lang) {
214 if (!lang_end_command.empty() &&
215 prev_par_lang != doc_lang &&
216 atSameLastLangSwitchDepth(state) &&
217 !prev_par_lang.empty()) {
218 os << from_ascii(subst(
222 // the '%' is necessary to prevent unwanted whitespace
225 popPolyglossiaLang();
228 // If no language was explicitly opened and we are using
229 // polyglossia, then the current polyglossia language is
230 // the document language.
231 string const & pol_lang = use_polyglossia
232 && state->lang_switch_depth_.size()
233 ? openPolyglossiaLang(state)
236 if ((lang_end_command.empty() ||
237 par_lang != doc_lang ||
238 par_lang != pol_lang) &&
240 string bc = use_polyglossia ?
241 getPolyglossiaBegin(lang_begin_command, par_lang,
242 data.par_language->polyglossiaOpts())
243 : subst(lang_begin_command, "$$lang", par_lang);
245 // the '%' is necessary to prevent unwanted whitespace
248 pushPolyglossiaLang(par_lang);
252 data.leftindent_open = false;
253 if (!pit->params().leftIndent().zero()) {
254 os << "\\begin{LyXParagraphLeftIndent}{"
255 << from_ascii(pit->params().leftIndent().asLatexString())
257 data.leftindent_open = true;
260 if (style.isEnvironment()) {
261 state->nest_level_ += 1;
262 os << "\\begin{" << from_ascii(style.latexname()) << '}';
263 if (!style.latexargs().empty()) {
264 OutputParams rp = runparams;
265 rp.local_font = &pit->getFirstFontSettings(bparams);
266 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
268 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
270 << pit->params().labelWidthString()
272 } else if (style.labeltype == LABEL_BIBLIO) {
273 if (pit->params().labelWidthString().empty())
274 os << '{' << bibitemWidest(buf, runparams) << "}\n";
277 << pit->params().labelWidthString()
280 os << from_ascii(style.latexparam()) << '\n';
284 // in multilingual environments, the CJK tags have to be nested properly
285 data.cjk_nested = false;
286 if (data.par_language->encoding()->package() == Encoding::CJK &&
287 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
288 if (prev_par_language->encoding()->package() == Encoding::CJK)
289 os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
290 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
291 state->open_encoding_ = CJK;
292 data.cjk_nested = true;
298 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
299 TeXEnvironmentData const & data)
301 OutputState * state = getOutputState();
302 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
303 if (state->open_encoding_ == CJK && data.cjk_nested) {
304 // We need to close the encoding even if it does not change
305 // to do correct environment nesting
306 os << "\\end{CJK}\n";
307 state->open_encoding_ = none;
310 if (data.style->isEnvironment()) {
312 // Close any polyglossia language opened at this nest level
313 if (runparams.use_polyglossia) {
314 while (langOpenedAtThisLevel(state)) {
315 if (isLocalSwitch(state)) {
319 << openPolyglossiaLang(state)
322 popPolyglossiaLang();
325 state->nest_level_ -= 1;
326 os << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
327 state->prev_env_language_ = data.par_language;
328 if (runparams.encoding != data.prev_encoding) {
329 runparams.encoding = data.prev_encoding;
330 os << setEncoding(data.prev_encoding->iconvName());
334 if (data.leftindent_open) {
335 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
336 state->prev_env_language_ = data.par_language;
337 if (runparams.encoding != data.prev_encoding) {
338 runparams.encoding = data.prev_encoding;
339 os << setEncoding(data.prev_encoding->iconvName());
343 // Check whether we should output a blank line after the environment
344 if (!data.style->nextnoindent)
349 void TeXEnvironment(Buffer const & buf, Text const & text,
350 OutputParams const & runparams,
351 pit_type & pit, otexstream & os)
353 ParagraphList const & paragraphs = text.paragraphs();
354 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
355 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
357 Layout const & current_layout = par->layout();
358 depth_type const current_depth = par->params().depth();
359 Length const & current_left_indent = par->params().leftIndent();
361 // This is for debugging purpose at the end.
362 pit_type const par_begin = pit;
363 for (; pit < runparams.par_end; ++pit) {
364 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
366 // check first if this is an higher depth paragraph.
367 bool go_out = (par->params().depth() < current_depth);
368 if (par->params().depth() == current_depth) {
369 // This environment is finished.
370 go_out |= (par->layout() != current_layout);
371 go_out |= (par->params().leftIndent() != current_left_indent);
374 // nothing to do here, restore pit and go out.
379 if (par->layout() == current_layout
380 && par->params().depth() == current_depth
381 && par->params().leftIndent() == current_left_indent) {
382 // We are still in the same environment so TeXOnePar and continue;
383 TeXOnePar(buf, text, pit, os, runparams);
387 // We are now in a deeper environment.
388 // Either par->layout() != current_layout
389 // Or par->params().depth() > current_depth
390 // Or par->params().leftIndent() != current_left_indent)
392 // FIXME This test should not be necessary.
393 // We should perhaps issue an error if it is.
394 bool const force_plain_layout = text.inset().forcePlainLayout();
395 Layout const & style = force_plain_layout
396 ? buf.params().documentClass().plainLayout()
399 if (!style.isEnvironment()) {
400 // This is a standard paragraph, no need to call TeXEnvironment.
401 TeXOnePar(buf, text, pit, os, runparams);
405 // This is a new environment.
406 TeXEnvironmentData const data =
407 prepareEnvironment(buf, text, par, os, runparams);
408 // Recursive call to TeXEnvironment!
409 TeXEnvironment(buf, text, runparams, pit, os);
410 finishEnvironment(os, runparams, data);
413 if (pit != runparams.par_end)
414 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
418 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
419 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
421 unsigned int const argnr = latexargs.size();
425 // Default and preset args are always output, so if they require
426 // other arguments, consider this.
427 Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
428 Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
429 for (; lit != lend; ++lit) {
430 Layout::latexarg arg = (*lit).second;
431 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
432 vector<string> req = getVectorFromString(arg.requires);
433 required.insert(required.end(), req.begin(), req.end());
437 for (unsigned int i = 1; i <= argnr; ++i) {
438 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
439 bool inserted = false;
440 if (lit != ilist.end()) {
441 InsetArgument const * ins = (*lit).second;
443 Layout::LaTeXArgMap::const_iterator const lait =
444 latexargs.find(ins->name());
445 if (lait != latexargs.end()) {
446 Layout::latexarg arg = (*lait).second;
447 docstring ldelim = arg.mandatory ?
448 from_ascii("{") : from_ascii("[");
449 docstring rdelim = arg.mandatory ?
450 from_ascii("}") : from_ascii("]");
451 if (!arg.ldelim.empty())
453 if (!arg.rdelim.empty())
455 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
461 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
462 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
463 for (; lait != laend; ++lait) {
464 string const name = prefix + convert<string>(i);
465 if ((*lait).first == name) {
466 Layout::latexarg arg = (*lait).second;
467 docstring preset = arg.presetarg;
468 if (!arg.defaultarg.empty()) {
471 preset += arg.defaultarg;
474 docstring ldelim = arg.ldelim.empty() ?
475 from_ascii("{") : arg.ldelim;
476 docstring rdelim = arg.rdelim.empty() ?
477 from_ascii("}") : arg.rdelim;
478 os << ldelim << preset << rdelim;
479 } else if (!preset.empty()) {
480 docstring ldelim = arg.ldelim.empty() ?
481 from_ascii("[") : arg.ldelim;
482 docstring rdelim = arg.rdelim.empty() ?
483 from_ascii("]") : arg.rdelim;
484 os << ldelim << preset << rdelim;
485 } else if (find(required.begin(), required.end(),
486 (*lait).first) != required.end()) {
487 docstring ldelim = arg.ldelim.empty() ?
488 from_ascii("[") : arg.ldelim;
489 docstring rdelim = arg.rdelim.empty() ?
490 from_ascii("]") : arg.rdelim;
491 os << ldelim << rdelim;
504 void pushPolyglossiaLang(string const & lang_name, bool localswitch)
506 OutputState * state = getOutputState();
508 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
509 state->lang_switch_depth_.push(nest_level);
510 state->open_polyglossia_lang_.push(lang_name);
514 void popPolyglossiaLang()
516 OutputState * state = getOutputState();
518 state->lang_switch_depth_.pop();
519 state->open_polyglossia_lang_.pop();
523 void latexArgInsets(Paragraph const & par, otexstream & os,
524 OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
526 map<int, InsetArgument const *> ilist;
527 vector<string> required;
529 InsetList::const_iterator it = par.insetList().begin();
530 InsetList::const_iterator end = par.insetList().end();
531 for (; it != end; ++it) {
532 if (it->inset->lyxCode() == ARG_CODE) {
533 InsetArgument const * ins =
534 static_cast<InsetArgument const *>(it->inset);
535 if (ins->name().empty())
536 LYXERR0("Error: Unnamed argument inset!");
538 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
539 unsigned int const nr = convert<unsigned int>(name);
541 Layout::LaTeXArgMap::const_iterator const lit =
542 latexargs.find(ins->name());
543 if (lit != latexargs.end()) {
544 Layout::latexarg const & arg = (*lit).second;
545 if (!arg.requires.empty()) {
546 vector<string> req = getVectorFromString(arg.requires);
547 required.insert(required.end(), req.begin(), req.end());
553 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
557 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
558 otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
559 string const & prefix)
561 map<int, InsetArgument const *> ilist;
562 vector<string> required;
564 depth_type const current_depth = pit->params().depth();
565 Layout const current_layout = pit->layout();
567 // get the first paragraph in sequence with this layout and depth
570 if (lyx::prev(pit, offset) == pars.begin())
572 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
573 if (priorpit->layout() == current_layout
574 && priorpit->params().depth() == current_depth)
580 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
582 for (; spit != pars.end(); ++spit) {
583 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
585 if (spit->params().depth() > current_depth)
587 InsetList::const_iterator it = spit->insetList().begin();
588 InsetList::const_iterator end = spit->insetList().end();
589 for (; it != end; ++it) {
590 if (it->inset->lyxCode() == ARG_CODE) {
591 InsetArgument const * ins =
592 static_cast<InsetArgument const *>(it->inset);
593 if (ins->name().empty())
594 LYXERR0("Error: Unnamed argument inset!");
596 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
597 unsigned int const nr = convert<unsigned int>(name);
598 if (ilist.find(nr) == ilist.end())
600 Layout::LaTeXArgMap::const_iterator const lit =
601 latexargs.find(ins->name());
602 if (lit != latexargs.end()) {
603 Layout::latexarg const & arg = (*lit).second;
604 if (!arg.requires.empty()) {
605 vector<string> req = getVectorFromString(arg.requires);
606 required.insert(required.end(), req.begin(), req.end());
613 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
618 // output the proper paragraph start according to latextype.
619 void parStartCommand(Paragraph const & par, otexstream & os,
620 OutputParams const & runparams, Layout const & style)
622 switch (style.latextype) {
624 os << '\\' << from_ascii(style.latexname());
627 if (!style.latexargs().empty())
628 latexArgInsets(par, os, runparams, style.latexargs());
629 os << from_ascii(style.latexparam());
631 case LATEX_ITEM_ENVIRONMENT:
632 case LATEX_LIST_ENVIRONMENT:
633 os << "\\" + style.itemcommand();
635 if (!style.itemargs().empty())
636 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
639 case LATEX_BIB_ENVIRONMENT:
640 // ignore this, the inset will write itself
649 // FIXME: this should be anonymous
650 void TeXOnePar(Buffer const & buf,
654 OutputParams const & runparams_in,
655 string const & everypar,
656 int start_pos, int end_pos)
658 BufferParams const & bparams = runparams_in.is_child
659 ? buf.masterParams() : buf.params();
660 ParagraphList const & paragraphs = text.paragraphs();
661 Paragraph const & par = paragraphs.at(pit);
662 // FIXME This check should not really be needed.
663 // Perhaps we should issue an error if it is.
664 Layout const & style = text.inset().forcePlainLayout() ?
665 bparams.documentClass().plainLayout() : par.layout();
667 if (style.inpreamble)
670 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
673 OutputParams runparams = runparams_in;
674 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
675 // We reinitialze par begin and end to be on the safe side
676 // with embedded inset as we don't know if they set those
678 runparams.par_begin = 0;
679 runparams.par_end = 0;
681 bool const maintext = text.isMainText();
682 // we are at the beginning of an inset and CJK is already open;
683 // we count inheritation levels to get the inset nesting right.
684 OutputState * state = getOutputState();
685 if (pit == 0 && !maintext
686 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
687 state->cjk_inherited_ += 1;
688 state->open_encoding_ = none;
691 if (text.inset().isPassThru()) {
692 Font const outerfont = text.outerFont(pit);
694 // No newline before first paragraph in this lyxtext
697 if (!text.inset().getLayout().parbreakIsNewline())
701 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
705 Paragraph const * nextpar = runparams.isLastPar
706 ? 0 : ¶graphs.at(pit + 1);
708 if (style.pass_thru) {
709 Font const outerfont = text.outerFont(pit);
710 parStartCommand(par, os, runparams, style);
712 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
714 // I did not create a parEndCommand for this minuscule
715 // task because in the other user of parStartCommand
716 // the code is different (JMarc)
717 if (style.isCommand())
721 if (!style.parbreak_is_newline) {
723 } else if (nextpar && !style.isEnvironment()) {
724 Layout const nextstyle = text.inset().forcePlainLayout()
725 ? bparams.documentClass().plainLayout()
727 if (nextstyle.name() != style.name())
734 // This paragraph's language
735 Language const * const par_language = par.getParLanguage(bparams);
736 Language const * const nextpar_language = nextpar ?
737 nextpar->getParLanguage(bparams) : 0;
738 // The document's language
739 Language const * const doc_language = bparams.language;
740 // The language that was in effect when the environment this paragraph is
741 // inside of was opened
742 Language const * const outer_language =
743 (runparams.local_font != 0) ?
744 runparams.local_font->language() : doc_language;
746 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
748 // The previous language that was in effect is the language of the
749 // previous paragraph, unless the previous paragraph is inside an
750 // environment with nesting depth greater than (or equal to, but with
751 // a different layout) the current one. If there is no previous
752 // paragraph, the previous language is the outer language.
753 bool const use_prev_env_language = state->prev_env_language_ != 0
755 && priorpar->layout().isEnvironment()
756 && (priorpar->getDepth() > par.getDepth()
757 || (priorpar->getDepth() == par.getDepth()
758 && priorpar->layout() != par.layout()));
759 Language const * const prev_language =
761 ? (use_prev_env_language ? state->prev_env_language_
762 : priorpar->getParLanguage(bparams))
766 bool const use_polyglossia = runparams.use_polyglossia;
767 string const par_lang = use_polyglossia ?
768 getPolyglossiaEnvName(par_language): par_language->babel();
769 string const prev_lang = use_polyglossia ?
770 getPolyglossiaEnvName(prev_language) : prev_language->babel();
771 string const outer_lang = use_polyglossia ?
772 getPolyglossiaEnvName(outer_language) : outer_language->babel();
773 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
774 getPolyglossiaEnvName(nextpar_language) :
775 nextpar_language->babel()) : string();
776 string lang_begin_command = use_polyglossia ?
777 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
778 string lang_end_command = use_polyglossia ?
779 "\\end{$$lang}" : lyxrc.language_command_end;
780 // the '%' is necessary to prevent unwanted whitespace
781 string lang_command_termination = "%\n";
783 // In some insets (such as Arguments), we cannot use \selectlanguage
784 bool const localswitch = text.inset().forceLocalFontSwitch()
785 || (use_polyglossia && text.inset().forcePlainLayout());
787 lang_begin_command = use_polyglossia ?
788 "\\text$$lang$$opts{" : lyxrc.language_command_local;
789 lang_end_command = "}";
790 lang_command_termination.clear();
793 if (par_lang != prev_lang
794 // check if we already put language command in TeXEnvironment()
795 && !(style.isEnvironment()
796 && (pit == 0 || (priorpar->layout() != par.layout()
797 && priorpar->getDepth() <= par.getDepth())
798 || priorpar->getDepth() < par.getDepth())))
800 if (!lang_end_command.empty() &&
801 prev_lang != outer_lang &&
802 !prev_lang.empty() &&
803 (!use_polyglossia || !style.isEnvironment()))
805 os << from_ascii(subst(lang_end_command,
808 << lang_command_termination;
810 popPolyglossiaLang();
813 // We need to open a new language if we couldn't close the previous
814 // one (because there's no language_command_end); and even if we closed
815 // the previous one, if the current language is different than the
816 // outer_language (which is currently in effect once the previous one
818 if ((lang_end_command.empty() || par_lang != outer_lang
820 || (style.isEnvironment() && par_lang != prev_lang)))
821 && !par_lang.empty()) {
822 // If we're inside an inset, and that inset is within an \L or \R
823 // (or equivalents), then within the inset, too, any opposite
824 // language paragraph should appear within an \L or \R (in addition
825 // to, outside of, the normal language switch commands).
826 // This behavior is not correct for ArabTeX, though.
829 && par_language->lang() != "arabic_arabtex"
830 && outer_language->lang() != "arabic_arabtex"
831 // are we in an inset?
832 && runparams.local_font != 0
833 // is the inset within an \L or \R?
835 // FIXME: currently, we don't check this; this means that
836 // we'll have unnnecessary \L and \R commands, but that
837 // doesn't seem to hurt (though latex will complain)
839 // is this paragraph in the opposite direction?
840 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
841 // FIXME: I don't have a working copy of the Arabi package, so
842 // I'm not sure if the farsi and arabic_arabi stuff is correct
844 if (par_language->lang() == "farsi")
846 else if (outer_language->lang() == "farsi")
848 else if (par_language->lang() == "arabic_arabi")
850 else if (outer_language->lang() == "arabic_arabi")
852 // remaining RTL languages currently is hebrew
853 else if (par_language->rightToLeft())
858 // With CJK, the CJK tag has to be closed first (see below)
859 if (runparams.encoding->package() != Encoding::CJK
860 && par_lang != openPolyglossiaLang(state)
861 && !par_lang.empty()) {
862 string bc = use_polyglossia ?
863 getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
864 : subst(lang_begin_command, "$$lang", par_lang);
866 os << lang_command_termination;
868 pushPolyglossiaLang(par_lang, localswitch);
873 // Switch file encoding if necessary; no need to do this for "default"
874 // encoding, since this only affects the position of the outputted
875 // \inputencoding command; the encoding switch will occur when necessary
876 if (bparams.inputenc == "auto"
877 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
878 && runparams.encoding->package() != Encoding::none) {
879 // Look ahead for future encoding changes.
880 // We try to output them at the beginning of the paragraph,
881 // since the \inputencoding command is not allowed e.g. in
882 // sections. For this reason we only set runparams.moving_arg
883 // after checking for the encoding change, otherwise the
884 // change would be always avoided by switchEncoding().
885 for (pos_type i = 0; i < par.size(); ++i) {
886 char_type const c = par.getChar(i);
887 Encoding const * const encoding =
888 par.getFontSettings(bparams, i).language()->encoding();
889 if (encoding->package() != Encoding::CJK
890 && runparams.encoding->package() == Encoding::inputenc
895 // All characters before c are in the ASCII range, and
896 // c is non-ASCII (but no inset), so change the
897 // encoding to that required by the language of c.
898 // With CJK, only add switch if we have CJK content at the beginning
900 if (i != 0 && encoding->package() == Encoding::CJK)
903 pair<bool, int> enc_switch = switchEncoding(os.os(),
904 bparams, runparams, *encoding);
905 // the following is necessary after a CJK environment in a multilingual
906 // context (nesting issue).
907 if (par_language->encoding()->package() == Encoding::CJK
908 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
909 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
910 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
911 state->open_encoding_ = CJK;
913 if (encoding->package() != Encoding::none && enc_switch.first) {
914 if (enc_switch.second > 0) {
915 // the '%' is necessary to prevent unwanted whitespace
918 // With CJK, the CJK tag had to be closed first (see above)
919 if (runparams.encoding->package() == Encoding::CJK
920 && par_lang != openPolyglossiaLang(state)
921 && !par_lang.empty()) {
922 os << from_ascii(subst(
926 << lang_command_termination;
928 pushPolyglossiaLang(par_lang, localswitch);
930 runparams.encoding = encoding;
936 runparams.moving_arg |= style.needprotect;
937 Encoding const * const prev_encoding = runparams.encoding;
939 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
940 if (par.allowParagraphCustomization()) {
941 if (par.params().startOfAppendix()) {
942 os << "\n\\appendix\n";
945 if (!par.params().spacing().isDefault()
946 && (pit == 0 || !priorpar->hasSameLayout(par)))
948 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
952 if (style.isCommand()) {
957 parStartCommand(par, os, runparams, style);
958 Font const outerfont = text.outerFont(pit);
961 os << from_utf8(everypar);
962 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
964 // Make sure that \\par is done with the font of the last
965 // character if this has another size as the default.
966 // This is necessary because LaTeX (and LyX on the screen)
967 // calculates the space between the baselines according
968 // to this font. (Matthias)
970 // We must not change the font for the last paragraph
971 // of non-multipar insets, tabular cells or commands,
972 // since this produces unwanted whitespace.
974 Font const font = par.empty()
975 ? par.getLayoutFont(bparams, outerfont)
976 : par.getFont(bparams, par.size() - 1, outerfont);
978 bool const is_command = style.isCommand();
980 if (style.resfont.size() != font.fontInfo().size()
981 && (nextpar || maintext
982 || (text.inset().paragraphs().size() > 1
983 && text.inset().lyxCode() != CELL_CODE))
986 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
987 } else if (is_command) {
989 if (!style.postcommandargs().empty())
990 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
991 if (runparams.encoding != prev_encoding) {
992 runparams.encoding = prev_encoding;
993 os << setEncoding(prev_encoding->iconvName());
997 bool pending_newline = false;
998 bool unskip_newline = false;
999 bool close_lang_switch = false;
1000 switch (style.latextype) {
1001 case LATEX_ITEM_ENVIRONMENT:
1002 case LATEX_LIST_ENVIRONMENT:
1003 if ((nextpar && par_lang != nextpar_lang
1004 && nextpar->getDepth() == par.getDepth())
1005 || (atSameLastLangSwitchDepth(state) && nextpar
1006 && nextpar->getDepth() < par.getDepth()))
1007 close_lang_switch = use_polyglossia;
1008 if (nextpar && par.params().depth() < nextpar->params().depth())
1009 pending_newline = true;
1011 case LATEX_ENVIRONMENT: {
1012 // if its the last paragraph of the current environment
1013 // skip it otherwise fall through
1015 && ((nextpar->layout() != par.layout()
1016 || nextpar->params().depth() != par.params().depth())
1017 || (!use_polyglossia || par_lang != nextpar_lang)))
1019 close_lang_switch = use_polyglossia;
1024 // fall through possible
1026 // we don't need it for the last paragraph!!!
1028 pending_newline = true;
1031 if (par.allowParagraphCustomization()) {
1032 if (!par.params().spacing().isDefault()
1033 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1034 if (pending_newline)
1037 string const endtag =
1038 par.params().spacing().writeEnvirEnd(useSetSpace);
1039 if (prefixIs(endtag, "\\end{"))
1042 os << from_ascii(endtag);
1043 pending_newline = true;
1047 // Closing the language is needed for the last paragraph; it is also
1048 // needed if we're within an \L or \R that we may have opened above (not
1049 // necessarily in this paragraph) and are about to close.
1050 bool closing_rtl_ltr_environment = !use_polyglossia
1052 && (par_language->lang() != "arabic_arabtex"
1053 && outer_language->lang() != "arabic_arabtex")
1054 // have we opened an \L or \R environment?
1055 && runparams.local_font != 0
1056 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1057 // are we about to close the language?
1058 &&((nextpar && par_lang != nextpar_lang)
1059 || (runparams.isLastPar && par_lang != outer_lang));
1061 if (closing_rtl_ltr_environment
1062 || ((runparams.isLastPar || close_lang_switch)
1063 && (par_lang != outer_lang || (use_polyglossia
1064 && style.isEnvironment()
1065 && par_lang != nextpar_lang)))) {
1066 // Since \selectlanguage write the language to the aux file,
1067 // we need to reset the language at the end of footnote or
1070 if (pending_newline || close_lang_switch)
1073 // when the paragraph uses CJK, the language has to be closed earlier
1074 if (font.language()->encoding()->package() != Encoding::CJK) {
1075 if (lang_end_command.empty()) {
1076 // If this is a child, we should restore the
1077 // master language after the last paragraph.
1078 Language const * const current_language =
1079 (runparams.isLastPar && runparams.master_language)
1080 ? runparams.master_language
1082 string const current_lang = use_polyglossia
1083 ? getPolyglossiaEnvName(current_language)
1084 : current_language->babel();
1085 if (!current_lang.empty()
1086 && current_lang != openPolyglossiaLang(state)) {
1087 string bc = use_polyglossia ?
1088 getPolyglossiaBegin(lang_begin_command, current_lang,
1089 current_language->polyglossiaOpts())
1090 : subst(lang_begin_command, "$$lang", current_lang);
1092 pending_newline = !localswitch;
1093 unskip_newline = !localswitch;
1094 if (use_polyglossia)
1095 pushPolyglossiaLang(current_lang, localswitch);
1097 } else if (!par_lang.empty()) {
1098 // If we are in an environment, we have to close the "outer" language afterwards
1099 string const & pol_lang = openPolyglossiaLang(state);
1100 if (!style.isEnvironment()
1101 || (close_lang_switch
1102 && atSameLastLangSwitchDepth(state)
1103 && par_lang != outer_lang
1104 && (par_lang != pol_lang
1105 || (pol_lang != outer_lang
1107 && style != nextpar->layout())))
1108 || (atSameLastLangSwitchDepth(state)
1109 && state->lang_switch_depth_.size()
1110 && pol_lang != par_lang))
1112 if (use_polyglossia && !localswitch)
1114 os << from_ascii(subst(
1118 pending_newline = !localswitch;
1119 unskip_newline = !localswitch;
1120 if (use_polyglossia)
1121 popPolyglossiaLang();
1126 if (closing_rtl_ltr_environment)
1129 bool const last_was_separator =
1130 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1132 if (pending_newline) {
1134 // prevent unwanted whitespace
1136 if (!os.afterParbreak() && !last_was_separator)
1140 // if this is a CJK-paragraph and the next isn't, close CJK
1141 // also if the next paragraph is a multilingual environment (because of nesting)
1143 && state->open_encoding_ == CJK
1144 && (nextpar_language->encoding()->package() != Encoding::CJK
1145 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1146 // inbetween environments, CJK has to be closed later (nesting!)
1147 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1148 os << "\\end{CJK}\n";
1149 state->open_encoding_ = none;
1152 // If this is the last paragraph, close the CJK environment
1153 // if necessary. If it's an environment, we'll have to \end that first.
1154 if (runparams.isLastPar && !style.isEnvironment()) {
1155 switch (state->open_encoding_) {
1157 // do nothing at the end of child documents
1158 if (maintext && buf.masterBuffer() != &buf)
1162 os << "\n\\end{CJK}\n";
1166 state->open_encoding_ = none;
1171 state->open_encoding_ = none;
1181 // If this is the last paragraph, and a local_font was set upon entering
1182 // the inset, and we're using "auto" or "default" encoding, and not
1183 // compiling with XeTeX or LuaTeX, the encoding
1184 // should be set back to that local_font's encoding.
1185 if (runparams.isLastPar && runparams_in.local_font != 0
1186 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1187 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1188 && !runparams.isFullUnicode()
1190 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1191 os << setEncoding(runparams_in.encoding->iconvName());
1193 // Otherwise, the current encoding should be set for the next paragraph.
1195 runparams_in.encoding = runparams.encoding;
1198 // we don't need a newline for the last paragraph!!!
1199 // Note from JMarc: we will re-add a \n explicitly in
1200 // TeXEnvironment, because it is needed in this case
1201 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1202 // Make sure to start a new line
1204 Layout const & next_layout = nextpar->layout();
1205 // A newline '\n' is always output before a command,
1206 // so avoid doubling it.
1207 if (!next_layout.isCommand()) {
1208 // Here we now try to avoid spurious empty lines by
1209 // outputting a paragraph break only if: (case 1) the
1210 // paragraph style allows parbreaks and no \begin, \end
1211 // or \item tags are going to follow (i.e., if the next
1212 // isn't the first or the current isn't the last
1213 // paragraph of an environment or itemize) and the
1214 // depth and alignment of the following paragraph is
1215 // unchanged, or (case 2) the following is a
1216 // non-environment paragraph whose depth is increased
1217 // but whose alignment is unchanged, or (case 3) the
1218 // paragraph is not an environment and the next one is a
1219 // non-itemize-like env at lower depth, or (case 4) the
1220 // paragraph is a command not followed by an environment
1221 // and the alignment of the current and next paragraph
1222 // is unchanged, or (case 5) the current alignment is
1223 // changed and a standard paragraph follows.
1224 DocumentClass const & tclass = bparams.documentClass();
1225 if ((style == next_layout
1226 && !style.parbreak_is_newline
1227 && !text.inset().getLayout().parbreakIsNewline()
1228 && style.latextype != LATEX_ITEM_ENVIRONMENT
1229 && style.latextype != LATEX_LIST_ENVIRONMENT
1230 && style.align == par.getAlign()
1231 && nextpar->getDepth() == par.getDepth()
1232 && nextpar->getAlign() == par.getAlign())
1233 || (!next_layout.isEnvironment()
1234 && nextpar->getDepth() > par.getDepth()
1235 && nextpar->getAlign() == par.getAlign())
1236 || (!style.isEnvironment()
1237 && next_layout.latextype == LATEX_ENVIRONMENT
1238 && nextpar->getDepth() < par.getDepth())
1239 || (style.isCommand()
1240 && !next_layout.isEnvironment()
1241 && style.align == par.getAlign()
1242 && next_layout.align == nextpar->getAlign())
1243 || (style.align != par.getAlign()
1244 && tclass.isDefaultLayout(next_layout))) {
1250 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1251 << &par << " next " << nextpar);
1257 // LaTeX all paragraphs
1258 void latexParagraphs(Buffer const & buf,
1261 OutputParams const & runparams,
1262 string const & everypar)
1264 LASSERT(runparams.par_begin <= runparams.par_end,
1265 { os << "% LaTeX Output Error\n"; return; } );
1267 BufferParams const & bparams = buf.params();
1269 bool const maintext = text.isMainText();
1270 bool const is_child = buf.masterBuffer() != &buf;
1272 // Open a CJK environment at the beginning of the main buffer
1273 // if the document's language is a CJK language
1274 // (but not in child documents)
1275 OutputState * state = getOutputState();
1276 if (maintext && !is_child
1277 && bparams.encoding().package() == Encoding::CJK) {
1278 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1279 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1280 state->open_encoding_ = CJK;
1282 // if "auto begin" is switched off, explicitly switch the
1283 // language on at start
1284 string const mainlang = runparams.use_polyglossia
1285 ? getPolyglossiaEnvName(bparams.language)
1286 : bparams.language->babel();
1287 string const lang_begin_command = runparams.use_polyglossia ?
1288 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1290 if (maintext && !lyxrc.language_auto_begin &&
1291 !mainlang.empty()) {
1293 string bc = runparams.use_polyglossia ?
1294 getPolyglossiaBegin(lang_begin_command, mainlang,
1295 bparams.language->polyglossiaOpts())
1296 : subst(lang_begin_command, "$$lang", mainlang);
1299 if (runparams.use_polyglossia)
1300 pushPolyglossiaLang(mainlang);
1303 ParagraphList const & paragraphs = text.paragraphs();
1305 if (runparams.par_begin == runparams.par_end) {
1306 // The full doc will be exported but it is easier to just rely on
1307 // runparams range parameters that will be passed TeXEnvironment.
1308 runparams.par_begin = 0;
1309 runparams.par_end = paragraphs.size();
1312 pit_type pit = runparams.par_begin;
1313 // lastpit is for the language check after the loop.
1314 pit_type lastpit = pit;
1315 // variables used in the loop:
1316 bool was_title = false;
1317 bool already_title = false;
1318 DocumentClass const & tclass = bparams.documentClass();
1320 // Did we already warn about inTitle layout mixing? (we only warn once)
1321 bool gave_layout_warning = false;
1322 for (; pit < runparams.par_end; ++pit) {
1324 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1326 // FIXME This check should not be needed. We should
1327 // perhaps issue an error if it is.
1328 Layout const & layout = text.inset().forcePlainLayout() ?
1329 tclass.plainLayout() : par->layout();
1331 if (layout.intitle) {
1332 if (already_title) {
1333 if (!gave_layout_warning) {
1334 gave_layout_warning = true;
1335 frontend::Alert::warning(_("Error in latexParagraphs"),
1336 bformat(_("You are using at least one "
1337 "layout (%1$s) intended for the title, "
1338 "after using non-title layouts. This "
1339 "could lead to missing or incorrect output."
1342 } else if (!was_title) {
1344 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1346 << from_ascii(tclass.titlename())
1350 } else if (was_title && !already_title) {
1351 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1352 os << "\\end{" << from_ascii(tclass.titlename())
1356 os << "\\" << from_ascii(tclass.titlename())
1359 already_title = true;
1364 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1365 // This is a standard top level paragraph, TeX it and continue.
1366 TeXOnePar(buf, text, pit, os, runparams, everypar);
1370 TeXEnvironmentData const data =
1371 prepareEnvironment(buf, text, par, os, runparams);
1372 // pit can be changed in TeXEnvironment.
1373 TeXEnvironment(buf, text, runparams, pit, os);
1374 finishEnvironment(os, runparams, data);
1377 if (pit == runparams.par_end) {
1378 // Make sure that the last paragraph is
1379 // correctly terminated (because TeXOnePar does
1380 // not add a \n in this case)
1384 // It might be that we only have a title in this document
1385 if (was_title && !already_title) {
1386 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1387 os << "\\end{" << from_ascii(tclass.titlename())
1390 os << "\\" << from_ascii(tclass.titlename())
1395 // if "auto end" is switched off, explicitly close the language at the end
1396 // but only if the last par is in a babel or polyglossia language
1397 string const lang_end_command = runparams.use_polyglossia ?
1398 "\\end{$$lang}" : lyxrc.language_command_end;
1399 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1400 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1401 os << from_utf8(subst(lang_end_command,
1405 if (runparams.use_polyglossia)
1406 popPolyglossiaLang();
1409 // If the last paragraph is an environment, we'll have to close
1410 // CJK at the very end to do proper nesting.
1411 if (maintext && !is_child && state->open_encoding_ == CJK) {
1412 os << "\\end{CJK}\n";
1413 state->open_encoding_ = none;
1415 // Likewise for polyglossia
1416 string const & pol_lang = openPolyglossiaLang(state);
1417 if (maintext && !is_child && !pol_lang.empty()) {
1418 os << from_utf8(subst(lang_end_command,
1422 if (runparams.use_polyglossia)
1423 popPolyglossiaLang();
1426 // reset inherited encoding
1427 if (state->cjk_inherited_ > 0) {
1428 state->cjk_inherited_ -= 1;
1429 if (state->cjk_inherited_ == 0)
1430 state->open_encoding_ = CJK;
1435 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1436 OutputParams const & runparams, Encoding const & newEnc,
1439 // XeTeX/LuaTeX use only one encoding per document:
1440 // * with useNonTeXFonts: "utf8plain",
1441 // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1442 // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1443 if (runparams.isFullUnicode())
1444 return make_pair(false, 0);
1446 Encoding const & oldEnc = *runparams.encoding;
1447 bool moving_arg = runparams.moving_arg;
1448 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1449 bool const from_to_cjk =
1450 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1451 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1452 if (!force && !from_to_cjk
1453 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1454 return make_pair(false, 0);
1456 // Do nothing if the encoding is unchanged.
1457 if (oldEnc.name() == newEnc.name())
1458 return make_pair(false, 0);
1460 // FIXME We ignore encoding switches from/to encodings that do
1461 // neither support the inputenc package nor the CJK package here.
1462 // This does of course only work in special cases (e.g. switch from
1463 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1464 // but it is the best we can do
1465 if (oldEnc.package() == Encoding::none
1466 || newEnc.package() == Encoding::none)
1467 return make_pair(false, 0);
1469 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1470 << oldEnc.name() << " to " << newEnc.name());
1471 os << setEncoding(newEnc.iconvName());
1472 if (bparams.inputenc == "default")
1473 return make_pair(true, 0);
1475 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1476 OutputState * state = getOutputState();
1477 switch (newEnc.package()) {
1478 case Encoding::none:
1479 case Encoding::japanese:
1480 // shouldn't ever reach here, see above
1481 return make_pair(true, 0);
1482 case Encoding::inputenc: {
1483 int count = inputenc_arg.length();
1484 if (oldEnc.package() == Encoding::CJK &&
1485 state->open_encoding_ == CJK) {
1487 state->open_encoding_ = none;
1490 else if (oldEnc.package() == Encoding::inputenc &&
1491 state->open_encoding_ == inputenc) {
1493 state->open_encoding_ = none;
1496 if (runparams.local_font != 0
1497 && oldEnc.package() == Encoding::CJK) {
1498 // within insets, \inputenc switches need
1499 // to be embraced within \bgroup...\egroup;
1503 state->open_encoding_ = inputenc;
1505 // with the japanese option, inputenc is omitted.
1506 if (runparams.use_japanese)
1507 return make_pair(true, count);
1508 os << "\\inputencoding{" << inputenc_arg << '}';
1509 return make_pair(true, count + 16);
1511 case Encoding::CJK: {
1512 int count = inputenc_arg.length();
1513 if (oldEnc.package() == Encoding::CJK &&
1514 state->open_encoding_ == CJK) {
1518 if (oldEnc.package() == Encoding::inputenc &&
1519 state->open_encoding_ == inputenc) {
1523 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1524 << from_ascii(bparams.fonts_cjk) << "}";
1525 state->open_encoding_ = CJK;
1526 return make_pair(true, count + 15);
1529 // Dead code to avoid a warning:
1530 return make_pair(true, 0);