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 string const & openLanguageName()
532 OutputState * state = getOutputState();
534 return openLanguageName(state);
538 void latexArgInsets(Paragraph const & par, otexstream & os,
539 OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
541 map<int, InsetArgument const *> ilist;
542 vector<string> required;
544 InsetList::const_iterator it = par.insetList().begin();
545 InsetList::const_iterator end = par.insetList().end();
546 for (; it != end; ++it) {
547 if (it->inset->lyxCode() == ARG_CODE) {
548 InsetArgument const * ins =
549 static_cast<InsetArgument const *>(it->inset);
550 if (ins->name().empty())
551 LYXERR0("Error: Unnamed argument inset!");
553 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
554 unsigned int const nr = convert<unsigned int>(name);
556 Layout::LaTeXArgMap::const_iterator const lit =
557 latexargs.find(ins->name());
558 if (lit != latexargs.end()) {
559 Layout::latexarg const & arg = (*lit).second;
560 if (!arg.requires.empty()) {
561 vector<string> req = getVectorFromString(arg.requires);
562 required.insert(required.end(), req.begin(), req.end());
568 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
572 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
573 otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
574 string const & prefix)
576 map<int, InsetArgument const *> ilist;
577 vector<string> required;
579 depth_type const current_depth = pit->params().depth();
580 Layout const current_layout = pit->layout();
582 // get the first paragraph in sequence with this layout and depth
585 if (lyx::prev(pit, offset) == pars.begin())
587 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
588 if (priorpit->layout() == current_layout
589 && priorpit->params().depth() == current_depth)
595 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
597 for (; spit != pars.end(); ++spit) {
598 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
600 if (spit->params().depth() > current_depth)
602 InsetList::const_iterator it = spit->insetList().begin();
603 InsetList::const_iterator end = spit->insetList().end();
604 for (; it != end; ++it) {
605 if (it->inset->lyxCode() == ARG_CODE) {
606 InsetArgument const * ins =
607 static_cast<InsetArgument const *>(it->inset);
608 if (ins->name().empty())
609 LYXERR0("Error: Unnamed argument inset!");
611 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
612 unsigned int const nr = convert<unsigned int>(name);
613 if (ilist.find(nr) == ilist.end())
615 Layout::LaTeXArgMap::const_iterator const lit =
616 latexargs.find(ins->name());
617 if (lit != latexargs.end()) {
618 Layout::latexarg const & arg = (*lit).second;
619 if (!arg.requires.empty()) {
620 vector<string> req = getVectorFromString(arg.requires);
621 required.insert(required.end(), req.begin(), req.end());
628 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
633 // output the proper paragraph start according to latextype.
634 void parStartCommand(Paragraph const & par, otexstream & os,
635 OutputParams const & runparams, Layout const & style)
637 switch (style.latextype) {
639 os << '\\' << from_ascii(style.latexname());
642 if (!style.latexargs().empty())
643 latexArgInsets(par, os, runparams, style.latexargs());
644 os << from_ascii(style.latexparam());
646 case LATEX_ITEM_ENVIRONMENT:
647 case LATEX_LIST_ENVIRONMENT:
648 os << "\\" + style.itemcommand();
650 if (!style.itemargs().empty())
651 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
654 case LATEX_BIB_ENVIRONMENT:
655 // ignore this, the inset will write itself
664 // FIXME: this should be anonymous
665 void TeXOnePar(Buffer const & buf,
669 OutputParams const & runparams_in,
670 string const & everypar,
671 int start_pos, int end_pos)
673 BufferParams const & bparams = runparams_in.is_child
674 ? buf.masterParams() : buf.params();
675 ParagraphList const & paragraphs = text.paragraphs();
676 Paragraph const & par = paragraphs.at(pit);
677 // FIXME This check should not really be needed.
678 // Perhaps we should issue an error if it is.
679 Layout const & style = text.inset().forcePlainLayout() ?
680 bparams.documentClass().plainLayout() : par.layout();
682 if (style.inpreamble)
685 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
688 OutputParams runparams = runparams_in;
689 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
690 // We reinitialze par begin and end to be on the safe side
691 // with embedded inset as we don't know if they set those
693 runparams.par_begin = 0;
694 runparams.par_end = 0;
696 bool const maintext = text.isMainText();
697 // we are at the beginning of an inset and CJK is already open;
698 // we count inheritation levels to get the inset nesting right.
699 OutputState * state = getOutputState();
700 if (pit == 0 && !maintext
701 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
702 state->cjk_inherited_ += 1;
703 state->open_encoding_ = none;
706 if (text.inset().isPassThru()) {
707 Font const outerfont = text.outerFont(pit);
709 // No newline before first paragraph in this lyxtext
712 if (!text.inset().getLayout().parbreakIsNewline())
716 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
720 Paragraph const * nextpar = runparams.isLastPar
721 ? 0 : ¶graphs.at(pit + 1);
723 if (style.pass_thru) {
724 Font const outerfont = text.outerFont(pit);
725 parStartCommand(par, os, runparams, style);
727 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
729 // I did not create a parEndCommand for this minuscule
730 // task because in the other user of parStartCommand
731 // the code is different (JMarc)
732 if (style.isCommand())
736 if (!style.parbreak_is_newline) {
738 } else if (nextpar && !style.isEnvironment()) {
739 Layout const nextstyle = text.inset().forcePlainLayout()
740 ? bparams.documentClass().plainLayout()
742 if (nextstyle.name() != style.name())
749 // This paragraph's language
750 Language const * const par_language = par.getParLanguage(bparams);
751 Language const * const nextpar_language = nextpar ?
752 nextpar->getParLanguage(bparams) : 0;
753 // The document's language
754 Language const * const doc_language = bparams.language;
755 // The language that was in effect when the environment this paragraph is
756 // inside of was opened
757 Language const * const outer_language =
758 (runparams.local_font != 0) ?
759 runparams.local_font->language() : doc_language;
761 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
763 // The previous language that was in effect is the language of the
764 // previous paragraph, unless the previous paragraph is inside an
765 // environment with nesting depth greater than (or equal to, but with
766 // a different layout) the current one. If there is no previous
767 // paragraph, the previous language is the outer language.
768 bool const use_prev_env_language = state->prev_env_language_ != 0
770 && priorpar->layout().isEnvironment()
771 && (priorpar->getDepth() > par.getDepth()
772 || (priorpar->getDepth() == par.getDepth()
773 && priorpar->layout() != par.layout()));
774 Language const * const prev_language =
776 ? (use_prev_env_language ? state->prev_env_language_
777 : priorpar->getParLanguage(bparams))
781 bool const use_polyglossia = runparams.use_polyglossia;
782 string const par_lang = use_polyglossia ?
783 getPolyglossiaEnvName(par_language): par_language->babel();
784 string const prev_lang = use_polyglossia ?
785 getPolyglossiaEnvName(prev_language) : prev_language->babel();
786 string const outer_lang = use_polyglossia ?
787 getPolyglossiaEnvName(outer_language) : outer_language->babel();
788 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
789 getPolyglossiaEnvName(nextpar_language) :
790 nextpar_language->babel()) : string();
791 string lang_begin_command = use_polyglossia ?
792 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
793 string lang_end_command = use_polyglossia ?
794 "\\end{$$lang}" : lyxrc.language_command_end;
795 // the '%' is necessary to prevent unwanted whitespace
796 string lang_command_termination = "%\n";
797 bool const using_begin_end = use_polyglossia ||
798 !lang_end_command.empty();
800 // In some insets (such as Arguments), we cannot use \selectlanguage
801 bool const localswitch = text.inset().forceLocalFontSwitch()
802 || (using_begin_end && text.inset().forcePlainLayout());
804 lang_begin_command = use_polyglossia ?
805 "\\text$$lang$$opts{" : lyxrc.language_command_local;
806 lang_end_command = "}";
807 lang_command_termination.clear();
810 if (par_lang != prev_lang
811 // check if we already put language command in TeXEnvironment()
812 && !(style.isEnvironment()
813 && (pit == 0 || (priorpar->layout() != par.layout()
814 && priorpar->getDepth() <= par.getDepth())
815 || priorpar->getDepth() < par.getDepth())))
817 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
818 !lang_end_command.empty() &&
819 prev_lang != outer_lang &&
820 !prev_lang.empty() &&
821 (!using_begin_end || !style.isEnvironment()))
823 os << from_ascii(subst(lang_end_command,
826 << lang_command_termination;
831 // We need to open a new language if we couldn't close the previous
832 // one (because there's no language_command_end); and even if we closed
833 // the previous one, if the current language is different than the
834 // outer_language (which is currently in effect once the previous one
836 if ((lang_end_command.empty() || par_lang != outer_lang
838 || (style.isEnvironment() && par_lang != prev_lang)))
839 && !par_lang.empty()) {
840 // If we're inside an inset, and that inset is within an \L or \R
841 // (or equivalents), then within the inset, too, any opposite
842 // language paragraph should appear within an \L or \R (in addition
843 // to, outside of, the normal language switch commands).
844 // This behavior is not correct for ArabTeX, though.
847 && par_language->lang() != "arabic_arabtex"
848 && outer_language->lang() != "arabic_arabtex"
849 // are we in an inset?
850 && runparams.local_font != 0
851 // is the inset within an \L or \R?
853 // FIXME: currently, we don't check this; this means that
854 // we'll have unnnecessary \L and \R commands, but that
855 // doesn't seem to hurt (though latex will complain)
857 // is this paragraph in the opposite direction?
858 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
859 // FIXME: I don't have a working copy of the Arabi package, so
860 // I'm not sure if the farsi and arabic_arabi stuff is correct
862 if (par_language->lang() == "farsi")
864 else if (outer_language->lang() == "farsi")
866 else if (par_language->lang() == "arabic_arabi")
868 else if (outer_language->lang() == "arabic_arabi")
870 // remaining RTL languages currently is hebrew
871 else if (par_language->rightToLeft())
876 // With CJK, the CJK tag has to be closed first (see below)
877 if (runparams.encoding->package() != Encoding::CJK
878 && par_lang != openLanguageName(state)
879 && !par_lang.empty()) {
880 string bc = use_polyglossia ?
881 getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
882 : subst(lang_begin_command, "$$lang", par_lang);
884 os << lang_command_termination;
886 pushLanguageName(par_lang, localswitch);
891 // Switch file encoding if necessary; no need to do this for "default"
892 // encoding, since this only affects the position of the outputted
893 // \inputencoding command; the encoding switch will occur when necessary
894 if (bparams.inputenc == "auto"
895 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
896 && runparams.encoding->package() != Encoding::none) {
897 // Look ahead for future encoding changes.
898 // We try to output them at the beginning of the paragraph,
899 // since the \inputencoding command is not allowed e.g. in
900 // sections. For this reason we only set runparams.moving_arg
901 // after checking for the encoding change, otherwise the
902 // change would be always avoided by switchEncoding().
903 for (pos_type i = 0; i < par.size(); ++i) {
904 char_type const c = par.getChar(i);
905 Encoding const * const encoding =
906 par.getFontSettings(bparams, i).language()->encoding();
907 if (encoding->package() != Encoding::CJK
908 && runparams.encoding->package() == Encoding::inputenc
913 // All characters before c are in the ASCII range, and
914 // c is non-ASCII (but no inset), so change the
915 // encoding to that required by the language of c.
916 // With CJK, only add switch if we have CJK content at the beginning
918 if (i != 0 && encoding->package() == Encoding::CJK)
921 pair<bool, int> enc_switch = switchEncoding(os.os(),
922 bparams, runparams, *encoding);
923 // the following is necessary after a CJK environment in a multilingual
924 // context (nesting issue).
925 if (par_language->encoding()->package() == Encoding::CJK
926 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
927 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
928 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
929 state->open_encoding_ = CJK;
931 if (encoding->package() != Encoding::none && enc_switch.first) {
932 if (enc_switch.second > 0) {
933 // the '%' is necessary to prevent unwanted whitespace
936 // With CJK, the CJK tag had to be closed first (see above)
937 if (runparams.encoding->package() == Encoding::CJK
938 && par_lang != openLanguageName(state)
939 && !par_lang.empty()) {
940 os << from_ascii(subst(
944 << lang_command_termination;
946 pushLanguageName(par_lang, localswitch);
948 runparams.encoding = encoding;
954 runparams.moving_arg |= style.needprotect;
955 Encoding const * const prev_encoding = runparams.encoding;
957 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
958 if (par.allowParagraphCustomization()) {
959 if (par.params().startOfAppendix()) {
960 os << "\n\\appendix\n";
963 if (!par.params().spacing().isDefault()
964 && (pit == 0 || !priorpar->hasSameLayout(par)))
966 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
970 if (style.isCommand()) {
975 parStartCommand(par, os, runparams, style);
976 Font const outerfont = text.outerFont(pit);
979 os << from_utf8(everypar);
980 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
982 Font const font = par.empty()
983 ? par.getLayoutFont(bparams, outerfont)
984 : par.getFont(bparams, par.size() - 1, outerfont);
986 bool const is_command = style.isCommand();
990 if (!style.postcommandargs().empty())
991 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
992 if (runparams.encoding != prev_encoding) {
993 runparams.encoding = prev_encoding;
994 os << setEncoding(prev_encoding->iconvName());
998 bool pending_newline = false;
999 bool unskip_newline = false;
1000 bool close_lang_switch = false;
1001 switch (style.latextype) {
1002 case LATEX_ITEM_ENVIRONMENT:
1003 case LATEX_LIST_ENVIRONMENT:
1004 if ((nextpar && par_lang != nextpar_lang
1005 && nextpar->getDepth() == par.getDepth())
1006 || (atSameLastLangSwitchDepth(state) && nextpar
1007 && nextpar->getDepth() < par.getDepth()))
1008 close_lang_switch = using_begin_end;
1009 if (nextpar && par.params().depth() < nextpar->params().depth())
1010 pending_newline = true;
1012 case LATEX_ENVIRONMENT: {
1013 // if its the last paragraph of the current environment
1014 // skip it otherwise fall through
1016 && ((nextpar->layout() != par.layout()
1017 || nextpar->params().depth() != par.params().depth())
1018 || (!using_begin_end || par_lang != nextpar_lang)))
1020 close_lang_switch = using_begin_end;
1025 // fall through possible
1027 // we don't need it for the last paragraph!!!
1029 pending_newline = true;
1032 if (par.allowParagraphCustomization()) {
1033 if (!par.params().spacing().isDefault()
1034 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1035 if (pending_newline)
1038 string const endtag =
1039 par.params().spacing().writeEnvirEnd(useSetSpace);
1040 if (prefixIs(endtag, "\\end{"))
1043 os << from_ascii(endtag);
1044 pending_newline = true;
1048 // Closing the language is needed for the last paragraph; it is also
1049 // needed if we're within an \L or \R that we may have opened above (not
1050 // necessarily in this paragraph) and are about to close.
1051 bool closing_rtl_ltr_environment = !using_begin_end
1053 && (par_language->lang() != "arabic_arabtex"
1054 && outer_language->lang() != "arabic_arabtex")
1055 // have we opened an \L or \R environment?
1056 && runparams.local_font != 0
1057 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1058 // are we about to close the language?
1059 &&((nextpar && par_lang != nextpar_lang)
1060 || (runparams.isLastPar && par_lang != outer_lang));
1062 if (closing_rtl_ltr_environment
1063 || ((runparams.isLastPar || close_lang_switch)
1064 && (par_lang != outer_lang || (using_begin_end
1065 && style.isEnvironment()
1066 && par_lang != nextpar_lang)))) {
1067 // Since \selectlanguage write the language to the aux file,
1068 // we need to reset the language at the end of footnote or
1071 if (pending_newline || close_lang_switch)
1074 // when the paragraph uses CJK, the language has to be closed earlier
1075 if (font.language()->encoding()->package() != Encoding::CJK) {
1076 if (lang_end_command.empty()) {
1077 // If this is a child, we should restore the
1078 // master language after the last paragraph.
1079 Language const * const current_language =
1080 (runparams.isLastPar && runparams.master_language)
1081 ? runparams.master_language
1083 string const current_lang = use_polyglossia
1084 ? getPolyglossiaEnvName(current_language)
1085 : current_language->babel();
1086 if (!current_lang.empty()
1087 && current_lang != openLanguageName(state)) {
1088 string bc = use_polyglossia ?
1089 getPolyglossiaBegin(lang_begin_command, current_lang,
1090 current_language->polyglossiaOpts())
1091 : subst(lang_begin_command, "$$lang", current_lang);
1093 pending_newline = !localswitch;
1094 unskip_newline = !localswitch;
1095 if (using_begin_end)
1096 pushLanguageName(current_lang, localswitch);
1098 } else if ((!using_begin_end ||
1099 langOpenedAtThisLevel(state)) &&
1100 !par_lang.empty()) {
1101 // If we are in an environment, we have to
1102 // close the "outer" language afterwards
1103 string const & cur_lang = openLanguageName(state);
1104 if (!style.isEnvironment()
1105 || (close_lang_switch
1106 && atSameLastLangSwitchDepth(state)
1107 && par_lang != outer_lang
1108 && (par_lang != cur_lang
1109 || (cur_lang != outer_lang
1111 && style != nextpar->layout())))
1112 || (atSameLastLangSwitchDepth(state)
1113 && state->lang_switch_depth_.size()
1114 && cur_lang != par_lang))
1116 if (using_begin_end && !localswitch)
1118 os << from_ascii(subst(
1122 pending_newline = !localswitch;
1123 unskip_newline = !localswitch;
1124 if (using_begin_end)
1130 if (closing_rtl_ltr_environment)
1133 bool const last_was_separator =
1134 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1136 if (pending_newline) {
1138 // prevent unwanted whitespace
1140 if (!os.afterParbreak() && !last_was_separator)
1144 // if this is a CJK-paragraph and the next isn't, close CJK
1145 // also if the next paragraph is a multilingual environment (because of nesting)
1147 && state->open_encoding_ == CJK
1148 && (nextpar_language->encoding()->package() != Encoding::CJK
1149 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1150 // inbetween environments, CJK has to be closed later (nesting!)
1151 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1152 os << "\\end{CJK}\n";
1153 state->open_encoding_ = none;
1156 // If this is the last paragraph, close the CJK environment
1157 // if necessary. If it's an environment, we'll have to \end that first.
1158 if (runparams.isLastPar && !style.isEnvironment()) {
1159 switch (state->open_encoding_) {
1161 // do nothing at the end of child documents
1162 if (maintext && buf.masterBuffer() != &buf)
1166 os << "\n\\end{CJK}\n";
1170 state->open_encoding_ = none;
1175 state->open_encoding_ = none;
1185 // If this is the last paragraph, and a local_font was set upon entering
1186 // the inset, and we're using "auto" or "default" encoding, and not
1187 // compiling with XeTeX or LuaTeX, the encoding
1188 // should be set back to that local_font's encoding.
1189 if (runparams.isLastPar && runparams_in.local_font != 0
1190 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1191 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1192 && !runparams.isFullUnicode()
1194 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1195 os << setEncoding(runparams_in.encoding->iconvName());
1197 // Otherwise, the current encoding should be set for the next paragraph.
1199 runparams_in.encoding = runparams.encoding;
1202 // we don't need a newline for the last paragraph!!!
1203 // Note from JMarc: we will re-add a \n explicitly in
1204 // TeXEnvironment, because it is needed in this case
1205 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1206 // Make sure to start a new line
1208 Layout const & next_layout = nextpar->layout();
1209 // A newline '\n' is always output before a command,
1210 // so avoid doubling it.
1211 if (!next_layout.isCommand()) {
1212 // Here we now try to avoid spurious empty lines by
1213 // outputting a paragraph break only if: (case 1) the
1214 // paragraph style allows parbreaks and no \begin, \end
1215 // or \item tags are going to follow (i.e., if the next
1216 // isn't the first or the current isn't the last
1217 // paragraph of an environment or itemize) and the
1218 // depth and alignment of the following paragraph is
1219 // unchanged, or (case 2) the following is a
1220 // non-environment paragraph whose depth is increased
1221 // but whose alignment is unchanged, or (case 3) the
1222 // paragraph is not an environment and the next one is a
1223 // non-itemize-like env at lower depth, or (case 4) the
1224 // paragraph is a command not followed by an environment
1225 // and the alignment of the current and next paragraph
1226 // is unchanged, or (case 5) the current alignment is
1227 // changed and a standard paragraph follows.
1228 DocumentClass const & tclass = bparams.documentClass();
1229 if ((style == next_layout
1230 && !style.parbreak_is_newline
1231 && !text.inset().getLayout().parbreakIsNewline()
1232 && style.latextype != LATEX_ITEM_ENVIRONMENT
1233 && style.latextype != LATEX_LIST_ENVIRONMENT
1234 && style.align == par.getAlign()
1235 && nextpar->getDepth() == par.getDepth()
1236 && nextpar->getAlign() == par.getAlign())
1237 || (!next_layout.isEnvironment()
1238 && nextpar->getDepth() > par.getDepth()
1239 && nextpar->getAlign() == par.getAlign())
1240 || (!style.isEnvironment()
1241 && next_layout.latextype == LATEX_ENVIRONMENT
1242 && nextpar->getDepth() < par.getDepth())
1243 || (style.isCommand()
1244 && !next_layout.isEnvironment()
1245 && style.align == par.getAlign()
1246 && next_layout.align == nextpar->getAlign())
1247 || (style.align != par.getAlign()
1248 && tclass.isDefaultLayout(next_layout))) {
1254 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1255 << &par << " next " << nextpar);
1261 // LaTeX all paragraphs
1262 void latexParagraphs(Buffer const & buf,
1265 OutputParams const & runparams,
1266 string const & everypar)
1268 LASSERT(runparams.par_begin <= runparams.par_end,
1269 { os << "% LaTeX Output Error\n"; return; } );
1271 BufferParams const & bparams = buf.params();
1273 bool const maintext = text.isMainText();
1274 bool const is_child = buf.masterBuffer() != &buf;
1276 // Open a CJK environment at the beginning of the main buffer
1277 // if the document's language is a CJK language
1278 // (but not in child documents)
1279 OutputState * state = getOutputState();
1280 if (maintext && !is_child
1281 && bparams.encoding().package() == Encoding::CJK) {
1282 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1283 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1284 state->open_encoding_ = CJK;
1286 // if "auto begin" is switched off, explicitly switch the
1287 // language on at start
1288 string const mainlang = runparams.use_polyglossia
1289 ? getPolyglossiaEnvName(bparams.language)
1290 : bparams.language->babel();
1291 string const lang_begin_command = runparams.use_polyglossia ?
1292 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1293 string const lang_end_command = runparams.use_polyglossia ?
1294 "\\end{$$lang}" : lyxrc.language_command_end;
1295 bool const using_begin_end = runparams.use_polyglossia ||
1296 !lang_end_command.empty();
1298 if (maintext && !lyxrc.language_auto_begin &&
1299 !mainlang.empty()) {
1301 string bc = runparams.use_polyglossia ?
1302 getPolyglossiaBegin(lang_begin_command, mainlang,
1303 bparams.language->polyglossiaOpts())
1304 : subst(lang_begin_command, "$$lang", mainlang);
1307 if (using_begin_end)
1308 pushLanguageName(mainlang);
1311 ParagraphList const & paragraphs = text.paragraphs();
1313 if (runparams.par_begin == runparams.par_end) {
1314 // The full doc will be exported but it is easier to just rely on
1315 // runparams range parameters that will be passed TeXEnvironment.
1316 runparams.par_begin = 0;
1317 runparams.par_end = paragraphs.size();
1320 pit_type pit = runparams.par_begin;
1321 // lastpit is for the language check after the loop.
1322 pit_type lastpit = pit;
1323 // variables used in the loop:
1324 bool was_title = false;
1325 bool already_title = false;
1326 DocumentClass const & tclass = bparams.documentClass();
1328 // Did we already warn about inTitle layout mixing? (we only warn once)
1329 bool gave_layout_warning = false;
1330 for (; pit < runparams.par_end; ++pit) {
1332 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1334 // FIXME This check should not be needed. We should
1335 // perhaps issue an error if it is.
1336 Layout const & layout = text.inset().forcePlainLayout() ?
1337 tclass.plainLayout() : par->layout();
1339 if (layout.intitle) {
1340 if (already_title) {
1341 if (!gave_layout_warning) {
1342 gave_layout_warning = true;
1343 frontend::Alert::warning(_("Error in latexParagraphs"),
1344 bformat(_("You are using at least one "
1345 "layout (%1$s) intended for the title, "
1346 "after using non-title layouts. This "
1347 "could lead to missing or incorrect output."
1350 } else if (!was_title) {
1352 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1354 << from_ascii(tclass.titlename())
1358 } else if (was_title && !already_title) {
1359 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1360 os << "\\end{" << from_ascii(tclass.titlename())
1364 os << "\\" << from_ascii(tclass.titlename())
1367 already_title = true;
1372 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1373 // This is a standard top level paragraph, TeX it and continue.
1374 TeXOnePar(buf, text, pit, os, runparams, everypar);
1378 TeXEnvironmentData const data =
1379 prepareEnvironment(buf, text, par, os, runparams);
1380 // pit can be changed in TeXEnvironment.
1381 TeXEnvironment(buf, text, runparams, pit, os);
1382 finishEnvironment(os, runparams, data);
1385 if (pit == runparams.par_end) {
1386 // Make sure that the last paragraph is
1387 // correctly terminated (because TeXOnePar does
1388 // not add a \n in this case)
1392 // It might be that we only have a title in this document
1393 if (was_title && !already_title) {
1394 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1395 os << "\\end{" << from_ascii(tclass.titlename())
1398 os << "\\" << from_ascii(tclass.titlename())
1403 // if "auto end" is switched off, explicitly close the language at the end
1404 // but only if the last par is in a babel or polyglossia language
1405 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1406 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1407 os << from_utf8(subst(lang_end_command,
1411 if (using_begin_end)
1415 // If the last paragraph is an environment, we'll have to close
1416 // CJK at the very end to do proper nesting.
1417 if (maintext && !is_child && state->open_encoding_ == CJK) {
1418 os << "\\end{CJK}\n";
1419 state->open_encoding_ = none;
1421 // Likewise for polyglossia or when using begin/end commands
1422 string const & cur_lang = openLanguageName(state);
1423 if (maintext && !is_child && !cur_lang.empty()) {
1424 os << from_utf8(subst(lang_end_command,
1428 if (using_begin_end)
1432 // reset inherited encoding
1433 if (state->cjk_inherited_ > 0) {
1434 state->cjk_inherited_ -= 1;
1435 if (state->cjk_inherited_ == 0)
1436 state->open_encoding_ = CJK;
1441 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1442 OutputParams const & runparams, Encoding const & newEnc,
1445 // XeTeX/LuaTeX use only one encoding per document:
1446 // * with useNonTeXFonts: "utf8plain",
1447 // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1448 // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1449 if (runparams.isFullUnicode())
1450 return make_pair(false, 0);
1452 Encoding const & oldEnc = *runparams.encoding;
1453 bool moving_arg = runparams.moving_arg;
1454 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1455 bool const from_to_cjk =
1456 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1457 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1458 if (!force && !from_to_cjk
1459 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1460 return make_pair(false, 0);
1462 // Do nothing if the encoding is unchanged.
1463 if (oldEnc.name() == newEnc.name())
1464 return make_pair(false, 0);
1466 // FIXME We ignore encoding switches from/to encodings that do
1467 // neither support the inputenc package nor the CJK package here.
1468 // This does of course only work in special cases (e.g. switch from
1469 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1470 // but it is the best we can do
1471 if (oldEnc.package() == Encoding::none
1472 || newEnc.package() == Encoding::none)
1473 return make_pair(false, 0);
1475 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1476 << oldEnc.name() << " to " << newEnc.name());
1477 os << setEncoding(newEnc.iconvName());
1478 if (bparams.inputenc == "default")
1479 return make_pair(true, 0);
1481 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1482 OutputState * state = getOutputState();
1483 switch (newEnc.package()) {
1484 case Encoding::none:
1485 case Encoding::japanese:
1486 // shouldn't ever reach here, see above
1487 return make_pair(true, 0);
1488 case Encoding::inputenc: {
1489 int count = inputenc_arg.length();
1490 if (oldEnc.package() == Encoding::CJK &&
1491 state->open_encoding_ == CJK) {
1493 state->open_encoding_ = none;
1496 else if (oldEnc.package() == Encoding::inputenc &&
1497 state->open_encoding_ == inputenc) {
1499 state->open_encoding_ = none;
1502 if (runparams.local_font != 0
1503 && oldEnc.package() == Encoding::CJK) {
1504 // within insets, \inputenc switches need
1505 // to be embraced within \bgroup...\egroup;
1509 state->open_encoding_ = inputenc;
1511 // with the japanese option, inputenc is omitted.
1512 if (runparams.use_japanese)
1513 return make_pair(true, count);
1514 os << "\\inputencoding{" << inputenc_arg << '}';
1515 return make_pair(true, count + 16);
1517 case Encoding::CJK: {
1518 int count = inputenc_arg.length();
1519 if (oldEnc.package() == Encoding::CJK &&
1520 state->open_encoding_ == CJK) {
1524 if (oldEnc.package() == Encoding::inputenc &&
1525 state->open_encoding_ == inputenc) {
1529 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1530 << from_ascii(bparams.fonts_cjk) << "}";
1531 state->open_encoding_ = CJK;
1532 return make_pair(true, count + 15);
1535 // Dead code to avoid a warning:
1536 return make_pair(true, 0);