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 & openLanguageName(OutputState const * state)
89 // Return a reference to the last active language opened with
90 // polyglossia or when using begin/end commands. If none or when
91 // using babel with only a begin command, return a reference to
94 static string const empty;
96 return state->open_polyglossia_lang_.empty()
98 : state->open_polyglossia_lang_.top();
102 bool atSameLastLangSwitchDepth(OutputState const * state)
104 // Return true if the actual nest level is the same at which the
105 // language was switched when using polyglossia or begin/end
106 // commands. Instead, return always true when using babel with
107 // only a begin command.
109 return state->lang_switch_depth_.size() == 0
111 : abs(state->lang_switch_depth_.top()) == state->nest_level_;
115 bool isLocalSwitch(OutputState const * state)
117 // Return true if the language was opened by a local command switch.
119 return state->lang_switch_depth_.size()
120 && state->lang_switch_depth_.top() < 0;
124 bool langOpenedAtThisLevel(OutputState const * state)
126 // Return true if the language was opened at the current nesting level.
128 return state->lang_switch_depth_.size()
129 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
133 string const getPolyglossiaEnvName(Language const * lang)
135 string result = lang->polyglossia();
136 if (result == "arabic")
137 // exceptional spelling; see polyglossia docs.
143 string const getPolyglossiaBegin(string const & lang_begin_command,
144 string const & lang, string const & opts)
148 result = subst(lang_begin_command, "$$lang", lang);
149 string options = opts.empty() ?
150 string() : "[" + opts + "]";
151 result = subst(result, "$$opts", options);
157 struct TeXEnvironmentData
160 Layout const * style;
161 Language const * par_language;
162 Encoding const * prev_encoding;
163 bool leftindent_open;
167 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
169 ParagraphList::const_iterator pit,
171 OutputParams const & runparams)
173 TeXEnvironmentData data;
175 BufferParams const & bparams = buf.params();
177 // FIXME This test should not be necessary.
178 // We should perhaps issue an error if it is.
179 Layout const & style = text.inset().forcePlainLayout() ?
180 bparams.documentClass().plainLayout() : pit->layout();
182 ParagraphList const & paragraphs = text.paragraphs();
183 ParagraphList::const_iterator const priorpit =
184 pit == paragraphs.begin() ? pit : prev(pit, 1);
186 OutputState * state = getOutputState();
187 bool const use_prev_env_language = state->prev_env_language_ != 0
188 && priorpit->layout().isEnvironment()
189 && (priorpit->getDepth() > pit->getDepth()
190 || (priorpit->getDepth() == pit->getDepth()
191 && priorpit->layout() != pit->layout()));
193 data.prev_encoding = runparams.encoding;
194 data.par_language = pit->getParLanguage(bparams);
195 Language const * const doc_language = bparams.language;
196 Language const * const prev_par_language =
197 (pit != paragraphs.begin())
198 ? (use_prev_env_language ? state->prev_env_language_
199 : priorpit->getParLanguage(bparams))
202 bool const use_polyglossia = runparams.use_polyglossia;
203 string const par_lang = use_polyglossia ?
204 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
205 string const prev_par_lang = use_polyglossia ?
206 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
207 string const doc_lang = use_polyglossia ?
208 getPolyglossiaEnvName(doc_language) : doc_language->babel();
209 string const lang_begin_command = use_polyglossia ?
210 "\\begin{$$lang}" : lyxrc.language_command_begin;
211 string const lang_end_command = use_polyglossia ?
212 "\\end{$$lang}" : lyxrc.language_command_end;
213 bool const using_begin_end = use_polyglossia ||
214 !lang_end_command.empty();
216 // For polyglossia, switch language outside of environment, if possible.
217 if (par_lang != prev_par_lang) {
218 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
219 !lang_end_command.empty() &&
220 prev_par_lang != doc_lang &&
221 !prev_par_lang.empty()) {
222 os << from_ascii(subst(
226 // the '%' is necessary to prevent unwanted whitespace
232 // If no language was explicitly opened and we are using
233 // polyglossia or begin/end commands, then the current
234 // language is the document language.
235 string const & cur_lang = using_begin_end
236 && state->lang_switch_depth_.size()
237 ? openLanguageName(state)
240 if ((lang_end_command.empty() ||
241 par_lang != doc_lang ||
242 par_lang != cur_lang) &&
244 string bc = use_polyglossia ?
245 getPolyglossiaBegin(lang_begin_command, par_lang,
246 data.par_language->polyglossiaOpts())
247 : subst(lang_begin_command, "$$lang", par_lang);
249 // the '%' is necessary to prevent unwanted whitespace
252 pushLanguageName(par_lang);
256 data.leftindent_open = false;
257 if (!pit->params().leftIndent().zero()) {
258 os << "\\begin{LyXParagraphLeftIndent}{"
259 << from_ascii(pit->params().leftIndent().asLatexString())
261 data.leftindent_open = true;
264 if (style.isEnvironment()) {
265 state->nest_level_ += 1;
266 os << "\\begin{" << from_ascii(style.latexname()) << '}';
267 if (!style.latexargs().empty()) {
268 OutputParams rp = runparams;
269 rp.local_font = &pit->getFirstFontSettings(bparams);
270 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
272 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
274 << pit->params().labelWidthString()
276 } else if (style.labeltype == LABEL_BIBLIO) {
277 if (pit->params().labelWidthString().empty())
278 os << '{' << bibitemWidest(buf, runparams) << "}\n";
281 << pit->params().labelWidthString()
284 os << from_ascii(style.latexparam()) << '\n';
288 // in multilingual environments, the CJK tags have to be nested properly
289 data.cjk_nested = false;
290 if (data.par_language->encoding()->package() == Encoding::CJK &&
291 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
292 if (prev_par_language->encoding()->package() == Encoding::CJK)
293 os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
294 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
295 state->open_encoding_ = CJK;
296 data.cjk_nested = true;
302 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
303 TeXEnvironmentData const & data)
305 OutputState * state = getOutputState();
306 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
307 if (state->open_encoding_ == CJK && data.cjk_nested) {
308 // We need to close the encoding even if it does not change
309 // to do correct environment nesting
310 os << "\\end{CJK}\n";
311 state->open_encoding_ = none;
314 if (data.style->isEnvironment()) {
316 bool const using_begin_end =
317 runparams.use_polyglossia ||
318 !lyxrc.language_command_end.empty();
319 // Close any language opened at this nest level
320 if (using_begin_end) {
321 while (langOpenedAtThisLevel(state)) {
322 if (isLocalSwitch(state)) {
326 << openLanguageName(state)
332 state->nest_level_ -= 1;
333 os << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
334 state->prev_env_language_ = data.par_language;
335 if (runparams.encoding != data.prev_encoding) {
336 runparams.encoding = data.prev_encoding;
337 os << setEncoding(data.prev_encoding->iconvName());
341 if (data.leftindent_open) {
342 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
343 state->prev_env_language_ = data.par_language;
344 if (runparams.encoding != data.prev_encoding) {
345 runparams.encoding = data.prev_encoding;
346 os << setEncoding(data.prev_encoding->iconvName());
350 // Check whether we should output a blank line after the environment
351 if (!data.style->nextnoindent)
356 void TeXEnvironment(Buffer const & buf, Text const & text,
357 OutputParams const & runparams,
358 pit_type & pit, otexstream & os)
360 ParagraphList const & paragraphs = text.paragraphs();
361 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
362 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
364 Layout const & current_layout = par->layout();
365 depth_type const current_depth = par->params().depth();
366 Length const & current_left_indent = par->params().leftIndent();
368 // This is for debugging purpose at the end.
369 pit_type const par_begin = pit;
370 for (; pit < runparams.par_end; ++pit) {
371 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
373 // check first if this is an higher depth paragraph.
374 bool go_out = (par->params().depth() < current_depth);
375 if (par->params().depth() == current_depth) {
376 // This environment is finished.
377 go_out |= (par->layout() != current_layout);
378 go_out |= (par->params().leftIndent() != current_left_indent);
381 // nothing to do here, restore pit and go out.
386 if (par->layout() == current_layout
387 && par->params().depth() == current_depth
388 && par->params().leftIndent() == current_left_indent) {
389 // We are still in the same environment so TeXOnePar and continue;
390 TeXOnePar(buf, text, pit, os, runparams);
394 // We are now in a deeper environment.
395 // Either par->layout() != current_layout
396 // Or par->params().depth() > current_depth
397 // Or par->params().leftIndent() != current_left_indent)
399 // FIXME This test should not be necessary.
400 // We should perhaps issue an error if it is.
401 bool const force_plain_layout = text.inset().forcePlainLayout();
402 Layout const & style = force_plain_layout
403 ? buf.params().documentClass().plainLayout()
406 if (!style.isEnvironment()) {
407 // This is a standard paragraph, no need to call TeXEnvironment.
408 TeXOnePar(buf, text, pit, os, runparams);
412 // This is a new environment.
413 TeXEnvironmentData const data =
414 prepareEnvironment(buf, text, par, os, runparams);
415 // Recursive call to TeXEnvironment!
416 TeXEnvironment(buf, text, runparams, pit, os);
417 finishEnvironment(os, runparams, data);
420 if (pit != runparams.par_end)
421 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
425 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
426 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
428 unsigned int const argnr = latexargs.size();
432 // Default and preset args are always output, so if they require
433 // other arguments, consider this.
434 Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
435 Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
436 for (; lit != lend; ++lit) {
437 Layout::latexarg arg = (*lit).second;
438 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
439 vector<string> req = getVectorFromString(arg.requires);
440 required.insert(required.end(), req.begin(), req.end());
444 for (unsigned int i = 1; i <= argnr; ++i) {
445 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
446 bool inserted = false;
447 if (lit != ilist.end()) {
448 InsetArgument const * ins = (*lit).second;
450 Layout::LaTeXArgMap::const_iterator const lait =
451 latexargs.find(ins->name());
452 if (lait != latexargs.end()) {
453 Layout::latexarg arg = (*lait).second;
454 docstring ldelim = arg.mandatory ?
455 from_ascii("{") : from_ascii("[");
456 docstring rdelim = arg.mandatory ?
457 from_ascii("}") : from_ascii("]");
458 if (!arg.ldelim.empty())
460 if (!arg.rdelim.empty())
462 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
468 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
469 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
470 for (; lait != laend; ++lait) {
471 string const name = prefix + convert<string>(i);
472 if ((*lait).first == name) {
473 Layout::latexarg arg = (*lait).second;
474 docstring preset = arg.presetarg;
475 if (!arg.defaultarg.empty()) {
478 preset += arg.defaultarg;
481 docstring ldelim = arg.ldelim.empty() ?
482 from_ascii("{") : arg.ldelim;
483 docstring rdelim = arg.rdelim.empty() ?
484 from_ascii("}") : arg.rdelim;
485 os << ldelim << preset << rdelim;
486 } else if (!preset.empty()) {
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 << preset << rdelim;
492 } else if (find(required.begin(), required.end(),
493 (*lait).first) != required.end()) {
494 docstring ldelim = arg.ldelim.empty() ?
495 from_ascii("[") : arg.ldelim;
496 docstring rdelim = arg.rdelim.empty() ?
497 from_ascii("]") : arg.rdelim;
498 os << ldelim << rdelim;
511 void pushLanguageName(string const & lang_name, bool localswitch)
513 OutputState * state = getOutputState();
515 int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
516 state->lang_switch_depth_.push(nest_level);
517 state->open_polyglossia_lang_.push(lang_name);
521 void popLanguageName()
523 OutputState * state = getOutputState();
525 state->lang_switch_depth_.pop();
526 state->open_polyglossia_lang_.pop();
530 void latexArgInsets(Paragraph const & par, otexstream & os,
531 OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
533 map<int, InsetArgument const *> ilist;
534 vector<string> required;
536 InsetList::const_iterator it = par.insetList().begin();
537 InsetList::const_iterator end = par.insetList().end();
538 for (; it != end; ++it) {
539 if (it->inset->lyxCode() == ARG_CODE) {
540 InsetArgument const * ins =
541 static_cast<InsetArgument const *>(it->inset);
542 if (ins->name().empty())
543 LYXERR0("Error: Unnamed argument inset!");
545 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
546 unsigned int const nr = convert<unsigned int>(name);
548 Layout::LaTeXArgMap::const_iterator const lit =
549 latexargs.find(ins->name());
550 if (lit != latexargs.end()) {
551 Layout::latexarg const & arg = (*lit).second;
552 if (!arg.requires.empty()) {
553 vector<string> req = getVectorFromString(arg.requires);
554 required.insert(required.end(), req.begin(), req.end());
560 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
564 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
565 otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
566 string const & prefix)
568 map<int, InsetArgument const *> ilist;
569 vector<string> required;
571 depth_type const current_depth = pit->params().depth();
572 Layout const current_layout = pit->layout();
574 // get the first paragraph in sequence with this layout and depth
577 if (lyx::prev(pit, offset) == pars.begin())
579 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
580 if (priorpit->layout() == current_layout
581 && priorpit->params().depth() == current_depth)
587 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
589 for (; spit != pars.end(); ++spit) {
590 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
592 if (spit->params().depth() > current_depth)
594 InsetList::const_iterator it = spit->insetList().begin();
595 InsetList::const_iterator end = spit->insetList().end();
596 for (; it != end; ++it) {
597 if (it->inset->lyxCode() == ARG_CODE) {
598 InsetArgument const * ins =
599 static_cast<InsetArgument const *>(it->inset);
600 if (ins->name().empty())
601 LYXERR0("Error: Unnamed argument inset!");
603 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
604 unsigned int const nr = convert<unsigned int>(name);
605 if (ilist.find(nr) == ilist.end())
607 Layout::LaTeXArgMap::const_iterator const lit =
608 latexargs.find(ins->name());
609 if (lit != latexargs.end()) {
610 Layout::latexarg const & arg = (*lit).second;
611 if (!arg.requires.empty()) {
612 vector<string> req = getVectorFromString(arg.requires);
613 required.insert(required.end(), req.begin(), req.end());
620 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
625 // output the proper paragraph start according to latextype.
626 void parStartCommand(Paragraph const & par, otexstream & os,
627 OutputParams const & runparams, Layout const & style)
629 switch (style.latextype) {
631 os << '\\' << from_ascii(style.latexname());
634 if (!style.latexargs().empty())
635 latexArgInsets(par, os, runparams, style.latexargs());
636 os << from_ascii(style.latexparam());
638 case LATEX_ITEM_ENVIRONMENT:
639 case LATEX_LIST_ENVIRONMENT:
640 os << "\\" + style.itemcommand();
642 if (!style.itemargs().empty())
643 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
646 case LATEX_BIB_ENVIRONMENT:
647 // ignore this, the inset will write itself
656 // FIXME: this should be anonymous
657 void TeXOnePar(Buffer const & buf,
661 OutputParams const & runparams_in,
662 string const & everypar,
663 int start_pos, int end_pos)
665 BufferParams const & bparams = runparams_in.is_child
666 ? buf.masterParams() : buf.params();
667 ParagraphList const & paragraphs = text.paragraphs();
668 Paragraph const & par = paragraphs.at(pit);
669 // FIXME This check should not really be needed.
670 // Perhaps we should issue an error if it is.
671 Layout const & style = text.inset().forcePlainLayout() ?
672 bparams.documentClass().plainLayout() : par.layout();
674 if (style.inpreamble)
677 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
680 OutputParams runparams = runparams_in;
681 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
682 // We reinitialze par begin and end to be on the safe side
683 // with embedded inset as we don't know if they set those
685 runparams.par_begin = 0;
686 runparams.par_end = 0;
688 bool const maintext = text.isMainText();
689 // we are at the beginning of an inset and CJK is already open;
690 // we count inheritation levels to get the inset nesting right.
691 OutputState * state = getOutputState();
692 if (pit == 0 && !maintext
693 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
694 state->cjk_inherited_ += 1;
695 state->open_encoding_ = none;
698 if (text.inset().isPassThru()) {
699 Font const outerfont = text.outerFont(pit);
701 // No newline before first paragraph in this lyxtext
704 if (!text.inset().getLayout().parbreakIsNewline())
708 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
712 Paragraph const * nextpar = runparams.isLastPar
713 ? 0 : ¶graphs.at(pit + 1);
715 if (style.pass_thru) {
716 Font const outerfont = text.outerFont(pit);
717 parStartCommand(par, os, runparams, style);
719 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
721 // I did not create a parEndCommand for this minuscule
722 // task because in the other user of parStartCommand
723 // the code is different (JMarc)
724 if (style.isCommand())
728 if (!style.parbreak_is_newline) {
730 } else if (nextpar && !style.isEnvironment()) {
731 Layout const nextstyle = text.inset().forcePlainLayout()
732 ? bparams.documentClass().plainLayout()
734 if (nextstyle.name() != style.name())
741 // This paragraph's language
742 Language const * const par_language = par.getParLanguage(bparams);
743 Language const * const nextpar_language = nextpar ?
744 nextpar->getParLanguage(bparams) : 0;
745 // The document's language
746 Language const * const doc_language = bparams.language;
747 // The language that was in effect when the environment this paragraph is
748 // inside of was opened
749 Language const * const outer_language =
750 (runparams.local_font != 0) ?
751 runparams.local_font->language() : doc_language;
753 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
755 // The previous language that was in effect is the language of the
756 // previous paragraph, unless the previous paragraph is inside an
757 // environment with nesting depth greater than (or equal to, but with
758 // a different layout) the current one. If there is no previous
759 // paragraph, the previous language is the outer language.
760 bool const use_prev_env_language = state->prev_env_language_ != 0
762 && priorpar->layout().isEnvironment()
763 && (priorpar->getDepth() > par.getDepth()
764 || (priorpar->getDepth() == par.getDepth()
765 && priorpar->layout() != par.layout()));
766 Language const * const prev_language =
768 ? (use_prev_env_language ? state->prev_env_language_
769 : priorpar->getParLanguage(bparams))
773 bool const use_polyglossia = runparams.use_polyglossia;
774 string const par_lang = use_polyglossia ?
775 getPolyglossiaEnvName(par_language): par_language->babel();
776 string const prev_lang = use_polyglossia ?
777 getPolyglossiaEnvName(prev_language) : prev_language->babel();
778 string const outer_lang = use_polyglossia ?
779 getPolyglossiaEnvName(outer_language) : outer_language->babel();
780 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
781 getPolyglossiaEnvName(nextpar_language) :
782 nextpar_language->babel()) : string();
783 string lang_begin_command = use_polyglossia ?
784 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
785 string lang_end_command = use_polyglossia ?
786 "\\end{$$lang}" : lyxrc.language_command_end;
787 // the '%' is necessary to prevent unwanted whitespace
788 string lang_command_termination = "%\n";
789 bool const using_begin_end = use_polyglossia ||
790 !lang_end_command.empty();
792 // In some insets (such as Arguments), we cannot use \selectlanguage
793 bool const localswitch = text.inset().forceLocalFontSwitch()
794 || (using_begin_end && text.inset().forcePlainLayout());
796 lang_begin_command = use_polyglossia ?
797 "\\text$$lang$$opts{" : lyxrc.language_command_local;
798 lang_end_command = "}";
799 lang_command_termination.clear();
802 if (par_lang != prev_lang
803 // check if we already put language command in TeXEnvironment()
804 && !(style.isEnvironment()
805 && (pit == 0 || (priorpar->layout() != par.layout()
806 && priorpar->getDepth() <= par.getDepth())
807 || priorpar->getDepth() < par.getDepth())))
809 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
810 !lang_end_command.empty() &&
811 prev_lang != outer_lang &&
812 !prev_lang.empty() &&
813 (!using_begin_end || !style.isEnvironment()))
815 os << from_ascii(subst(lang_end_command,
818 << lang_command_termination;
823 // We need to open a new language if we couldn't close the previous
824 // one (because there's no language_command_end); and even if we closed
825 // the previous one, if the current language is different than the
826 // outer_language (which is currently in effect once the previous one
828 if ((lang_end_command.empty() || par_lang != outer_lang
830 || (style.isEnvironment() && par_lang != prev_lang)))
831 && !par_lang.empty()) {
832 // If we're inside an inset, and that inset is within an \L or \R
833 // (or equivalents), then within the inset, too, any opposite
834 // language paragraph should appear within an \L or \R (in addition
835 // to, outside of, the normal language switch commands).
836 // This behavior is not correct for ArabTeX, though.
839 && par_language->lang() != "arabic_arabtex"
840 && outer_language->lang() != "arabic_arabtex"
841 // are we in an inset?
842 && runparams.local_font != 0
843 // is the inset within an \L or \R?
845 // FIXME: currently, we don't check this; this means that
846 // we'll have unnnecessary \L and \R commands, but that
847 // doesn't seem to hurt (though latex will complain)
849 // is this paragraph in the opposite direction?
850 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
851 // FIXME: I don't have a working copy of the Arabi package, so
852 // I'm not sure if the farsi and arabic_arabi stuff is correct
854 if (par_language->lang() == "farsi")
856 else if (outer_language->lang() == "farsi")
858 else if (par_language->lang() == "arabic_arabi")
860 else if (outer_language->lang() == "arabic_arabi")
862 // remaining RTL languages currently is hebrew
863 else if (par_language->rightToLeft())
868 // With CJK, the CJK tag has to be closed first (see below)
869 if (runparams.encoding->package() != Encoding::CJK
870 && par_lang != openLanguageName(state)
871 && !par_lang.empty()) {
872 string bc = use_polyglossia ?
873 getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
874 : subst(lang_begin_command, "$$lang", par_lang);
876 os << lang_command_termination;
878 pushLanguageName(par_lang, localswitch);
883 // Switch file encoding if necessary; no need to do this for "default"
884 // encoding, since this only affects the position of the outputted
885 // \inputencoding command; the encoding switch will occur when necessary
886 if (bparams.inputenc == "auto"
887 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
888 && runparams.encoding->package() != Encoding::none) {
889 // Look ahead for future encoding changes.
890 // We try to output them at the beginning of the paragraph,
891 // since the \inputencoding command is not allowed e.g. in
892 // sections. For this reason we only set runparams.moving_arg
893 // after checking for the encoding change, otherwise the
894 // change would be always avoided by switchEncoding().
895 for (pos_type i = 0; i < par.size(); ++i) {
896 char_type const c = par.getChar(i);
897 Encoding const * const encoding =
898 par.getFontSettings(bparams, i).language()->encoding();
899 if (encoding->package() != Encoding::CJK
900 && runparams.encoding->package() == Encoding::inputenc
905 // All characters before c are in the ASCII range, and
906 // c is non-ASCII (but no inset), so change the
907 // encoding to that required by the language of c.
908 // With CJK, only add switch if we have CJK content at the beginning
910 if (i != 0 && encoding->package() == Encoding::CJK)
913 pair<bool, int> enc_switch = switchEncoding(os.os(),
914 bparams, runparams, *encoding);
915 // the following is necessary after a CJK environment in a multilingual
916 // context (nesting issue).
917 if (par_language->encoding()->package() == Encoding::CJK
918 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
919 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
920 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
921 state->open_encoding_ = CJK;
923 if (encoding->package() != Encoding::none && enc_switch.first) {
924 if (enc_switch.second > 0) {
925 // the '%' is necessary to prevent unwanted whitespace
928 // With CJK, the CJK tag had to be closed first (see above)
929 if (runparams.encoding->package() == Encoding::CJK
930 && par_lang != openLanguageName(state)
931 && !par_lang.empty()) {
932 os << from_ascii(subst(
936 << lang_command_termination;
938 pushLanguageName(par_lang, localswitch);
940 runparams.encoding = encoding;
946 runparams.moving_arg |= style.needprotect;
947 Encoding const * const prev_encoding = runparams.encoding;
949 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
950 if (par.allowParagraphCustomization()) {
951 if (par.params().startOfAppendix()) {
952 os << "\n\\appendix\n";
955 if (!par.params().spacing().isDefault()
956 && (pit == 0 || !priorpar->hasSameLayout(par)))
958 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
962 if (style.isCommand()) {
967 parStartCommand(par, os, runparams, style);
968 Font const outerfont = text.outerFont(pit);
971 os << from_utf8(everypar);
972 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
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();
982 if (!style.postcommandargs().empty())
983 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
984 if (runparams.encoding != prev_encoding) {
985 runparams.encoding = prev_encoding;
986 os << setEncoding(prev_encoding->iconvName());
990 bool pending_newline = false;
991 bool unskip_newline = false;
992 bool close_lang_switch = false;
993 switch (style.latextype) {
994 case LATEX_ITEM_ENVIRONMENT:
995 case LATEX_LIST_ENVIRONMENT:
996 if ((nextpar && par_lang != nextpar_lang
997 && nextpar->getDepth() == par.getDepth())
998 || (atSameLastLangSwitchDepth(state) && nextpar
999 && nextpar->getDepth() < par.getDepth()))
1000 close_lang_switch = using_begin_end;
1001 if (nextpar && par.params().depth() < nextpar->params().depth())
1002 pending_newline = true;
1004 case LATEX_ENVIRONMENT: {
1005 // if its the last paragraph of the current environment
1006 // skip it otherwise fall through
1008 && ((nextpar->layout() != par.layout()
1009 || nextpar->params().depth() != par.params().depth())
1010 || (!using_begin_end || par_lang != nextpar_lang)))
1012 close_lang_switch = using_begin_end;
1017 // fall through possible
1019 // we don't need it for the last paragraph!!!
1021 pending_newline = true;
1024 if (par.allowParagraphCustomization()) {
1025 if (!par.params().spacing().isDefault()
1026 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1027 if (pending_newline)
1030 string const endtag =
1031 par.params().spacing().writeEnvirEnd(useSetSpace);
1032 if (prefixIs(endtag, "\\end{"))
1035 os << from_ascii(endtag);
1036 pending_newline = true;
1040 // Closing the language is needed for the last paragraph; it is also
1041 // needed if we're within an \L or \R that we may have opened above (not
1042 // necessarily in this paragraph) and are about to close.
1043 bool closing_rtl_ltr_environment = !using_begin_end
1045 && (par_language->lang() != "arabic_arabtex"
1046 && outer_language->lang() != "arabic_arabtex")
1047 // have we opened an \L or \R environment?
1048 && runparams.local_font != 0
1049 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1050 // are we about to close the language?
1051 &&((nextpar && par_lang != nextpar_lang)
1052 || (runparams.isLastPar && par_lang != outer_lang));
1054 if (closing_rtl_ltr_environment
1055 || ((runparams.isLastPar || close_lang_switch)
1056 && (par_lang != outer_lang || (using_begin_end
1057 && style.isEnvironment()
1058 && par_lang != nextpar_lang)))) {
1059 // Since \selectlanguage write the language to the aux file,
1060 // we need to reset the language at the end of footnote or
1063 if (pending_newline || close_lang_switch)
1066 // when the paragraph uses CJK, the language has to be closed earlier
1067 if (font.language()->encoding()->package() != Encoding::CJK) {
1068 if (lang_end_command.empty()) {
1069 // If this is a child, we should restore the
1070 // master language after the last paragraph.
1071 Language const * const current_language =
1072 (runparams.isLastPar && runparams.master_language)
1073 ? runparams.master_language
1075 string const current_lang = use_polyglossia
1076 ? getPolyglossiaEnvName(current_language)
1077 : current_language->babel();
1078 if (!current_lang.empty()
1079 && current_lang != openLanguageName(state)) {
1080 string bc = use_polyglossia ?
1081 getPolyglossiaBegin(lang_begin_command, current_lang,
1082 current_language->polyglossiaOpts())
1083 : subst(lang_begin_command, "$$lang", current_lang);
1085 pending_newline = !localswitch;
1086 unskip_newline = !localswitch;
1087 if (using_begin_end)
1088 pushLanguageName(current_lang, localswitch);
1090 } else if ((!using_begin_end ||
1091 langOpenedAtThisLevel(state)) &&
1092 !par_lang.empty()) {
1093 // If we are in an environment, we have to
1094 // close the "outer" language afterwards
1095 string const & cur_lang = openLanguageName(state);
1096 if (!style.isEnvironment()
1097 || (close_lang_switch
1098 && atSameLastLangSwitchDepth(state)
1099 && par_lang != outer_lang
1100 && (par_lang != cur_lang
1101 || (cur_lang != outer_lang
1103 && style != nextpar->layout())))
1104 || (atSameLastLangSwitchDepth(state)
1105 && state->lang_switch_depth_.size()
1106 && cur_lang != par_lang))
1108 if (using_begin_end && !localswitch)
1110 os << from_ascii(subst(
1114 pending_newline = !localswitch;
1115 unskip_newline = !localswitch;
1116 if (using_begin_end)
1122 if (closing_rtl_ltr_environment)
1125 bool const last_was_separator =
1126 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1128 if (pending_newline) {
1130 // prevent unwanted whitespace
1132 if (!os.afterParbreak() && !last_was_separator)
1136 // if this is a CJK-paragraph and the next isn't, close CJK
1137 // also if the next paragraph is a multilingual environment (because of nesting)
1139 && state->open_encoding_ == CJK
1140 && (nextpar_language->encoding()->package() != Encoding::CJK
1141 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1142 // inbetween environments, CJK has to be closed later (nesting!)
1143 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1144 os << "\\end{CJK}\n";
1145 state->open_encoding_ = none;
1148 // If this is the last paragraph, close the CJK environment
1149 // if necessary. If it's an environment, we'll have to \end that first.
1150 if (runparams.isLastPar && !style.isEnvironment()) {
1151 switch (state->open_encoding_) {
1153 // do nothing at the end of child documents
1154 if (maintext && buf.masterBuffer() != &buf)
1158 os << "\n\\end{CJK}\n";
1162 state->open_encoding_ = none;
1167 state->open_encoding_ = none;
1177 // If this is the last paragraph, and a local_font was set upon entering
1178 // the inset, and we're using "auto" or "default" encoding, and not
1179 // compiling with XeTeX or LuaTeX, the encoding
1180 // should be set back to that local_font's encoding.
1181 if (runparams.isLastPar && runparams_in.local_font != 0
1182 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1183 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1184 && !runparams.isFullUnicode()
1186 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1187 os << setEncoding(runparams_in.encoding->iconvName());
1189 // Otherwise, the current encoding should be set for the next paragraph.
1191 runparams_in.encoding = runparams.encoding;
1194 // we don't need a newline for the last paragraph!!!
1195 // Note from JMarc: we will re-add a \n explicitly in
1196 // TeXEnvironment, because it is needed in this case
1197 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1198 // Make sure to start a new line
1200 Layout const & next_layout = nextpar->layout();
1201 // A newline '\n' is always output before a command,
1202 // so avoid doubling it.
1203 if (!next_layout.isCommand()) {
1204 // Here we now try to avoid spurious empty lines by
1205 // outputting a paragraph break only if: (case 1) the
1206 // paragraph style allows parbreaks and no \begin, \end
1207 // or \item tags are going to follow (i.e., if the next
1208 // isn't the first or the current isn't the last
1209 // paragraph of an environment or itemize) and the
1210 // depth and alignment of the following paragraph is
1211 // unchanged, or (case 2) the following is a
1212 // non-environment paragraph whose depth is increased
1213 // but whose alignment is unchanged, or (case 3) the
1214 // paragraph is not an environment and the next one is a
1215 // non-itemize-like env at lower depth, or (case 4) the
1216 // paragraph is a command not followed by an environment
1217 // and the alignment of the current and next paragraph
1218 // is unchanged, or (case 5) the current alignment is
1219 // changed and a standard paragraph follows.
1220 DocumentClass const & tclass = bparams.documentClass();
1221 if ((style == next_layout
1222 && !style.parbreak_is_newline
1223 && !text.inset().getLayout().parbreakIsNewline()
1224 && style.latextype != LATEX_ITEM_ENVIRONMENT
1225 && style.latextype != LATEX_LIST_ENVIRONMENT
1226 && style.align == par.getAlign()
1227 && nextpar->getDepth() == par.getDepth()
1228 && nextpar->getAlign() == par.getAlign())
1229 || (!next_layout.isEnvironment()
1230 && nextpar->getDepth() > par.getDepth()
1231 && nextpar->getAlign() == par.getAlign())
1232 || (!style.isEnvironment()
1233 && next_layout.latextype == LATEX_ENVIRONMENT
1234 && nextpar->getDepth() < par.getDepth())
1235 || (style.isCommand()
1236 && !next_layout.isEnvironment()
1237 && style.align == par.getAlign()
1238 && next_layout.align == nextpar->getAlign())
1239 || (style.align != par.getAlign()
1240 && tclass.isDefaultLayout(next_layout))) {
1246 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1247 << &par << " next " << nextpar);
1253 // LaTeX all paragraphs
1254 void latexParagraphs(Buffer const & buf,
1257 OutputParams const & runparams,
1258 string const & everypar)
1260 LASSERT(runparams.par_begin <= runparams.par_end,
1261 { os << "% LaTeX Output Error\n"; return; } );
1263 BufferParams const & bparams = buf.params();
1265 bool const maintext = text.isMainText();
1266 bool const is_child = buf.masterBuffer() != &buf;
1268 // Open a CJK environment at the beginning of the main buffer
1269 // if the document's language is a CJK language
1270 // (but not in child documents)
1271 OutputState * state = getOutputState();
1272 if (maintext && !is_child
1273 && bparams.encoding().package() == Encoding::CJK) {
1274 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1275 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1276 state->open_encoding_ = CJK;
1278 // if "auto begin" is switched off, explicitly switch the
1279 // language on at start
1280 string const mainlang = runparams.use_polyglossia
1281 ? getPolyglossiaEnvName(bparams.language)
1282 : bparams.language->babel();
1283 string const lang_begin_command = runparams.use_polyglossia ?
1284 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1285 string const lang_end_command = runparams.use_polyglossia ?
1286 "\\end{$$lang}" : lyxrc.language_command_end;
1287 bool const using_begin_end = runparams.use_polyglossia ||
1288 !lang_end_command.empty();
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 (using_begin_end)
1300 pushLanguageName(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 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1398 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1399 os << from_utf8(subst(lang_end_command,
1403 if (using_begin_end)
1407 // If the last paragraph is an environment, we'll have to close
1408 // CJK at the very end to do proper nesting.
1409 if (maintext && !is_child && state->open_encoding_ == CJK) {
1410 os << "\\end{CJK}\n";
1411 state->open_encoding_ = none;
1413 // Likewise for polyglossia or when using begin/end commands
1414 string const & cur_lang = openLanguageName(state);
1415 if (maintext && !is_child && !cur_lang.empty()) {
1416 os << from_utf8(subst(lang_end_command,
1420 if (using_begin_end)
1424 // reset inherited encoding
1425 if (state->cjk_inherited_ > 0) {
1426 state->cjk_inherited_ -= 1;
1427 if (state->cjk_inherited_ == 0)
1428 state->open_encoding_ = CJK;
1433 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1434 OutputParams const & runparams, Encoding const & newEnc,
1437 // XeTeX/LuaTeX use only one encoding per document:
1438 // * with useNonTeXFonts: "utf8plain",
1439 // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1440 // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1441 if (runparams.isFullUnicode())
1442 return make_pair(false, 0);
1444 Encoding const & oldEnc = *runparams.encoding;
1445 bool moving_arg = runparams.moving_arg;
1446 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1447 bool const from_to_cjk =
1448 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1449 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1450 if (!force && !from_to_cjk
1451 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1452 return make_pair(false, 0);
1454 // Do nothing if the encoding is unchanged.
1455 if (oldEnc.name() == newEnc.name())
1456 return make_pair(false, 0);
1458 // FIXME We ignore encoding switches from/to encodings that do
1459 // neither support the inputenc package nor the CJK package here.
1460 // This does of course only work in special cases (e.g. switch from
1461 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1462 // but it is the best we can do
1463 if (oldEnc.package() == Encoding::none
1464 || newEnc.package() == Encoding::none)
1465 return make_pair(false, 0);
1467 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1468 << oldEnc.name() << " to " << newEnc.name());
1469 os << setEncoding(newEnc.iconvName());
1470 if (bparams.inputenc == "default")
1471 return make_pair(true, 0);
1473 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1474 OutputState * state = getOutputState();
1475 switch (newEnc.package()) {
1476 case Encoding::none:
1477 case Encoding::japanese:
1478 // shouldn't ever reach here, see above
1479 return make_pair(true, 0);
1480 case Encoding::inputenc: {
1481 int count = inputenc_arg.length();
1482 if (oldEnc.package() == Encoding::CJK &&
1483 state->open_encoding_ == CJK) {
1485 state->open_encoding_ = none;
1488 else if (oldEnc.package() == Encoding::inputenc &&
1489 state->open_encoding_ == inputenc) {
1491 state->open_encoding_ = none;
1494 if (runparams.local_font != 0
1495 && oldEnc.package() == Encoding::CJK) {
1496 // within insets, \inputenc switches need
1497 // to be embraced within \bgroup...\egroup;
1501 state->open_encoding_ = inputenc;
1503 // with the japanese option, inputenc is omitted.
1504 if (runparams.use_japanese)
1505 return make_pair(true, count);
1506 os << "\\inputencoding{" << inputenc_arg << '}';
1507 return make_pair(true, count + 16);
1509 case Encoding::CJK: {
1510 int count = inputenc_arg.length();
1511 if (oldEnc.package() == Encoding::CJK &&
1512 state->open_encoding_ == CJK) {
1516 if (oldEnc.package() == Encoding::inputenc &&
1517 state->open_encoding_ == inputenc) {
1521 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1522 << from_ascii(bparams.fonts_cjk) << "}";
1523 state->open_encoding_ = CJK;
1524 return make_pair(true, count + 15);
1527 // Dead code to avoid a warning:
1528 return make_pair(true, 0);