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 // Is this really needed ? (Dekel)
853 // We do not need to use to change the font for the last paragraph
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()
866 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
867 } else if (is_command) {
869 if (!style.postcommandargs().empty())
870 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
871 if (runparams.encoding != prev_encoding) {
872 runparams.encoding = prev_encoding;
873 if (!runparams.isFullUnicode())
874 os << setEncoding(prev_encoding->iconvName());
878 bool pending_newline = false;
879 bool unskip_newline = false;
880 switch (style.latextype) {
881 case LATEX_ITEM_ENVIRONMENT:
882 case LATEX_LIST_ENVIRONMENT:
883 if (nextpar && par.params().depth() < nextpar->params().depth())
884 pending_newline = true;
886 case LATEX_ENVIRONMENT: {
887 // if its the last paragraph of the current environment
888 // skip it otherwise fall through
890 && (nextpar->layout() != par.layout()
891 || nextpar->params().depth() != par.params().depth()))
895 // fall through possible
897 // we don't need it for the last paragraph!!!
899 pending_newline = true;
902 if (par.allowParagraphCustomization()) {
903 if (!par.params().spacing().isDefault()
904 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
908 string const endtag =
909 par.params().spacing().writeEnvirEnd(useSetSpace);
910 if (prefixIs(endtag, "\\end{"))
913 os << from_ascii(endtag);
914 pending_newline = true;
918 // Closing the language is needed for the last paragraph; it is also
919 // needed if we're within an \L or \R that we may have opened above (not
920 // necessarily in this paragraph) and are about to close.
921 bool closing_rtl_ltr_environment = !use_polyglossia
923 && (par_language->lang() != "arabic_arabtex"
924 && outer_language->lang() != "arabic_arabtex")
925 // have we opened an \L or \R environment?
926 && runparams.local_font != 0
927 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
928 // are we about to close the language?
929 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
930 || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
932 if (closing_rtl_ltr_environment
933 || (runparams.isLastPar
934 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
935 || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
936 // Since \selectlanguage write the language to the aux file,
937 // we need to reset the language at the end of footnote or
943 // when the paragraph uses CJK, the language has to be closed earlier
944 if (font.language()->encoding()->package() != Encoding::CJK) {
945 if (lang_end_command.empty()) {
946 // If this is a child, we should restore the
947 // master language after the last paragraph.
948 Language const * const current_language =
949 (runparams.isLastPar && runparams.master_language)
950 ? runparams.master_language
952 string const current_lang = use_polyglossia
953 ? getPolyglossiaEnvName(current_language)
954 : current_language->babel();
955 if (!current_lang.empty()) {
956 os << from_ascii(subst(
960 pending_newline = !localswitch;
961 unskip_newline = !localswitch;
963 } else if (!par_lang.empty()) {
964 os << from_ascii(subst(
968 pending_newline = !localswitch;
969 unskip_newline = !localswitch;
973 if (closing_rtl_ltr_environment)
976 bool const last_was_separator =
977 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
979 if (pending_newline) {
981 // prevent unwanted whitespace
983 if (!os.afterParbreak() && !last_was_separator)
987 // if this is a CJK-paragraph and the next isn't, close CJK
988 // also if the next paragraph is a multilingual environment (because of nesting)
990 && state->open_encoding_ == CJK
991 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
992 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
993 // inbetween environments, CJK has to be closed later (nesting!)
994 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
995 os << "\\end{CJK}\n";
996 state->open_encoding_ = none;
999 // If this is the last paragraph, close the CJK environment
1000 // if necessary. If it's an environment, we'll have to \end that first.
1001 if (runparams.isLastPar && !style.isEnvironment()) {
1002 switch (state->open_encoding_) {
1004 // do nothing at the end of child documents
1005 if (maintext && buf.masterBuffer() != &buf)
1009 os << "\n\\end{CJK}\n";
1013 state->open_encoding_ = none;
1018 state->open_encoding_ = none;
1028 // If this is the last paragraph, and a local_font was set upon entering
1029 // the inset, and we're using "auto" or "default" encoding, the encoding
1030 // should be set back to that local_font's encoding.
1031 // However, do not change the encoding when a fully unicode aware backend
1032 // such as XeTeX is used.
1033 if (runparams.isLastPar && runparams_in.local_font != 0
1034 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1035 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1036 && (!runparams.isFullUnicode())) {
1037 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1038 os << setEncoding(runparams_in.encoding->iconvName());
1040 // Otherwise, the current encoding should be set for the next paragraph.
1042 runparams_in.encoding = runparams.encoding;
1045 // we don't need a newline for the last paragraph!!!
1046 // Note from JMarc: we will re-add a \n explicitly in
1047 // TeXEnvironment, because it is needed in this case
1048 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1049 // Make sure to start a new line
1051 Layout const & next_layout = nextpar->layout();
1052 // A newline '\n' is always output before a command,
1053 // so avoid doubling it.
1054 if (!next_layout.isCommand()) {
1055 // Here we now try to avoid spurious empty lines by
1056 // outputting a paragraph break only if: (case 1) the
1057 // paragraph style allows parbreaks and no \begin, \end
1058 // or \item tags are going to follow (i.e., if the next
1059 // isn't the first or the current isn't the last
1060 // paragraph of an environment or itemize) and the
1061 // depth and alignment of the following paragraph is
1062 // unchanged, or (case 2) the following is a
1063 // non-environment paragraph whose depth is increased
1064 // but whose alignment is unchanged, or (case 3) the
1065 // paragraph is not an environment and the next one is a
1066 // non-itemize-like env at lower depth, or (case 4) the
1067 // paragraph is a command not followed by an environment
1068 // and the alignment of the current and next paragraph
1069 // is unchanged, or (case 5) the current alignment is
1070 // changed and a standard paragraph follows.
1071 DocumentClass const & tclass = bparams.documentClass();
1072 if ((style == next_layout
1073 && !style.parbreak_is_newline
1074 && style.latextype != LATEX_ITEM_ENVIRONMENT
1075 && style.latextype != LATEX_LIST_ENVIRONMENT
1076 && style.align == par.getAlign()
1077 && nextpar->getDepth() == par.getDepth()
1078 && nextpar->getAlign() == par.getAlign())
1079 || (!next_layout.isEnvironment()
1080 && nextpar->getDepth() > par.getDepth()
1081 && nextpar->getAlign() == par.getAlign())
1082 || (!style.isEnvironment()
1083 && next_layout.latextype == LATEX_ENVIRONMENT
1084 && nextpar->getDepth() < par.getDepth())
1085 || (style.isCommand()
1086 && !next_layout.isEnvironment()
1087 && style.align == par.getAlign()
1088 && next_layout.align == nextpar->getAlign())
1089 || (style.align != par.getAlign()
1090 && tclass.isDefaultLayout(next_layout))) {
1096 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1097 << &par << " next " << nextpar);
1103 // LaTeX all paragraphs
1104 void latexParagraphs(Buffer const & buf,
1107 OutputParams const & runparams,
1108 string const & everypar)
1110 LASSERT(runparams.par_begin <= runparams.par_end,
1111 { os << "% LaTeX Output Error\n"; return; } );
1113 BufferParams const & bparams = buf.params();
1115 bool const maintext = text.isMainText();
1116 bool const is_child = buf.masterBuffer() != &buf;
1118 // Open a CJK environment at the beginning of the main buffer
1119 // if the document's language is a CJK language
1120 // (but not in child documents)
1121 OutputState * state = getOutputState();
1122 if (maintext && !is_child
1123 && bparams.encoding().package() == Encoding::CJK) {
1124 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1125 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1126 state->open_encoding_ = CJK;
1128 // if "auto begin" is switched off, explicitly switch the
1129 // language on at start
1130 string const mainlang = runparams.use_polyglossia
1131 ? getPolyglossiaEnvName(bparams.language)
1132 : bparams.language->babel();
1133 string const lang_begin_command = runparams.use_polyglossia ?
1134 "\\begin{$$lang}" : lyxrc.language_command_begin;
1136 if (maintext && !lyxrc.language_auto_begin &&
1137 !mainlang.empty()) {
1139 os << from_utf8(subst(lang_begin_command,
1142 if (runparams.use_polyglossia
1143 && !bparams.language->polyglossiaOpts().empty())
1145 << from_ascii(bparams.language->polyglossiaOpts())
1150 ParagraphList const & paragraphs = text.paragraphs();
1152 if (runparams.par_begin == runparams.par_end) {
1153 // The full doc will be exported but it is easier to just rely on
1154 // runparams range parameters that will be passed TeXEnvironment.
1155 runparams.par_begin = 0;
1156 runparams.par_end = paragraphs.size();
1159 pit_type pit = runparams.par_begin;
1160 // lastpit is for the language check after the loop.
1161 pit_type lastpit = pit;
1162 // variables used in the loop:
1163 bool was_title = false;
1164 bool already_title = false;
1165 DocumentClass const & tclass = bparams.documentClass();
1167 for (; pit < runparams.par_end; ++pit) {
1169 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1171 // FIXME This check should not be needed. We should
1172 // perhaps issue an error if it is.
1173 Layout const & layout = text.inset().forcePlainLayout() ?
1174 tclass.plainLayout() : par->layout();
1176 if (layout.intitle) {
1177 if (already_title) {
1178 LYXERR0("Error in latexParagraphs: You"
1179 " should not mix title layouts"
1180 " with normal ones.");
1181 } else if (!was_title) {
1183 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1185 << from_ascii(tclass.titlename())
1189 } else if (was_title && !already_title) {
1190 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1191 os << "\\end{" << from_ascii(tclass.titlename())
1195 os << "\\" << from_ascii(tclass.titlename())
1198 already_title = true;
1203 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1204 // This is a standard top level paragraph, TeX it and continue.
1205 TeXOnePar(buf, text, pit, os, runparams, everypar);
1209 TeXEnvironmentData const data =
1210 prepareEnvironment(buf, text, par, os, runparams);
1211 // pit can be changed in TeXEnvironment.
1212 TeXEnvironment(buf, text, runparams, pit, os);
1213 finishEnvironment(os, runparams, data);
1216 if (pit == runparams.par_end) {
1217 // Make sure that the last paragraph is
1218 // correctly terminated (because TeXOnePar does
1219 // not add a \n in this case)
1223 // It might be that we only have a title in this document
1224 if (was_title && !already_title) {
1225 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1226 os << "\\end{" << from_ascii(tclass.titlename())
1229 os << "\\" << from_ascii(tclass.titlename())
1234 // if "auto end" is switched off, explicitly close the language at the end
1235 // but only if the last par is in a babel language
1236 string const lang_end_command = runparams.use_polyglossia ?
1237 "\\end{$$lang}" : lyxrc.language_command_end;
1238 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1239 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1240 os << from_utf8(subst(lang_end_command,
1246 // If the last paragraph is an environment, we'll have to close
1247 // CJK at the very end to do proper nesting.
1248 if (maintext && !is_child && state->open_encoding_ == CJK) {
1249 os << "\\end{CJK}\n";
1250 state->open_encoding_ = none;
1253 // reset inherited encoding
1254 if (state->cjk_inherited_ > 0) {
1255 state->cjk_inherited_ -= 1;
1256 if (state->cjk_inherited_ == 0)
1257 state->open_encoding_ = CJK;
1262 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1263 OutputParams const & runparams, Encoding const & newEnc,
1266 Encoding const & oldEnc = *runparams.encoding;
1267 bool moving_arg = runparams.moving_arg;
1268 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1269 bool const from_to_cjk =
1270 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1271 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1272 if (!force && !from_to_cjk
1273 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1274 return make_pair(false, 0);
1276 // Do nothing if the encoding is unchanged.
1277 if (oldEnc.name() == newEnc.name())
1278 return make_pair(false, 0);
1280 // FIXME We ignore encoding switches from/to encodings that do
1281 // neither support the inputenc package nor the CJK package here.
1282 // This does of course only work in special cases (e.g. switch from
1283 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1284 // but it is the best we can do
1285 if (oldEnc.package() == Encoding::none
1286 || newEnc.package() == Encoding::none)
1287 return make_pair(false, 0);
1289 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1290 << oldEnc.name() << " to " << newEnc.name());
1291 os << setEncoding(newEnc.iconvName());
1292 if (bparams.inputenc == "default")
1293 return make_pair(true, 0);
1295 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1296 OutputState * state = getOutputState();
1297 switch (newEnc.package()) {
1298 case Encoding::none:
1299 case Encoding::japanese:
1300 // shouldn't ever reach here, see above
1301 return make_pair(true, 0);
1302 case Encoding::inputenc: {
1303 int count = inputenc_arg.length();
1304 if (oldEnc.package() == Encoding::CJK &&
1305 state->open_encoding_ == CJK) {
1307 state->open_encoding_ = none;
1310 else if (oldEnc.package() == Encoding::inputenc &&
1311 state->open_encoding_ == inputenc) {
1313 state->open_encoding_ = none;
1316 if (runparams.local_font != 0
1317 && oldEnc.package() == Encoding::CJK) {
1318 // within insets, \inputenc switches need
1319 // to be embraced within \bgroup...\egroup;
1323 state->open_encoding_ = inputenc;
1325 // with the japanese option, inputenc is omitted.
1326 if (runparams.use_japanese)
1327 return make_pair(true, count);
1328 os << "\\inputencoding{" << inputenc_arg << '}';
1329 return make_pair(true, count + 16);
1331 case Encoding::CJK: {
1332 int count = inputenc_arg.length();
1333 if (oldEnc.package() == Encoding::CJK &&
1334 state->open_encoding_ == CJK) {
1338 if (oldEnc.package() == Encoding::inputenc &&
1339 state->open_encoding_ == inputenc) {
1343 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1344 << from_ascii(bparams.fonts_cjk) << "}";
1345 state->open_encoding_ = CJK;
1346 return make_pair(true, count + 15);
1349 // Dead code to avoid a warning:
1350 return make_pair(true, 0);