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 "texstream.h"
27 #include "TextClass.h"
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetArgument.h"
32 #include "frontends/alert.h"
34 #include "support/lassert.h"
35 #include "support/convert.h"
36 #include "support/debug.h"
37 #include "support/lstrings.h"
38 #include "support/lyxalgo.h"
39 #include "support/textutils.h"
40 #include "support/gettext.h"
42 #include <QThreadStorage>
47 using namespace lyx::support;
63 OutputState() : open_encoding_(none), cjk_inherited_(0),
64 prev_env_language_(0), open_polyglossia_lang_("")
67 OpenEncoding open_encoding_;
69 Language const * prev_env_language_;
70 string open_polyglossia_lang_;
74 OutputState * getOutputState()
76 // FIXME An instance of OutputState should be kept around for each export
77 // instead of using local thread storage
78 static QThreadStorage<OutputState *> outputstate;
79 if (!outputstate.hasLocalData())
80 outputstate.setLocalData(new OutputState);
81 return outputstate.localData();
85 string const getPolyglossiaEnvName(Language const * lang)
87 string result = lang->polyglossia();
88 if (result == "arabic")
89 // exceptional spelling; see polyglossia docs.
95 string const getPolyglossiaBegin(string const & lang_begin_command,
96 string const & lang, string const & opts)
100 result = subst(lang_begin_command, "$$lang", lang);
101 string options = opts.empty() ?
102 string() : "[" + opts + "]";
103 result = subst(result, "$$opts", options);
109 struct TeXEnvironmentData
112 Layout const * style;
113 Language const * par_language;
114 Encoding const * prev_encoding;
115 bool leftindent_open;
119 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
121 ParagraphList::const_iterator pit,
123 OutputParams const & runparams)
125 TeXEnvironmentData data;
127 BufferParams const & bparams = buf.params();
129 // FIXME This test should not be necessary.
130 // We should perhaps issue an error if it is.
131 Layout const & style = text.inset().forcePlainLayout() ?
132 bparams.documentClass().plainLayout() : pit->layout();
134 ParagraphList const & paragraphs = text.paragraphs();
135 ParagraphList::const_iterator const priorpit =
136 pit == paragraphs.begin() ? pit : prev(pit, 1);
138 OutputState * state = getOutputState();
139 bool const use_prev_env_language = state->prev_env_language_ != 0
140 && priorpit->layout().isEnvironment()
141 && (priorpit->getDepth() > pit->getDepth()
142 || (priorpit->getDepth() == pit->getDepth()
143 && priorpit->layout() != pit->layout()));
145 data.prev_encoding = runparams.encoding;
146 data.par_language = pit->getParLanguage(bparams);
147 Language const * const doc_language = bparams.language;
148 Language const * const prev_par_language =
149 (pit != paragraphs.begin())
150 ? (use_prev_env_language ? state->prev_env_language_
151 : priorpit->getParLanguage(bparams))
154 bool const use_polyglossia = runparams.use_polyglossia;
155 string const par_lang = use_polyglossia ?
156 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
157 string const prev_par_lang = use_polyglossia ?
158 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
159 string const doc_lang = use_polyglossia ?
160 getPolyglossiaEnvName(doc_language) : doc_language->babel();
161 string const lang_begin_command = use_polyglossia ?
162 "\\begin{$$lang}" : lyxrc.language_command_begin;
163 string const lang_end_command = use_polyglossia ?
164 "\\end{$$lang}" : lyxrc.language_command_end;
166 if (par_lang != prev_par_lang) {
167 if (!lang_end_command.empty() &&
168 prev_par_lang != doc_lang &&
169 !prev_par_lang.empty()) {
170 os << from_ascii(subst(
174 // the '%' is necessary to prevent unwanted whitespace
178 if ((lang_end_command.empty() ||
179 par_lang != doc_lang) &&
181 string bc = use_polyglossia ?
182 getPolyglossiaBegin(lang_begin_command, par_lang,
183 data.par_language->polyglossiaOpts())
184 : subst(lang_begin_command, "$$lang", par_lang);
186 // the '%' is necessary to prevent unwanted whitespace
191 data.leftindent_open = false;
192 if (!pit->params().leftIndent().zero()) {
193 os << "\\begin{LyXParagraphLeftIndent}{"
194 << from_ascii(pit->params().leftIndent().asLatexString())
196 data.leftindent_open = true;
199 if (style.isEnvironment()) {
200 if (par_lang != doc_lang)
201 state->open_polyglossia_lang_ = par_lang;
202 os << "\\begin{" << from_ascii(style.latexname()) << '}';
203 if (!style.latexargs().empty()) {
204 OutputParams rp = runparams;
205 rp.local_font = &pit->getFirstFontSettings(bparams);
206 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
208 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
210 << pit->params().labelWidthString()
212 } else if (style.labeltype == LABEL_BIBLIO) {
213 if (pit->params().labelWidthString().empty())
214 os << '{' << bibitemWidest(buf, runparams) << "}\n";
217 << pit->params().labelWidthString()
220 os << from_ascii(style.latexparam()) << '\n';
224 // in multilingual environments, the CJK tags have to be nested properly
225 data.cjk_nested = false;
226 if (data.par_language->encoding()->package() == Encoding::CJK &&
227 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
228 if (prev_par_language->encoding()->package() == Encoding::CJK)
229 os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
230 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
231 state->open_encoding_ = CJK;
232 data.cjk_nested = true;
238 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
239 TeXEnvironmentData const & data)
241 OutputState * state = getOutputState();
242 // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
243 if (state->open_encoding_ == CJK && data.cjk_nested) {
244 // We need to close the encoding even if it does not change
245 // to do correct environment nesting
246 os << "\\end{CJK}\n";
247 state->open_encoding_ = none;
250 if (data.style->isEnvironment()) {
252 << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
253 state->prev_env_language_ = data.par_language;
254 if (runparams.encoding != data.prev_encoding) {
255 runparams.encoding = data.prev_encoding;
256 os << setEncoding(data.prev_encoding->iconvName());
260 if (data.leftindent_open) {
261 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
262 state->prev_env_language_ = data.par_language;
263 if (runparams.encoding != data.prev_encoding) {
264 runparams.encoding = data.prev_encoding;
265 os << setEncoding(data.prev_encoding->iconvName());
269 // Check whether we should output a blank line after the environment
270 if (!data.style->nextnoindent)
275 void TeXEnvironment(Buffer const & buf, Text const & text,
276 OutputParams const & runparams,
277 pit_type & pit, otexstream & os)
279 ParagraphList const & paragraphs = text.paragraphs();
280 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
281 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
283 Layout const & current_layout = par->layout();
284 depth_type const current_depth = par->params().depth();
285 Length const & current_left_indent = par->params().leftIndent();
287 // This is for debugging purpose at the end.
288 pit_type const par_begin = pit;
289 for (; pit < runparams.par_end; ++pit) {
290 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
292 // check first if this is an higher depth paragraph.
293 bool go_out = (par->params().depth() < current_depth);
294 if (par->params().depth() == current_depth) {
295 // This environment is finished.
296 go_out |= (par->layout() != current_layout);
297 go_out |= (par->params().leftIndent() != current_left_indent);
300 // nothing to do here, restore pit and go out.
305 if (par->layout() == current_layout
306 && par->params().depth() == current_depth
307 && par->params().leftIndent() == current_left_indent) {
308 // We are still in the same environment so TeXOnePar and continue;
309 TeXOnePar(buf, text, pit, os, runparams);
313 // We are now in a deeper environment.
314 // Either par->layout() != current_layout
315 // Or par->params().depth() > current_depth
316 // Or par->params().leftIndent() != current_left_indent)
318 // FIXME This test should not be necessary.
319 // We should perhaps issue an error if it is.
320 bool const force_plain_layout = text.inset().forcePlainLayout();
321 Layout const & style = force_plain_layout
322 ? buf.params().documentClass().plainLayout()
325 if (!style.isEnvironment()) {
326 // This is a standard paragraph, no need to call TeXEnvironment.
327 TeXOnePar(buf, text, pit, os, runparams);
331 // This is a new environment.
332 TeXEnvironmentData const data =
333 prepareEnvironment(buf, text, par, os, runparams);
334 // Recursive call to TeXEnvironment!
335 TeXEnvironment(buf, text, runparams, pit, os);
336 finishEnvironment(os, runparams, data);
339 if (pit != runparams.par_end)
340 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
344 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
345 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
347 unsigned int const argnr = latexargs.size();
351 // Default and preset args are always output, so if they require
352 // other arguments, consider this.
353 Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
354 Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
355 for (; lit != lend; ++lit) {
356 Layout::latexarg arg = (*lit).second;
357 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
358 vector<string> req = getVectorFromString(arg.requires);
359 required.insert(required.end(), req.begin(), req.end());
363 for (unsigned int i = 1; i <= argnr; ++i) {
364 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
365 bool inserted = false;
366 if (lit != ilist.end()) {
367 InsetArgument const * ins = (*lit).second;
369 Layout::LaTeXArgMap::const_iterator const lait =
370 latexargs.find(ins->name());
371 if (lait != latexargs.end()) {
372 Layout::latexarg arg = (*lait).second;
373 docstring ldelim = arg.mandatory ?
374 from_ascii("{") : from_ascii("[");
375 docstring rdelim = arg.mandatory ?
376 from_ascii("}") : from_ascii("]");
377 if (!arg.ldelim.empty())
379 if (!arg.rdelim.empty())
381 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
387 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
388 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
389 for (; lait != laend; ++lait) {
390 string const name = prefix + convert<string>(i);
391 if ((*lait).first == name) {
392 Layout::latexarg arg = (*lait).second;
393 docstring preset = arg.presetarg;
394 if (!arg.defaultarg.empty()) {
397 preset += arg.defaultarg;
400 docstring ldelim = arg.ldelim.empty() ?
401 from_ascii("{") : arg.ldelim;
402 docstring rdelim = arg.rdelim.empty() ?
403 from_ascii("}") : arg.rdelim;
404 os << ldelim << preset << rdelim;
405 } else if (!preset.empty()) {
406 docstring ldelim = arg.ldelim.empty() ?
407 from_ascii("[") : arg.ldelim;
408 docstring rdelim = arg.rdelim.empty() ?
409 from_ascii("]") : arg.rdelim;
410 os << ldelim << preset << rdelim;
411 } else if (find(required.begin(), required.end(),
412 (*lait).first) != required.end()) {
413 docstring ldelim = arg.ldelim.empty() ?
414 from_ascii("[") : arg.ldelim;
415 docstring rdelim = arg.rdelim.empty() ?
416 from_ascii("]") : arg.rdelim;
417 os << ldelim << rdelim;
430 void latexArgInsets(Paragraph const & par, otexstream & os,
431 OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
433 map<int, InsetArgument const *> ilist;
434 vector<string> required;
436 InsetList::const_iterator it = par.insetList().begin();
437 InsetList::const_iterator end = par.insetList().end();
438 for (; it != end; ++it) {
439 if (it->inset->lyxCode() == ARG_CODE) {
440 InsetArgument const * ins =
441 static_cast<InsetArgument const *>(it->inset);
442 if (ins->name().empty())
443 LYXERR0("Error: Unnamed argument inset!");
445 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
446 unsigned int const nr = convert<unsigned int>(name);
448 Layout::LaTeXArgMap::const_iterator const lit =
449 latexargs.find(ins->name());
450 if (lit != latexargs.end()) {
451 Layout::latexarg const & arg = (*lit).second;
452 if (!arg.requires.empty()) {
453 vector<string> req = getVectorFromString(arg.requires);
454 required.insert(required.end(), req.begin(), req.end());
460 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
464 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
465 otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
466 string const & prefix)
468 map<int, InsetArgument const *> ilist;
469 vector<string> required;
471 depth_type const current_depth = pit->params().depth();
472 Layout const current_layout = pit->layout();
474 // get the first paragraph in sequence with this layout and depth
477 if (lyx::prev(pit, offset) == pars.begin())
479 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
480 if (priorpit->layout() == current_layout
481 && priorpit->params().depth() == current_depth)
487 ParagraphList::const_iterator spit = lyx::prev(pit, offset);
489 for (; spit != pars.end(); ++spit) {
490 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
492 if (spit->params().depth() > current_depth)
494 InsetList::const_iterator it = spit->insetList().begin();
495 InsetList::const_iterator end = spit->insetList().end();
496 for (; it != end; ++it) {
497 if (it->inset->lyxCode() == ARG_CODE) {
498 InsetArgument const * ins =
499 static_cast<InsetArgument const *>(it->inset);
500 if (ins->name().empty())
501 LYXERR0("Error: Unnamed argument inset!");
503 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
504 unsigned int const nr = convert<unsigned int>(name);
505 if (ilist.find(nr) == ilist.end())
507 Layout::LaTeXArgMap::const_iterator const lit =
508 latexargs.find(ins->name());
509 if (lit != latexargs.end()) {
510 Layout::latexarg const & arg = (*lit).second;
511 if (!arg.requires.empty()) {
512 vector<string> req = getVectorFromString(arg.requires);
513 required.insert(required.end(), req.begin(), req.end());
520 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
525 // output the proper paragraph start according to latextype.
526 void parStartCommand(Paragraph const & par, otexstream & os,
527 OutputParams const & runparams, Layout const & style)
529 switch (style.latextype) {
531 os << '\\' << from_ascii(style.latexname());
534 if (!style.latexargs().empty())
535 latexArgInsets(par, os, runparams, style.latexargs());
536 os << from_ascii(style.latexparam());
538 case LATEX_ITEM_ENVIRONMENT:
539 case LATEX_LIST_ENVIRONMENT:
540 os << "\\" + style.itemcommand();
542 if (!style.itemargs().empty())
543 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
546 case LATEX_BIB_ENVIRONMENT:
547 // ignore this, the inset will write itself
556 // FIXME: this should be anonymous
557 void TeXOnePar(Buffer const & buf,
561 OutputParams const & runparams_in,
562 string const & everypar,
563 int start_pos, int end_pos)
565 BufferParams const & bparams = runparams_in.is_child
566 ? buf.masterParams() : buf.params();
567 ParagraphList const & paragraphs = text.paragraphs();
568 Paragraph const & par = paragraphs.at(pit);
569 // FIXME This check should not really be needed.
570 // Perhaps we should issue an error if it is.
571 Layout const & style = text.inset().forcePlainLayout() ?
572 bparams.documentClass().plainLayout() : par.layout();
574 if (style.inpreamble)
577 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
580 OutputParams runparams = runparams_in;
581 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
582 // We reinitialze par begin and end to be on the safe side
583 // with embedded inset as we don't know if they set those
585 runparams.par_begin = 0;
586 runparams.par_end = 0;
588 bool const maintext = text.isMainText();
589 // we are at the beginning of an inset and CJK is already open;
590 // we count inheritation levels to get the inset nesting right.
591 OutputState * state = getOutputState();
592 if (pit == 0 && !maintext
593 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
594 state->cjk_inherited_ += 1;
595 state->open_encoding_ = none;
598 if (text.inset().isPassThru()) {
599 Font const outerfont = text.outerFont(pit);
601 // No newline before first paragraph in this lyxtext
604 if (!text.inset().getLayout().parbreakIsNewline())
608 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
612 Paragraph const * nextpar = runparams.isLastPar
613 ? 0 : ¶graphs.at(pit + 1);
615 if (style.pass_thru) {
616 Font const outerfont = text.outerFont(pit);
617 parStartCommand(par, os, runparams, style);
619 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
621 // I did not create a parEndCommand for this minuscule
622 // task because in the other user of parStartCommand
623 // the code is different (JMarc)
624 if (style.isCommand())
628 if (!style.parbreak_is_newline) {
630 } else if (nextpar && !style.isEnvironment()) {
631 Layout const nextstyle = text.inset().forcePlainLayout()
632 ? bparams.documentClass().plainLayout()
634 if (nextstyle.name() != style.name())
641 // This paragraph's language
642 Language const * const par_language = par.getParLanguage(bparams);
643 Language const * const nextpar_language = nextpar ?
644 nextpar->getParLanguage(bparams) : 0;
645 // The document's language
646 Language const * const doc_language = bparams.language;
647 // The language that was in effect when the environment this paragraph is
648 // inside of was opened
649 Language const * const outer_language =
650 (runparams.local_font != 0) ?
651 runparams.local_font->language() : doc_language;
653 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
655 // The previous language that was in effect is the language of the
656 // previous paragraph, unless the previous paragraph is inside an
657 // environment with nesting depth greater than (or equal to, but with
658 // a different layout) the current one. If there is no previous
659 // paragraph, the previous language is the outer language.
660 bool const use_prev_env_language = state->prev_env_language_ != 0
662 && priorpar->layout().isEnvironment()
663 && (priorpar->getDepth() > par.getDepth()
664 || (priorpar->getDepth() == par.getDepth()
665 && priorpar->layout() != par.layout()));
666 Language const * const prev_language =
668 ? (use_prev_env_language ? state->prev_env_language_
669 : priorpar->getParLanguage(bparams))
673 bool const use_polyglossia = runparams.use_polyglossia;
674 string const par_lang = use_polyglossia ?
675 getPolyglossiaEnvName(par_language): par_language->babel();
676 string const prev_lang = use_polyglossia ?
677 getPolyglossiaEnvName(prev_language) : prev_language->babel();
678 string const outer_lang = use_polyglossia ?
679 getPolyglossiaEnvName(outer_language) : outer_language->babel();
680 string const nextpar_lang = nextpar_language ? (use_polyglossia ?
681 getPolyglossiaEnvName(nextpar_language) :
682 nextpar_language->babel()) : string();
683 string lang_begin_command = use_polyglossia ?
684 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
685 string lang_end_command = use_polyglossia ?
686 "\\end{$$lang}" : lyxrc.language_command_end;
687 // the '%' is necessary to prevent unwanted whitespace
688 string lang_command_termination = "%\n";
690 // In some insets (such as Arguments), we cannot use \selectlanguage
691 bool const localswitch = text.inset().forceLocalFontSwitch();
693 lang_begin_command = use_polyglossia ?
694 "\\text$$lang$$opts{" : lyxrc.language_command_local;
695 lang_end_command = "}";
696 lang_command_termination.clear();
699 if (par_lang != prev_lang
700 // check if we already put language command in TeXEnvironment()
701 && !(style.isEnvironment()
702 && (pit == 0 || (priorpar->layout() != par.layout()
703 && priorpar->getDepth() <= par.getDepth())
704 || priorpar->getDepth() < par.getDepth())))
706 if (!lang_end_command.empty() &&
707 prev_lang != outer_lang &&
710 os << from_ascii(subst(lang_end_command,
713 << lang_command_termination;
714 if (prev_lang == state->open_polyglossia_lang_)
715 state->open_polyglossia_lang_ = "";
718 // We need to open a new language if we couldn't close the previous
719 // one (because there's no language_command_end); and even if we closed
720 // the previous one, if the current language is different than the
721 // outer_language (which is currently in effect once the previous one
723 if ((lang_end_command.empty() || par_lang != outer_lang)
724 && !par_lang.empty()) {
725 // If we're inside an inset, and that inset is within an \L or \R
726 // (or equivalents), then within the inset, too, any opposite
727 // language paragraph should appear within an \L or \R (in addition
728 // to, outside of, the normal language switch commands).
729 // This behavior is not correct for ArabTeX, though.
732 && par_language->lang() != "arabic_arabtex"
733 && outer_language->lang() != "arabic_arabtex"
734 // are we in an inset?
735 && runparams.local_font != 0
736 // is the inset within an \L or \R?
738 // FIXME: currently, we don't check this; this means that
739 // we'll have unnnecessary \L and \R commands, but that
740 // doesn't seem to hurt (though latex will complain)
742 // is this paragraph in the opposite direction?
743 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
744 // FIXME: I don't have a working copy of the Arabi package, so
745 // I'm not sure if the farsi and arabic_arabi stuff is correct
747 if (par_language->lang() == "farsi")
749 else if (outer_language->lang() == "farsi")
751 else if (par_language->lang() == "arabic_arabi")
753 else if (outer_language->lang() == "arabic_arabi")
755 // remaining RTL languages currently is hebrew
756 else if (par_language->rightToLeft())
761 // With CJK, the CJK tag has to be closed first (see below)
762 if (runparams.encoding->package() != Encoding::CJK
763 && !par_lang.empty()) {
764 string bc = use_polyglossia ?
765 getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
766 : subst(lang_begin_command, "$$lang", par_lang);
768 os << lang_command_termination;
773 // Switch file encoding if necessary; no need to do this for "default"
774 // encoding, since this only affects the position of the outputted
775 // \inputencoding command; the encoding switch will occur when necessary
776 if (bparams.inputenc == "auto"
777 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding (see also switchEncoding())
778 && runparams.encoding->package() != Encoding::none) {
779 // Look ahead for future encoding changes.
780 // We try to output them at the beginning of the paragraph,
781 // since the \inputencoding command is not allowed e.g. in
782 // sections. For this reason we only set runparams.moving_arg
783 // after checking for the encoding change, otherwise the
784 // change would be always avoided by switchEncoding().
785 for (pos_type i = 0; i < par.size(); ++i) {
786 char_type const c = par.getChar(i);
787 Encoding const * const encoding =
788 par.getFontSettings(bparams, i).language()->encoding();
789 if (encoding->package() != Encoding::CJK
790 && runparams.encoding->package() == Encoding::inputenc
795 // All characters before c are in the ASCII range, and
796 // c is non-ASCII (but no inset), so change the
797 // encoding to that required by the language of c.
798 // With CJK, only add switch if we have CJK content at the beginning
800 if (i != 0 && encoding->package() == Encoding::CJK)
803 pair<bool, int> enc_switch = switchEncoding(os.os(),
804 bparams, runparams, *encoding);
805 // the following is necessary after a CJK environment in a multilingual
806 // context (nesting issue).
807 if (par_language->encoding()->package() == Encoding::CJK
808 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
809 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
810 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
811 state->open_encoding_ = CJK;
813 if (encoding->package() != Encoding::none && enc_switch.first) {
814 if (enc_switch.second > 0) {
815 // the '%' is necessary to prevent unwanted whitespace
818 // With CJK, the CJK tag had to be closed first (see above)
819 if (runparams.encoding->package() == Encoding::CJK
820 && !par_lang.empty()) {
821 os << from_ascii(subst(
825 << lang_command_termination;
827 runparams.encoding = encoding;
833 runparams.moving_arg |= style.needprotect;
834 Encoding const * const prev_encoding = runparams.encoding;
836 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
837 if (par.allowParagraphCustomization()) {
838 if (par.params().startOfAppendix()) {
839 os << "\n\\appendix\n";
842 if (!par.params().spacing().isDefault()
843 && (pit == 0 || !priorpar->hasSameLayout(par)))
845 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
849 if (style.isCommand()) {
854 parStartCommand(par, os, runparams, style);
855 Font const outerfont = text.outerFont(pit);
858 os << from_utf8(everypar);
859 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
861 // Make sure that \\par is done with the font of the last
862 // character if this has another size as the default.
863 // This is necessary because LaTeX (and LyX on the screen)
864 // calculates the space between the baselines according
865 // to this font. (Matthias)
867 // We must not change the font for the last paragraph
868 // of non-multipar insets, tabular cells or commands,
869 // since this produces unwanted whitespace.
871 Font const font = par.empty()
872 ? par.getLayoutFont(bparams, outerfont)
873 : par.getFont(bparams, par.size() - 1, outerfont);
875 bool const is_command = style.isCommand();
877 if (style.resfont.size() != font.fontInfo().size()
878 && (nextpar || maintext
879 || (text.inset().paragraphs().size() > 1
880 && text.inset().lyxCode() != CELL_CODE))
883 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
884 } else if (is_command) {
886 if (!style.postcommandargs().empty())
887 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
888 if (runparams.encoding != prev_encoding) {
889 runparams.encoding = prev_encoding;
890 os << setEncoding(prev_encoding->iconvName());
894 bool pending_newline = false;
895 bool unskip_newline = false;
896 switch (style.latextype) {
897 case LATEX_ITEM_ENVIRONMENT:
898 case LATEX_LIST_ENVIRONMENT:
899 if (nextpar && par.params().depth() < nextpar->params().depth())
900 pending_newline = true;
902 case LATEX_ENVIRONMENT: {
903 // if its the last paragraph of the current environment
904 // skip it otherwise fall through
906 && (nextpar->layout() != par.layout()
907 || nextpar->params().depth() != par.params().depth()))
911 // fall through possible
913 // we don't need it for the last paragraph!!!
915 pending_newline = true;
918 if (par.allowParagraphCustomization()) {
919 if (!par.params().spacing().isDefault()
920 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
924 string const endtag =
925 par.params().spacing().writeEnvirEnd(useSetSpace);
926 if (prefixIs(endtag, "\\end{"))
929 os << from_ascii(endtag);
930 pending_newline = true;
934 // Closing the language is needed for the last paragraph; it is also
935 // needed if we're within an \L or \R that we may have opened above (not
936 // necessarily in this paragraph) and are about to close.
937 bool closing_rtl_ltr_environment = !use_polyglossia
939 && (par_language->lang() != "arabic_arabtex"
940 && outer_language->lang() != "arabic_arabtex")
941 // have we opened an \L or \R environment?
942 && runparams.local_font != 0
943 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
944 // are we about to close the language?
945 &&((nextpar && par_lang != nextpar_lang)
946 || (runparams.isLastPar && par_lang != outer_lang));
948 if (closing_rtl_ltr_environment
949 || (runparams.isLastPar
950 && par_lang != outer_lang)) {
951 // Since \selectlanguage write the language to the aux file,
952 // we need to reset the language at the end of footnote or
958 // when the paragraph uses CJK, the language has to be closed earlier
959 if (font.language()->encoding()->package() != Encoding::CJK) {
960 if (lang_end_command.empty()) {
961 // If this is a child, we should restore the
962 // master language after the last paragraph.
963 Language const * const current_language =
964 (runparams.isLastPar && runparams.master_language)
965 ? runparams.master_language
967 string const current_lang = use_polyglossia
968 ? getPolyglossiaEnvName(current_language)
969 : current_language->babel();
970 if (!current_lang.empty()) {
971 string bc = use_polyglossia ?
972 getPolyglossiaBegin(lang_begin_command, current_lang,
973 current_language->polyglossiaOpts())
974 : subst(lang_begin_command, "$$lang", current_lang);
976 pending_newline = !localswitch;
977 unskip_newline = !localswitch;
979 } else if (!par_lang.empty()) {
980 // If we are in an environment, we have to close the "outer" language afterwards
981 if (!style.isEnvironment() || state->open_polyglossia_lang_ != par_lang) {
982 os << from_ascii(subst(
986 pending_newline = !localswitch;
987 unskip_newline = !localswitch;
992 if (closing_rtl_ltr_environment)
995 bool const last_was_separator =
996 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
998 if (pending_newline) {
1000 // prevent unwanted whitespace
1002 if (!os.afterParbreak() && !last_was_separator)
1006 // if this is a CJK-paragraph and the next isn't, close CJK
1007 // also if the next paragraph is a multilingual environment (because of nesting)
1009 && state->open_encoding_ == CJK
1010 && (nextpar_language->encoding()->package() != Encoding::CJK
1011 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1012 // inbetween environments, CJK has to be closed later (nesting!)
1013 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1014 os << "\\end{CJK}\n";
1015 state->open_encoding_ = none;
1018 // If this is the last paragraph, close the CJK environment
1019 // if necessary. If it's an environment, we'll have to \end that first.
1020 if (runparams.isLastPar && !style.isEnvironment()) {
1021 switch (state->open_encoding_) {
1023 // do nothing at the end of child documents
1024 if (maintext && buf.masterBuffer() != &buf)
1028 os << "\n\\end{CJK}\n";
1032 state->open_encoding_ = none;
1037 state->open_encoding_ = none;
1047 // If this is the last paragraph, and a local_font was set upon entering
1048 // the inset, and we're using "auto" or "default" encoding, and not
1049 // compiling with XeTeX or LuaTeX, the encoding
1050 // should be set back to that local_font's encoding.
1051 if (runparams.isLastPar && runparams_in.local_font != 0
1052 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1053 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1054 && !runparams.isFullUnicode()
1056 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1057 os << setEncoding(runparams_in.encoding->iconvName());
1059 // Otherwise, the current encoding should be set for the next paragraph.
1061 runparams_in.encoding = runparams.encoding;
1064 // we don't need a newline for the last paragraph!!!
1065 // Note from JMarc: we will re-add a \n explicitly in
1066 // TeXEnvironment, because it is needed in this case
1067 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1068 // Make sure to start a new line
1070 Layout const & next_layout = nextpar->layout();
1071 // A newline '\n' is always output before a command,
1072 // so avoid doubling it.
1073 if (!next_layout.isCommand()) {
1074 // Here we now try to avoid spurious empty lines by
1075 // outputting a paragraph break only if: (case 1) the
1076 // paragraph style allows parbreaks and no \begin, \end
1077 // or \item tags are going to follow (i.e., if the next
1078 // isn't the first or the current isn't the last
1079 // paragraph of an environment or itemize) and the
1080 // depth and alignment of the following paragraph is
1081 // unchanged, or (case 2) the following is a
1082 // non-environment paragraph whose depth is increased
1083 // but whose alignment is unchanged, or (case 3) the
1084 // paragraph is not an environment and the next one is a
1085 // non-itemize-like env at lower depth, or (case 4) the
1086 // paragraph is a command not followed by an environment
1087 // and the alignment of the current and next paragraph
1088 // is unchanged, or (case 5) the current alignment is
1089 // changed and a standard paragraph follows.
1090 DocumentClass const & tclass = bparams.documentClass();
1091 if ((style == next_layout
1092 && !style.parbreak_is_newline
1093 && !text.inset().getLayout().parbreakIsNewline()
1094 && style.latextype != LATEX_ITEM_ENVIRONMENT
1095 && style.latextype != LATEX_LIST_ENVIRONMENT
1096 && style.align == par.getAlign()
1097 && nextpar->getDepth() == par.getDepth()
1098 && nextpar->getAlign() == par.getAlign())
1099 || (!next_layout.isEnvironment()
1100 && nextpar->getDepth() > par.getDepth()
1101 && nextpar->getAlign() == par.getAlign())
1102 || (!style.isEnvironment()
1103 && next_layout.latextype == LATEX_ENVIRONMENT
1104 && nextpar->getDepth() < par.getDepth())
1105 || (style.isCommand()
1106 && !next_layout.isEnvironment()
1107 && style.align == par.getAlign()
1108 && next_layout.align == nextpar->getAlign())
1109 || (style.align != par.getAlign()
1110 && tclass.isDefaultLayout(next_layout))) {
1116 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1117 << &par << " next " << nextpar);
1123 // LaTeX all paragraphs
1124 void latexParagraphs(Buffer const & buf,
1127 OutputParams const & runparams,
1128 string const & everypar)
1130 LASSERT(runparams.par_begin <= runparams.par_end,
1131 { os << "% LaTeX Output Error\n"; return; } );
1133 BufferParams const & bparams = buf.params();
1135 bool const maintext = text.isMainText();
1136 bool const is_child = buf.masterBuffer() != &buf;
1138 // Open a CJK environment at the beginning of the main buffer
1139 // if the document's language is a CJK language
1140 // (but not in child documents)
1141 OutputState * state = getOutputState();
1142 if (maintext && !is_child
1143 && bparams.encoding().package() == Encoding::CJK) {
1144 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1145 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1146 state->open_encoding_ = CJK;
1148 // if "auto begin" is switched off, explicitly switch the
1149 // language on at start
1150 string const mainlang = runparams.use_polyglossia
1151 ? getPolyglossiaEnvName(bparams.language)
1152 : bparams.language->babel();
1153 string const lang_begin_command = runparams.use_polyglossia ?
1154 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1156 if (maintext && !lyxrc.language_auto_begin &&
1157 !mainlang.empty()) {
1159 string bc = runparams.use_polyglossia ?
1160 getPolyglossiaBegin(lang_begin_command, mainlang,
1161 bparams.language->polyglossiaOpts())
1162 : subst(lang_begin_command, "$$lang", mainlang);
1167 ParagraphList const & paragraphs = text.paragraphs();
1169 if (runparams.par_begin == runparams.par_end) {
1170 // The full doc will be exported but it is easier to just rely on
1171 // runparams range parameters that will be passed TeXEnvironment.
1172 runparams.par_begin = 0;
1173 runparams.par_end = paragraphs.size();
1176 pit_type pit = runparams.par_begin;
1177 // lastpit is for the language check after the loop.
1178 pit_type lastpit = pit;
1179 // variables used in the loop:
1180 bool was_title = false;
1181 bool already_title = false;
1182 DocumentClass const & tclass = bparams.documentClass();
1184 // Did we already warn about inTitle layout mixing? (we only warn once)
1185 bool gave_layout_warning = false;
1186 for (; pit < runparams.par_end; ++pit) {
1188 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1190 // FIXME This check should not be needed. We should
1191 // perhaps issue an error if it is.
1192 Layout const & layout = text.inset().forcePlainLayout() ?
1193 tclass.plainLayout() : par->layout();
1195 if (layout.intitle) {
1196 if (already_title) {
1197 if (!gave_layout_warning) {
1198 gave_layout_warning = true;
1199 frontend::Alert::warning(_("Error in latexParagraphs"),
1200 bformat(_("You are using at least one "
1201 "layout (%1$s) intended for the title, "
1202 "after using non-title layouts. This "
1203 "could lead to missing or incorrect output."
1206 } else if (!was_title) {
1208 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1210 << from_ascii(tclass.titlename())
1214 } else if (was_title && !already_title) {
1215 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1216 os << "\\end{" << from_ascii(tclass.titlename())
1220 os << "\\" << from_ascii(tclass.titlename())
1223 already_title = true;
1228 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1229 // This is a standard top level paragraph, TeX it and continue.
1230 TeXOnePar(buf, text, pit, os, runparams, everypar);
1234 TeXEnvironmentData const data =
1235 prepareEnvironment(buf, text, par, os, runparams);
1236 // pit can be changed in TeXEnvironment.
1237 TeXEnvironment(buf, text, runparams, pit, os);
1238 finishEnvironment(os, runparams, data);
1241 if (pit == runparams.par_end) {
1242 // Make sure that the last paragraph is
1243 // correctly terminated (because TeXOnePar does
1244 // not add a \n in this case)
1248 // It might be that we only have a title in this document
1249 if (was_title && !already_title) {
1250 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1251 os << "\\end{" << from_ascii(tclass.titlename())
1254 os << "\\" << from_ascii(tclass.titlename())
1259 // if "auto end" is switched off, explicitly close the language at the end
1260 // but only if the last par is in a babel or polyglossia language
1261 string const lang_end_command = runparams.use_polyglossia ?
1262 "\\end{$$lang}" : lyxrc.language_command_end;
1263 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1264 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1265 os << from_utf8(subst(lang_end_command,
1269 if (state->open_polyglossia_lang_ == mainlang)
1270 state->open_polyglossia_lang_ = "";
1273 // If the last paragraph is an environment, we'll have to close
1274 // CJK at the very end to do proper nesting.
1275 if (maintext && !is_child && state->open_encoding_ == CJK) {
1276 os << "\\end{CJK}\n";
1277 state->open_encoding_ = none;
1279 // Likewise for polyglossia
1280 if (maintext && !is_child && state->open_polyglossia_lang_ != "") {
1281 os << from_utf8(subst(lang_end_command,
1283 state->open_polyglossia_lang_))
1285 state->open_polyglossia_lang_ = "";
1288 // reset inherited encoding
1289 if (state->cjk_inherited_ > 0) {
1290 state->cjk_inherited_ -= 1;
1291 if (state->cjk_inherited_ == 0)
1292 state->open_encoding_ = CJK;
1297 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1298 OutputParams const & runparams, Encoding const & newEnc,
1301 // XeTeX/LuaTeX use only one encoding per document:
1302 // * with useNonTeXFonts: "utf8plain",
1303 // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1304 // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1305 if (runparams.isFullUnicode())
1306 return make_pair(false, 0);
1308 Encoding const & oldEnc = *runparams.encoding;
1309 bool moving_arg = runparams.moving_arg;
1310 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1311 bool const from_to_cjk =
1312 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1313 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1314 if (!force && !from_to_cjk
1315 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1316 return make_pair(false, 0);
1318 // Do nothing if the encoding is unchanged.
1319 if (oldEnc.name() == newEnc.name())
1320 return make_pair(false, 0);
1322 // FIXME We ignore encoding switches from/to encodings that do
1323 // neither support the inputenc package nor the CJK package here.
1324 // This does of course only work in special cases (e.g. switch from
1325 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1326 // but it is the best we can do
1327 if (oldEnc.package() == Encoding::none
1328 || newEnc.package() == Encoding::none)
1329 return make_pair(false, 0);
1331 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1332 << oldEnc.name() << " to " << newEnc.name());
1333 os << setEncoding(newEnc.iconvName());
1334 if (bparams.inputenc == "default")
1335 return make_pair(true, 0);
1337 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1338 OutputState * state = getOutputState();
1339 switch (newEnc.package()) {
1340 case Encoding::none:
1341 case Encoding::japanese:
1342 // shouldn't ever reach here, see above
1343 return make_pair(true, 0);
1344 case Encoding::inputenc: {
1345 int count = inputenc_arg.length();
1346 if (oldEnc.package() == Encoding::CJK &&
1347 state->open_encoding_ == CJK) {
1349 state->open_encoding_ = none;
1352 else if (oldEnc.package() == Encoding::inputenc &&
1353 state->open_encoding_ == inputenc) {
1355 state->open_encoding_ = none;
1358 if (runparams.local_font != 0
1359 && oldEnc.package() == Encoding::CJK) {
1360 // within insets, \inputenc switches need
1361 // to be embraced within \bgroup...\egroup;
1365 state->open_encoding_ = inputenc;
1367 // with the japanese option, inputenc is omitted.
1368 if (runparams.use_japanese)
1369 return make_pair(true, count);
1370 os << "\\inputencoding{" << inputenc_arg << '}';
1371 return make_pair(true, count + 16);
1373 case Encoding::CJK: {
1374 int count = inputenc_arg.length();
1375 if (oldEnc.package() == Encoding::CJK &&
1376 state->open_encoding_ == CJK) {
1380 if (oldEnc.package() == Encoding::inputenc &&
1381 state->open_encoding_ == inputenc) {
1385 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1386 << from_ascii(bparams.fonts_cjk) << "}";
1387 state->open_encoding_ = CJK;
1388 return make_pair(true, count + 15);
1391 // Dead code to avoid a warning:
1392 return make_pair(true, 0);