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"
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetArgument.h"
32 #include "support/lassert.h"
33 #include "support/convert.h"
34 #include "support/debug.h"
35 #include "support/lstrings.h"
36 #include "support/textutils.h"
38 #include <QThreadStorage>
41 #include <boost/next_prior.hpp>
45 using namespace lyx::support;
61 OutputState() : open_encoding_(none), cjk_inherited_(0),
67 Language const * prev_env_language_;
71 OutputState * getOutputState()
73 // FIXME An instance of OutputState should be kept around for each export
74 // instead of using local thread storage
75 static QThreadStorage<OutputState *> outputstate;
76 if (!outputstate.hasLocalData())
77 outputstate.setLocalData(new OutputState);
78 return outputstate.localData();
82 string const getPolyglossiaEnvName(Language const * lang)
84 string result = lang->polyglossia();
85 if (result == "arabic")
86 // exceptional spelling; see polyglossia docs.
92 struct TeXEnvironmentData
96 Language const * par_language;
97 Encoding const * prev_encoding;
102 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
104 ParagraphList::const_iterator pit,
106 OutputParams const & runparams)
108 TeXEnvironmentData data;
110 BufferParams const & bparams = buf.params();
112 // FIXME This test should not be necessary.
113 // We should perhaps issue an error if it is.
114 Layout const & style = text.inset().forcePlainLayout() ?
115 bparams.documentClass().plainLayout() : pit->layout();
117 ParagraphList const & paragraphs = text.paragraphs();
118 ParagraphList::const_iterator const priorpit =
119 pit == paragraphs.begin() ? pit : boost::prior(pit);
121 OutputState * state = getOutputState();
122 bool const use_prev_env_language = state->prev_env_language_ != 0
123 && priorpit->layout().isEnvironment()
124 && (priorpit->getDepth() > pit->getDepth()
125 || (priorpit->getDepth() == pit->getDepth()
126 && priorpit->layout() != pit->layout()));
128 data.prev_encoding = runparams.encoding;
129 data.par_language = pit->getParLanguage(bparams);
130 Language const * const doc_language = bparams.language;
131 Language const * const prev_par_language =
132 (pit != paragraphs.begin())
133 ? (use_prev_env_language ? state->prev_env_language_
134 : priorpit->getParLanguage(bparams))
137 bool const use_polyglossia = runparams.use_polyglossia;
138 string const par_lang = use_polyglossia ?
139 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
140 string const prev_par_lang = use_polyglossia ?
141 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
142 string const doc_lang = use_polyglossia ?
143 getPolyglossiaEnvName(doc_language) : doc_language->babel();
144 string const lang_begin_command = use_polyglossia ?
145 "\\begin{$$lang}" : lyxrc.language_command_begin;
146 string const lang_end_command = use_polyglossia ?
147 "\\end{$$lang}" : lyxrc.language_command_end;
149 if (par_lang != prev_par_lang) {
150 if (!lang_end_command.empty() &&
151 prev_par_lang != doc_lang &&
152 !prev_par_lang.empty()) {
153 os << from_ascii(subst(
157 // the '%' is necessary to prevent unwanted whitespace
161 if ((lang_end_command.empty() ||
162 par_lang != doc_lang) &&
164 os << from_ascii(subst(
169 && !data.par_language->polyglossiaOpts().empty())
171 << from_ascii(data.par_language->polyglossiaOpts())
173 // the '%' is necessary to prevent unwanted whitespace
178 data.leftindent_open = false;
179 if (!pit->params().leftIndent().zero()) {
180 os << "\\begin{LyXParagraphLeftIndent}{"
181 << from_ascii(pit->params().leftIndent().asLatexString())
183 data.leftindent_open = true;
186 if (style.isEnvironment()) {
187 os << "\\begin{" << from_ascii(style.latexname()) << '}';
188 if (!style.latexargs().empty()) {
189 OutputParams rp = runparams;
190 rp.local_font = &pit->getFirstFontSettings(bparams);
191 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
193 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
195 << pit->params().labelWidthString()
197 } else if (style.labeltype == LABEL_BIBLIO) {
198 if (pit->params().labelWidthString().empty())
199 os << '{' << bibitemWidest(buf, runparams) << "}\n";
202 << pit->params().labelWidthString()
205 os << from_ascii(style.latexparam()) << '\n';
209 // in multilingual environments, the CJK tags have to be nested properly
210 data.cjk_nested = false;
211 if (data.par_language->encoding()->package() == Encoding::CJK &&
212 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
213 if (prev_par_language->encoding()->package() == Encoding::CJK)
214 os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
215 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
216 state->open_encoding_ = CJK;
217 data.cjk_nested = true;
223 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
224 TeXEnvironmentData const & data)
226 OutputState * state = getOutputState();
227 if (state->open_encoding_ == CJK && data.cjk_nested) {
228 // We need to close the encoding even if it does not change
229 // to do correct environment nesting
230 os << "\\end{CJK}\n";
231 state->open_encoding_ = none;
234 if (data.style->isEnvironment()) {
236 << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
237 state->prev_env_language_ = data.par_language;
238 if (runparams.encoding != data.prev_encoding) {
239 runparams.encoding = data.prev_encoding;
240 if (!runparams.isFullUnicode())
241 os << setEncoding(data.prev_encoding->iconvName());
245 if (data.leftindent_open) {
246 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
247 state->prev_env_language_ = data.par_language;
248 if (runparams.encoding != data.prev_encoding) {
249 runparams.encoding = data.prev_encoding;
250 if (!runparams.isFullUnicode())
251 os << setEncoding(data.prev_encoding->iconvName());
255 // Check whether we should output a blank line after the environment
256 if (!data.style->nextnoindent)
261 void TeXEnvironment(Buffer const & buf, Text const & text,
262 OutputParams const & runparams,
263 pit_type & pit, otexstream & os)
265 ParagraphList const & paragraphs = text.paragraphs();
266 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
267 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
269 Layout const & current_layout = par->layout();
270 depth_type const current_depth = par->params().depth();
271 Length const & current_left_indent = par->params().leftIndent();
273 // This is for debugging purpose at the end.
274 pit_type const par_begin = pit;
275 for (; pit < runparams.par_end; ++pit) {
276 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
278 // check first if this is an higher depth paragraph.
279 bool go_out = (par->params().depth() < current_depth);
280 if (par->params().depth() == current_depth) {
281 // This environment is finished.
282 go_out |= (par->layout() != current_layout);
283 go_out |= (par->params().leftIndent() != current_left_indent);
286 // nothing to do here, restore pit and go out.
291 if (par->layout() == current_layout
292 && par->params().depth() == current_depth
293 && par->params().leftIndent() == current_left_indent) {
294 // We are still in the same environment so TeXOnePar and continue;
295 TeXOnePar(buf, text, pit, os, runparams);
299 // We are now in a deeper environment.
300 // Either par->layout() != current_layout
301 // Or par->params().depth() > current_depth
302 // Or par->params().leftIndent() != current_left_indent)
304 // FIXME This test should not be necessary.
305 // We should perhaps issue an error if it is.
306 bool const force_plain_layout = text.inset().forcePlainLayout();
307 Layout const & style = force_plain_layout
308 ? buf.params().documentClass().plainLayout()
311 if (!style.isEnvironment()) {
312 // This is a standard paragraph, no need to call TeXEnvironment.
313 TeXOnePar(buf, text, pit, os, runparams);
317 // This is a new environment.
318 TeXEnvironmentData const data =
319 prepareEnvironment(buf, text, par, os, runparams);
320 // Recursive call to TeXEnvironment!
321 TeXEnvironment(buf, text, runparams, pit, os);
322 finishEnvironment(os, runparams, data);
325 if (pit != runparams.par_end)
326 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
330 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
331 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
333 unsigned int const argnr = latexargs.size();
337 // Default and preset args are always output, so if they require
338 // other arguments, consider this.
339 Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
340 Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
341 for (; lit != lend; ++lit) {
342 Layout::latexarg arg = (*lit).second;
343 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
344 vector<string> req = getVectorFromString(arg.requires);
345 required.insert(required.end(), req.begin(), req.end());
349 for (unsigned int i = 1; i <= argnr; ++i) {
350 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
351 bool inserted = false;
352 if (lit != ilist.end()) {
353 InsetArgument const * ins = (*lit).second;
355 Layout::LaTeXArgMap::const_iterator const lait =
356 latexargs.find(ins->name());
357 if (lait != latexargs.end()) {
358 Layout::latexarg arg = (*lait).second;
359 docstring ldelim = arg.mandatory ?
360 from_ascii("{") : from_ascii("[");
361 docstring rdelim = arg.mandatory ?
362 from_ascii("}") : from_ascii("]");
363 if (!arg.ldelim.empty())
365 if (!arg.rdelim.empty())
367 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
373 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
374 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
375 for (; lait != laend; ++lait) {
376 string const name = prefix + convert<string>(i);
377 if ((*lait).first == name) {
378 Layout::latexarg arg = (*lait).second;
379 docstring preset = arg.presetarg;
380 if (!arg.defaultarg.empty()) {
383 preset += arg.defaultarg;
386 docstring ldelim = arg.ldelim.empty() ?
387 from_ascii("{") : arg.ldelim;
388 docstring rdelim = arg.rdelim.empty() ?
389 from_ascii("}") : arg.rdelim;
390 os << ldelim << preset << rdelim;
391 } else if (!preset.empty()) {
392 docstring ldelim = arg.ldelim.empty() ?
393 from_ascii("[") : arg.ldelim;
394 docstring rdelim = arg.rdelim.empty() ?
395 from_ascii("]") : arg.rdelim;
396 os << ldelim << preset << rdelim;
397 } else if (find(required.begin(), required.end(),
398 (*lait).first) != required.end()) {
399 docstring ldelim = arg.ldelim.empty() ?
400 from_ascii("[") : arg.ldelim;
401 docstring rdelim = arg.rdelim.empty() ?
402 from_ascii("]") : arg.rdelim;
403 os << ldelim << rdelim;
416 void latexArgInsets(Paragraph const & par, otexstream & os,
417 OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
419 map<int, InsetArgument const *> ilist;
420 vector<string> required;
422 InsetList::const_iterator it = par.insetList().begin();
423 InsetList::const_iterator end = par.insetList().end();
424 for (; it != end; ++it) {
425 if (it->inset->lyxCode() == ARG_CODE) {
426 InsetArgument const * ins =
427 static_cast<InsetArgument const *>(it->inset);
428 if (ins->name().empty())
429 LYXERR0("Error: Unnamed argument inset!");
431 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
432 unsigned int const nr = convert<unsigned int>(name);
434 Layout::LaTeXArgMap::const_iterator const lit =
435 latexargs.find(ins->name());
436 if (lit != latexargs.end()) {
437 Layout::latexarg const & arg = (*lit).second;
438 if (!arg.requires.empty()) {
439 vector<string> req = getVectorFromString(arg.requires);
440 required.insert(required.end(), req.begin(), req.end());
446 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
450 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
451 otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
452 string const & prefix)
454 map<int, InsetArgument const *> ilist;
455 vector<string> required;
457 depth_type const current_depth = pit->params().depth();
458 Layout const current_layout = pit->layout();
460 // get the first paragraph in sequence with this layout and depth
463 if (boost::prior(pit, offset) == pars.begin())
465 ParagraphList::const_iterator priorpit = boost::prior(pit, offset + 1);
466 if (priorpit->layout() == current_layout
467 && priorpit->params().depth() == current_depth)
473 ParagraphList::const_iterator spit = boost::prior(pit, offset);
475 for (; spit != pars.end(); ++spit) {
476 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
478 if (spit->params().depth() > current_depth)
480 InsetList::const_iterator it = spit->insetList().begin();
481 InsetList::const_iterator end = spit->insetList().end();
482 for (; it != end; ++it) {
483 if (it->inset->lyxCode() == ARG_CODE) {
484 InsetArgument const * ins =
485 static_cast<InsetArgument const *>(it->inset);
486 if (ins->name().empty())
487 LYXERR0("Error: Unnamed argument inset!");
489 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
490 unsigned int const nr = convert<unsigned int>(name);
491 if (ilist.find(nr) == ilist.end())
493 Layout::LaTeXArgMap::const_iterator const lit =
494 latexargs.find(ins->name());
495 if (lit != latexargs.end()) {
496 Layout::latexarg const & arg = (*lit).second;
497 if (!arg.requires.empty()) {
498 vector<string> req = getVectorFromString(arg.requires);
499 required.insert(required.end(), req.begin(), req.end());
506 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
511 // output the proper paragraph start according to latextype.
512 void parStartCommand(Paragraph const & par, otexstream & os,
513 OutputParams const & runparams, Layout const & style)
515 switch (style.latextype) {
517 os << '\\' << from_ascii(style.latexname());
520 if (!style.latexargs().empty())
521 latexArgInsets(par, os, runparams, style.latexargs());
522 os << from_ascii(style.latexparam());
524 case LATEX_ITEM_ENVIRONMENT:
525 case LATEX_LIST_ENVIRONMENT:
526 os << "\\" + style.itemcommand();
528 if (!style.itemargs().empty())
529 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
532 case LATEX_BIB_ENVIRONMENT:
533 // ignore this, the inset will write itself
542 // FIXME: this should be anonymous
543 void TeXOnePar(Buffer const & buf,
547 OutputParams const & runparams_in,
548 string const & everypar,
549 int start_pos, int end_pos)
551 BufferParams const & bparams = runparams_in.is_child
552 ? buf.masterParams() : buf.params();
553 ParagraphList const & paragraphs = text.paragraphs();
554 Paragraph const & par = paragraphs.at(pit);
555 // FIXME This check should not really be needed.
556 // Perhaps we should issue an error if it is.
557 Layout const & style = text.inset().forcePlainLayout() ?
558 bparams.documentClass().plainLayout() : par.layout();
560 if (style.inpreamble)
563 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
566 OutputParams runparams = runparams_in;
567 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
568 // We reinitialze par begin and end to be on the safe side
569 // with embedded inset as we don't know if they set those
571 runparams.par_begin = 0;
572 runparams.par_end = 0;
574 bool const maintext = text.isMainText();
575 // we are at the beginning of an inset and CJK is already open;
576 // we count inheritation levels to get the inset nesting right.
577 OutputState * state = getOutputState();
578 if (pit == 0 && !maintext
579 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
580 state->cjk_inherited_ += 1;
581 state->open_encoding_ = none;
584 if (text.inset().isPassThru()) {
585 Font const outerfont = text.outerFont(pit);
587 // No newline before first paragraph in this lyxtext
590 if (!text.inset().getLayout().parbreakIsNewline())
594 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
598 Paragraph const * nextpar = runparams.isLastPar
599 ? 0 : ¶graphs.at(pit + 1);
601 if (style.pass_thru) {
602 Font const outerfont = text.outerFont(pit);
603 parStartCommand(par, os, runparams, style);
605 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
607 // I did not create a parEndCommand for this minuscule
608 // task because in the other user of parStartCommand
609 // the code is different (JMarc)
610 if (style.isCommand())
614 if (!style.parbreak_is_newline) {
616 } else if (nextpar && !style.isEnvironment()) {
617 Layout const nextstyle = text.inset().forcePlainLayout()
618 ? bparams.documentClass().plainLayout()
620 if (nextstyle.name() != style.name())
627 // This paragraph's language
628 Language const * const par_language = par.getParLanguage(bparams);
629 // The document's language
630 Language const * const doc_language = bparams.language;
631 // The language that was in effect when the environment this paragraph is
632 // inside of was opened
633 Language const * const outer_language =
634 (runparams.local_font != 0) ?
635 runparams.local_font->language() : doc_language;
637 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
639 // The previous language that was in effect is the language of the
640 // previous paragraph, unless the previous paragraph is inside an
641 // environment with nesting depth greater than (or equal to, but with
642 // a different layout) the current one. If there is no previous
643 // paragraph, the previous language is the outer language.
644 bool const use_prev_env_language = state->prev_env_language_ != 0
646 && priorpar->layout().isEnvironment()
647 && (priorpar->getDepth() > par.getDepth()
648 || (priorpar->getDepth() == par.getDepth()
649 && priorpar->layout() != par.layout()));
650 Language const * const prev_language =
652 ? (use_prev_env_language ? state->prev_env_language_
653 : priorpar->getParLanguage(bparams))
657 bool const use_polyglossia = runparams.use_polyglossia;
658 string const par_lang = use_polyglossia ?
659 getPolyglossiaEnvName(par_language): par_language->babel();
660 string const prev_lang = use_polyglossia ?
661 getPolyglossiaEnvName(prev_language) : prev_language->babel();
662 string const doc_lang = use_polyglossia ?
663 getPolyglossiaEnvName(doc_language) : doc_language->babel();
664 string const outer_lang = use_polyglossia ?
665 getPolyglossiaEnvName(outer_language) : outer_language->babel();
666 string lang_begin_command = use_polyglossia ?
667 "\\begin{$$lang}" : lyxrc.language_command_begin;
668 string lang_end_command = use_polyglossia ?
669 "\\end{$$lang}" : lyxrc.language_command_end;
670 // the '%' is necessary to prevent unwanted whitespace
671 string lang_command_termination = "%\n";
673 // In some insets (such as Arguments), we cannot use \selectlanguage
674 bool const localswitch = !use_polyglossia
675 && text.inset().getLayout().forcelocalfontswitch();
677 lang_begin_command = lyxrc.language_command_local;
678 lang_end_command = "}";
679 lang_command_termination.clear();
682 if (par_lang != prev_lang
683 // check if we already put language command in TeXEnvironment()
684 && !(style.isEnvironment()
685 && (pit == 0 || (priorpar->layout() != par.layout()
686 && priorpar->getDepth() <= par.getDepth())
687 || priorpar->getDepth() < par.getDepth())))
689 if (!lang_end_command.empty() &&
690 prev_lang != outer_lang &&
693 os << from_ascii(subst(lang_end_command,
696 << lang_command_termination;
699 // We need to open a new language if we couldn't close the previous
700 // one (because there's no language_command_end); and even if we closed
701 // the previous one, if the current language is different than the
702 // outer_language (which is currently in effect once the previous one
704 if ((lang_end_command.empty() || par_lang != outer_lang)
705 && !par_lang.empty()) {
706 // If we're inside an inset, and that inset is within an \L or \R
707 // (or equivalents), then within the inset, too, any opposite
708 // language paragraph should appear within an \L or \R (in addition
709 // to, outside of, the normal language switch commands).
710 // This behavior is not correct for ArabTeX, though.
713 && par_language->lang() != "arabic_arabtex"
714 && outer_language->lang() != "arabic_arabtex"
715 // are we in an inset?
716 && runparams.local_font != 0
717 // is the inset within an \L or \R?
719 // FIXME: currently, we don't check this; this means that
720 // we'll have unnnecessary \L and \R commands, but that
721 // doesn't seem to hurt (though latex will complain)
723 // is this paragraph in the opposite direction?
724 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
725 // FIXME: I don't have a working copy of the Arabi package, so
726 // I'm not sure if the farsi and arabic_arabi stuff is correct
728 if (par_language->lang() == "farsi")
730 else if (outer_language->lang() == "farsi")
732 else if (par_language->lang() == "arabic_arabi")
734 else if (outer_language->lang() == "arabic_arabi")
736 // remaining RTL languages currently is hebrew
737 else if (par_language->rightToLeft())
742 // With CJK, the CJK tag has to be closed first (see below)
743 if (runparams.encoding->package() != Encoding::CJK
744 && !par_lang.empty()) {
745 os << from_ascii(subst(
750 && !par_language->polyglossiaOpts().empty())
752 << from_ascii(par_language->polyglossiaOpts())
754 os << lang_command_termination;
759 // Switch file encoding if necessary; no need to do this for "default"
760 // encoding, since this only affects the position of the outputted
761 // \inputencoding command; the encoding switch will occur when necessary
762 if (bparams.inputenc == "auto"
763 && runparams.encoding->package() != Encoding::none) {
764 // Look ahead for future encoding changes.
765 // We try to output them at the beginning of the paragraph,
766 // since the \inputencoding command is not allowed e.g. in
767 // sections. For this reason we only set runparams.moving_arg
768 // after checking for the encoding change, otherwise the
769 // change would be always avoided by switchEncoding().
770 for (pos_type i = 0; i < par.size(); ++i) {
771 char_type const c = par.getChar(i);
772 Encoding const * const encoding =
773 par.getFontSettings(bparams, i).language()->encoding();
774 if (encoding->package() != Encoding::CJK
775 && runparams.encoding->package() == Encoding::inputenc
780 // All characters before c are in the ASCII range, and
781 // c is non-ASCII (but no inset), so change the
782 // encoding to that required by the language of c.
783 // With CJK, only add switch if we have CJK content at the beginning
785 if (i != 0 && encoding->package() == Encoding::CJK)
788 pair<bool, int> enc_switch = switchEncoding(os.os(),
789 bparams, runparams, *encoding);
790 // the following is necessary after a CJK environment in a multilingual
791 // context (nesting issue).
792 if (par_language->encoding()->package() == Encoding::CJK
793 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
794 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
795 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
796 state->open_encoding_ = CJK;
798 if (encoding->package() != Encoding::none && enc_switch.first) {
799 if (enc_switch.second > 0) {
800 // the '%' is necessary to prevent unwanted whitespace
803 // With CJK, the CJK tag had to be closed first (see above)
804 if (runparams.encoding->package() == Encoding::CJK
805 && !par_lang.empty()) {
806 os << from_ascii(subst(
810 << lang_command_termination;
812 runparams.encoding = encoding;
818 runparams.moving_arg |= style.needprotect;
819 Encoding const * const prev_encoding = runparams.encoding;
821 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
822 if (par.allowParagraphCustomization()) {
823 if (par.params().startOfAppendix()) {
824 os << "\n\\appendix\n";
827 if (!par.params().spacing().isDefault()
828 && (pit == 0 || !priorpar->hasSameLayout(par)))
830 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
834 if (style.isCommand()) {
839 parStartCommand(par, os, runparams, style);
840 Font const outerfont = text.outerFont(pit);
843 os << from_utf8(everypar);
844 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
846 // Make sure that \\par is done with the font of the last
847 // character if this has another size as the default.
848 // This is necessary because LaTeX (and LyX on the screen)
849 // calculates the space between the baselines according
850 // to this font. (Matthias)
852 // We must not change the font for the last paragraph
853 // of non-multipar insets, tabular cells or commands,
854 // since this produces unwanted whitespace.
856 Font const font = par.empty()
857 ? par.getLayoutFont(bparams, outerfont)
858 : par.getFont(bparams, par.size() - 1, outerfont);
860 bool const is_command = style.isCommand();
862 if (style.resfont.size() != font.fontInfo().size()
863 && (nextpar || maintext
864 || (text.inset().getLayout().isMultiPar()
865 && text.inset().lyxCode() != CELL_CODE))
868 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
869 } else if (is_command) {
871 if (!style.postcommandargs().empty())
872 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
873 if (runparams.encoding != prev_encoding) {
874 runparams.encoding = prev_encoding;
875 if (!runparams.isFullUnicode())
876 os << setEncoding(prev_encoding->iconvName());
880 bool pending_newline = false;
881 bool unskip_newline = false;
882 switch (style.latextype) {
883 case LATEX_ITEM_ENVIRONMENT:
884 case LATEX_LIST_ENVIRONMENT:
885 if (nextpar && par.params().depth() < nextpar->params().depth())
886 pending_newline = true;
888 case LATEX_ENVIRONMENT: {
889 // if its the last paragraph of the current environment
890 // skip it otherwise fall through
892 && (nextpar->layout() != par.layout()
893 || nextpar->params().depth() != par.params().depth()))
897 // fall through possible
899 // we don't need it for the last paragraph!!!
901 pending_newline = true;
904 if (par.allowParagraphCustomization()) {
905 if (!par.params().spacing().isDefault()
906 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
910 string const endtag =
911 par.params().spacing().writeEnvirEnd(useSetSpace);
912 if (prefixIs(endtag, "\\end{"))
915 os << from_ascii(endtag);
916 pending_newline = true;
920 // Closing the language is needed for the last paragraph; it is also
921 // needed if we're within an \L or \R that we may have opened above (not
922 // necessarily in this paragraph) and are about to close.
923 bool closing_rtl_ltr_environment = !use_polyglossia
925 && (par_language->lang() != "arabic_arabtex"
926 && outer_language->lang() != "arabic_arabtex")
927 // have we opened an \L or \R environment?
928 && runparams.local_font != 0
929 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
930 // are we about to close the language?
931 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
932 || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
934 if (closing_rtl_ltr_environment
935 || (runparams.isLastPar
936 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
937 || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
938 // Since \selectlanguage write the language to the aux file,
939 // we need to reset the language at the end of footnote or
945 // when the paragraph uses CJK, the language has to be closed earlier
946 if (font.language()->encoding()->package() != Encoding::CJK) {
947 if (lang_end_command.empty()) {
948 // If this is a child, we should restore the
949 // master language after the last paragraph.
950 Language const * const current_language =
951 (runparams.isLastPar && runparams.master_language)
952 ? runparams.master_language
954 string const current_lang = use_polyglossia
955 ? getPolyglossiaEnvName(current_language)
956 : current_language->babel();
957 if (!current_lang.empty()) {
958 os << from_ascii(subst(
962 pending_newline = !localswitch;
963 unskip_newline = !localswitch;
965 } else if (!par_lang.empty()) {
966 os << from_ascii(subst(
970 pending_newline = !localswitch;
971 unskip_newline = !localswitch;
975 if (closing_rtl_ltr_environment)
978 bool const last_was_separator =
979 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
981 if (pending_newline) {
983 // prevent unwanted whitespace
985 if (!os.afterParbreak() && !last_was_separator)
989 // if this is a CJK-paragraph and the next isn't, close CJK
990 // also if the next paragraph is a multilingual environment (because of nesting)
992 && state->open_encoding_ == CJK
993 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
994 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
995 // inbetween environments, CJK has to be closed later (nesting!)
996 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
997 os << "\\end{CJK}\n";
998 state->open_encoding_ = none;
1001 // If this is the last paragraph, close the CJK environment
1002 // if necessary. If it's an environment, we'll have to \end that first.
1003 if (runparams.isLastPar && !style.isEnvironment()) {
1004 switch (state->open_encoding_) {
1006 // do nothing at the end of child documents
1007 if (maintext && buf.masterBuffer() != &buf)
1011 os << "\n\\end{CJK}\n";
1015 state->open_encoding_ = none;
1020 state->open_encoding_ = none;
1030 // If this is the last paragraph, and a local_font was set upon entering
1031 // the inset, and we're using "auto" or "default" encoding, the encoding
1032 // should be set back to that local_font's encoding.
1033 // However, do not change the encoding when a fully unicode aware backend
1034 // such as XeTeX is used.
1035 if (runparams.isLastPar && runparams_in.local_font != 0
1036 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1037 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1038 && (!runparams.isFullUnicode())) {
1039 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1040 os << setEncoding(runparams_in.encoding->iconvName());
1042 // Otherwise, the current encoding should be set for the next paragraph.
1044 runparams_in.encoding = runparams.encoding;
1047 // we don't need a newline for the last paragraph!!!
1048 // Note from JMarc: we will re-add a \n explicitly in
1049 // TeXEnvironment, because it is needed in this case
1050 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1051 // Make sure to start a new line
1053 Layout const & next_layout = nextpar->layout();
1054 // A newline '\n' is always output before a command,
1055 // so avoid doubling it.
1056 if (!next_layout.isCommand()) {
1057 // Here we now try to avoid spurious empty lines by
1058 // outputting a paragraph break only if: (case 1) the
1059 // paragraph style allows parbreaks and no \begin, \end
1060 // or \item tags are going to follow (i.e., if the next
1061 // isn't the first or the current isn't the last
1062 // paragraph of an environment or itemize) and the
1063 // depth and alignment of the following paragraph is
1064 // unchanged, or (case 2) the following is a
1065 // non-environment paragraph whose depth is increased
1066 // but whose alignment is unchanged, or (case 3) the
1067 // paragraph is not an environment and the next one is a
1068 // non-itemize-like env at lower depth, or (case 4) the
1069 // paragraph is a command not followed by an environment
1070 // and the alignment of the current and next paragraph
1071 // is unchanged, or (case 5) the current alignment is
1072 // changed and a standard paragraph follows.
1073 DocumentClass const & tclass = bparams.documentClass();
1074 if ((style == next_layout
1075 && !style.parbreak_is_newline
1076 && style.latextype != LATEX_ITEM_ENVIRONMENT
1077 && style.latextype != LATEX_LIST_ENVIRONMENT
1078 && style.align == par.getAlign()
1079 && nextpar->getDepth() == par.getDepth()
1080 && nextpar->getAlign() == par.getAlign())
1081 || (!next_layout.isEnvironment()
1082 && nextpar->getDepth() > par.getDepth()
1083 && nextpar->getAlign() == par.getAlign())
1084 || (!style.isEnvironment()
1085 && next_layout.latextype == LATEX_ENVIRONMENT
1086 && nextpar->getDepth() < par.getDepth())
1087 || (style.isCommand()
1088 && !next_layout.isEnvironment()
1089 && style.align == par.getAlign()
1090 && next_layout.align == nextpar->getAlign())
1091 || (style.align != par.getAlign()
1092 && tclass.isDefaultLayout(next_layout))) {
1098 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1099 << &par << " next " << nextpar);
1105 // LaTeX all paragraphs
1106 void latexParagraphs(Buffer const & buf,
1109 OutputParams const & runparams,
1110 string const & everypar)
1112 LASSERT(runparams.par_begin <= runparams.par_end,
1113 { os << "% LaTeX Output Error\n"; return; } );
1115 BufferParams const & bparams = buf.params();
1117 bool const maintext = text.isMainText();
1118 bool const is_child = buf.masterBuffer() != &buf;
1120 // Open a CJK environment at the beginning of the main buffer
1121 // if the document's language is a CJK language
1122 // (but not in child documents)
1123 OutputState * state = getOutputState();
1124 if (maintext && !is_child
1125 && bparams.encoding().package() == Encoding::CJK) {
1126 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1127 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1128 state->open_encoding_ = CJK;
1130 // if "auto begin" is switched off, explicitly switch the
1131 // language on at start
1132 string const mainlang = runparams.use_polyglossia
1133 ? getPolyglossiaEnvName(bparams.language)
1134 : bparams.language->babel();
1135 string const lang_begin_command = runparams.use_polyglossia ?
1136 "\\begin{$$lang}" : lyxrc.language_command_begin;
1138 if (maintext && !lyxrc.language_auto_begin &&
1139 !mainlang.empty()) {
1141 os << from_utf8(subst(lang_begin_command,
1144 if (runparams.use_polyglossia
1145 && !bparams.language->polyglossiaOpts().empty())
1147 << from_ascii(bparams.language->polyglossiaOpts())
1152 ParagraphList const & paragraphs = text.paragraphs();
1154 if (runparams.par_begin == runparams.par_end) {
1155 // The full doc will be exported but it is easier to just rely on
1156 // runparams range parameters that will be passed TeXEnvironment.
1157 runparams.par_begin = 0;
1158 runparams.par_end = paragraphs.size();
1161 pit_type pit = runparams.par_begin;
1162 // lastpit is for the language check after the loop.
1163 pit_type lastpit = pit;
1164 // variables used in the loop:
1165 bool was_title = false;
1166 bool already_title = false;
1167 DocumentClass const & tclass = bparams.documentClass();
1169 for (; pit < runparams.par_end; ++pit) {
1171 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1173 // FIXME This check should not be needed. We should
1174 // perhaps issue an error if it is.
1175 Layout const & layout = text.inset().forcePlainLayout() ?
1176 tclass.plainLayout() : par->layout();
1178 if (layout.intitle) {
1179 if (already_title) {
1180 LYXERR0("Error in latexParagraphs: You"
1181 " should not mix title layouts"
1182 " with normal ones.");
1183 } else if (!was_title) {
1185 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1187 << from_ascii(tclass.titlename())
1191 } else if (was_title && !already_title) {
1192 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1193 os << "\\end{" << from_ascii(tclass.titlename())
1197 os << "\\" << from_ascii(tclass.titlename())
1200 already_title = true;
1205 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1206 // This is a standard top level paragraph, TeX it and continue.
1207 TeXOnePar(buf, text, pit, os, runparams, everypar);
1211 TeXEnvironmentData const data =
1212 prepareEnvironment(buf, text, par, os, runparams);
1213 // pit can be changed in TeXEnvironment.
1214 TeXEnvironment(buf, text, runparams, pit, os);
1215 finishEnvironment(os, runparams, data);
1218 if (pit == runparams.par_end) {
1219 // Make sure that the last paragraph is
1220 // correctly terminated (because TeXOnePar does
1221 // not add a \n in this case)
1225 // It might be that we only have a title in this document
1226 if (was_title && !already_title) {
1227 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1228 os << "\\end{" << from_ascii(tclass.titlename())
1231 os << "\\" << from_ascii(tclass.titlename())
1236 // if "auto end" is switched off, explicitly close the language at the end
1237 // but only if the last par is in a babel language
1238 string const lang_end_command = runparams.use_polyglossia ?
1239 "\\end{$$lang}" : lyxrc.language_command_end;
1240 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1241 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1242 os << from_utf8(subst(lang_end_command,
1248 // If the last paragraph is an environment, we'll have to close
1249 // CJK at the very end to do proper nesting.
1250 if (maintext && !is_child && state->open_encoding_ == CJK) {
1251 os << "\\end{CJK}\n";
1252 state->open_encoding_ = none;
1255 // reset inherited encoding
1256 if (state->cjk_inherited_ > 0) {
1257 state->cjk_inherited_ -= 1;
1258 if (state->cjk_inherited_ == 0)
1259 state->open_encoding_ = CJK;
1264 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1265 OutputParams const & runparams, Encoding const & newEnc,
1268 Encoding const & oldEnc = *runparams.encoding;
1269 bool moving_arg = runparams.moving_arg;
1270 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1271 bool const from_to_cjk =
1272 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1273 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1274 if (!force && !from_to_cjk
1275 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1276 return make_pair(false, 0);
1278 // Do nothing if the encoding is unchanged.
1279 if (oldEnc.name() == newEnc.name())
1280 return make_pair(false, 0);
1282 // FIXME We ignore encoding switches from/to encodings that do
1283 // neither support the inputenc package nor the CJK package here.
1284 // This does of course only work in special cases (e.g. switch from
1285 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1286 // but it is the best we can do
1287 if (oldEnc.package() == Encoding::none
1288 || newEnc.package() == Encoding::none)
1289 return make_pair(false, 0);
1291 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1292 << oldEnc.name() << " to " << newEnc.name());
1293 os << setEncoding(newEnc.iconvName());
1294 if (bparams.inputenc == "default")
1295 return make_pair(true, 0);
1297 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1298 OutputState * state = getOutputState();
1299 switch (newEnc.package()) {
1300 case Encoding::none:
1301 case Encoding::japanese:
1302 // shouldn't ever reach here, see above
1303 return make_pair(true, 0);
1304 case Encoding::inputenc: {
1305 int count = inputenc_arg.length();
1306 if (oldEnc.package() == Encoding::CJK &&
1307 state->open_encoding_ == CJK) {
1309 state->open_encoding_ = none;
1312 else if (oldEnc.package() == Encoding::inputenc &&
1313 state->open_encoding_ == inputenc) {
1315 state->open_encoding_ = none;
1318 if (runparams.local_font != 0
1319 && oldEnc.package() == Encoding::CJK) {
1320 // within insets, \inputenc switches need
1321 // to be embraced within \bgroup...\egroup;
1325 state->open_encoding_ = inputenc;
1327 // with the japanese option, inputenc is omitted.
1328 if (runparams.use_japanese)
1329 return make_pair(true, count);
1330 os << "\\inputencoding{" << inputenc_arg << '}';
1331 return make_pair(true, count + 16);
1333 case Encoding::CJK: {
1334 int count = inputenc_arg.length();
1335 if (oldEnc.package() == Encoding::CJK &&
1336 state->open_encoding_ == CJK) {
1340 if (oldEnc.package() == Encoding::inputenc &&
1341 state->open_encoding_ == inputenc) {
1345 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1346 << from_ascii(bparams.fonts_cjk) << "}";
1347 state->open_encoding_ = CJK;
1348 return make_pair(true, count + 15);
1351 // Dead code to avoid a warning:
1352 return make_pair(true, 0);