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"
39 #include <boost/next_prior.hpp>
43 using namespace lyx::support;
57 // There could easily be a conflict here, with the export process
58 // setting this one way, and a View>Source process (possbily for
59 // another Buffer) resetting it.
60 static int open_encoding_ = none;
61 static int cjk_inherited_ = 0;
62 Language const * prev_env_language_ = 0;
65 string const getPolyglossiaEnvName(Language const * lang)
67 string result = lang->polyglossia();
68 if (result == "arabic")
69 // exceptional spelling; see polyglossia docs.
75 struct TeXEnvironmentData
79 Language const * par_language;
80 Encoding const * prev_encoding;
85 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
87 ParagraphList::const_iterator pit,
89 OutputParams const & runparams)
91 TeXEnvironmentData data;
93 BufferParams const & bparams = buf.params();
95 // FIXME This test should not be necessary.
96 // We should perhaps issue an error if it is.
97 Layout const & style = text.inset().forcePlainLayout() ?
98 bparams.documentClass().plainLayout() : pit->layout();
100 ParagraphList const & paragraphs = text.paragraphs();
101 ParagraphList::const_iterator const priorpit =
102 pit == paragraphs.begin() ? pit : boost::prior(pit);
104 bool const use_prev_env_language = prev_env_language_ != 0
105 && priorpit->layout().isEnvironment()
106 && (priorpit->getDepth() > pit->getDepth()
107 || (priorpit->getDepth() == pit->getDepth()
108 && priorpit->layout() != pit->layout()));
110 data.prev_encoding = runparams.encoding;
111 data.par_language = pit->getParLanguage(bparams);
112 Language const * const doc_language = bparams.language;
113 Language const * const prev_par_language =
114 (pit != paragraphs.begin())
115 ? (use_prev_env_language ? prev_env_language_
116 : priorpit->getParLanguage(bparams))
119 bool const use_polyglossia = runparams.use_polyglossia;
120 string const par_lang = use_polyglossia ?
121 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
122 string const prev_par_lang = use_polyglossia ?
123 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
124 string const doc_lang = use_polyglossia ?
125 getPolyglossiaEnvName(doc_language) : doc_language->babel();
126 string const lang_begin_command = use_polyglossia ?
127 "\\begin{$$lang}" : lyxrc.language_command_begin;
128 string const lang_end_command = use_polyglossia ?
129 "\\end{$$lang}" : lyxrc.language_command_end;
131 if (par_lang != prev_par_lang) {
132 if (!lang_end_command.empty() &&
133 prev_par_lang != doc_lang &&
134 !prev_par_lang.empty()) {
135 os << from_ascii(subst(
139 // the '%' is necessary to prevent unwanted whitespace
143 if ((lang_end_command.empty() ||
144 par_lang != doc_lang) &&
146 os << from_ascii(subst(
151 && !data.par_language->polyglossiaOpts().empty())
153 << from_ascii(data.par_language->polyglossiaOpts())
155 // the '%' is necessary to prevent unwanted whitespace
160 data.leftindent_open = false;
161 if (!pit->params().leftIndent().zero()) {
162 os << "\\begin{LyXParagraphLeftIndent}{"
163 << from_ascii(pit->params().leftIndent().asLatexString())
165 data.leftindent_open = true;
168 if (style.isEnvironment()) {
169 os << "\\begin{" << from_ascii(style.latexname()) << '}';
170 if (!style.latexargs().empty()) {
171 OutputParams rp = runparams;
172 rp.local_font = &pit->getFirstFontSettings(bparams);
173 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
175 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
177 << pit->params().labelWidthString()
179 } else if (style.labeltype == LABEL_BIBLIO) {
180 if (pit->params().labelWidthString().empty())
181 os << '{' << bibitemWidest(buf, runparams) << "}\n";
184 << pit->params().labelWidthString()
187 os << from_ascii(style.latexparam()) << '\n';
191 // in multilingual environments, the CJK tags have to be nested properly
192 data.cjk_nested = false;
193 if (data.par_language->encoding()->package() == Encoding::CJK &&
194 open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
195 if (prev_par_language->encoding()->package() == Encoding::CJK)
196 os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
197 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
198 open_encoding_ = CJK;
199 data.cjk_nested = true;
205 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
206 TeXEnvironmentData const & data)
208 if (open_encoding_ == CJK && data.cjk_nested) {
209 // We need to close the encoding even if it does not change
210 // to do correct environment nesting
211 os << "\\end{CJK}\n";
212 open_encoding_ = none;
215 if (data.style->isEnvironment()) {
217 << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
218 prev_env_language_ = data.par_language;
219 if (runparams.encoding != data.prev_encoding) {
220 runparams.encoding = data.prev_encoding;
221 if (!runparams.isFullUnicode())
222 os << setEncoding(data.prev_encoding->iconvName());
226 if (data.leftindent_open) {
227 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
228 prev_env_language_ = data.par_language;
229 if (runparams.encoding != data.prev_encoding) {
230 runparams.encoding = data.prev_encoding;
231 if (!runparams.isFullUnicode())
232 os << setEncoding(data.prev_encoding->iconvName());
236 // Check whether we should output a blank line after the environment
237 if (!data.style->nextnoindent)
242 void TeXEnvironment(Buffer const & buf, Text const & text,
243 OutputParams const & runparams,
244 pit_type & pit, otexstream & os)
246 ParagraphList const & paragraphs = text.paragraphs();
247 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
248 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
250 Layout const & current_layout = par->layout();
251 depth_type const current_depth = par->params().depth();
252 Length const & current_left_indent = par->params().leftIndent();
254 // This is for debugging purpose at the end.
255 pit_type const par_begin = pit;
256 for (; pit < runparams.par_end; ++pit) {
257 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
259 // check first if this is an higher depth paragraph.
260 bool go_out = (par->params().depth() < current_depth);
261 if (par->params().depth() == current_depth) {
262 // This environment is finished.
263 go_out |= (par->layout() != current_layout);
264 go_out |= (par->params().leftIndent() != current_left_indent);
267 // nothing to do here, restore pit and go out.
272 if (par->layout() == current_layout
273 && par->params().depth() == current_depth
274 && par->params().leftIndent() == current_left_indent) {
275 // We are still in the same environment so TeXOnePar and continue;
276 TeXOnePar(buf, text, pit, os, runparams);
280 // We are now in a deeper environment.
281 // Either par->layout() != current_layout
282 // Or par->params().depth() > current_depth
283 // Or par->params().leftIndent() != current_left_indent)
285 // FIXME This test should not be necessary.
286 // We should perhaps issue an error if it is.
287 bool const force_plain_layout = text.inset().forcePlainLayout();
288 Layout const & style = force_plain_layout
289 ? buf.params().documentClass().plainLayout()
292 if (!style.isEnvironment()) {
293 // This is a standard paragraph, no need to call TeXEnvironment.
294 TeXOnePar(buf, text, pit, os, runparams);
298 // This is a new environment.
299 TeXEnvironmentData const data =
300 prepareEnvironment(buf, text, par, os, runparams);
301 // Recursive call to TeXEnvironment!
302 TeXEnvironment(buf, text, runparams, pit, os);
303 finishEnvironment(os, runparams, data);
306 if (pit != runparams.par_end)
307 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
311 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
312 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
314 unsigned int const argnr = latexargs.size();
318 // Default and preset args are always output, so if they require
319 // other arguments, consider this.
320 Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
321 Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
322 for (; lit != lend; ++lit) {
323 Layout::latexarg arg = (*lit).second;
324 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
325 vector<string> req = getVectorFromString(arg.requires);
326 required.insert(required.end(), req.begin(), req.end());
330 for (unsigned int i = 1; i <= argnr; ++i) {
331 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
332 bool inserted = false;
333 if (lit != ilist.end()) {
334 InsetArgument const * ins = (*lit).second;
336 Layout::LaTeXArgMap::const_iterator const lait =
337 latexargs.find(ins->name());
338 if (lait != latexargs.end()) {
339 Layout::latexarg arg = (*lait).second;
340 docstring ldelim = arg.mandatory ?
341 from_ascii("{") : from_ascii("[");
342 docstring rdelim = arg.mandatory ?
343 from_ascii("}") : from_ascii("]");
344 if (!arg.ldelim.empty())
346 if (!arg.rdelim.empty())
348 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
354 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
355 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
356 for (; lait != laend; ++lait) {
357 string const name = prefix + convert<string>(i);
358 if ((*lait).first == name) {
359 Layout::latexarg arg = (*lait).second;
360 docstring preset = arg.presetarg;
361 if (!arg.defaultarg.empty()) {
364 preset += arg.defaultarg;
367 docstring ldelim = arg.ldelim.empty() ?
368 from_ascii("{") : arg.ldelim;
369 docstring rdelim = arg.rdelim.empty() ?
370 from_ascii("}") : arg.rdelim;
371 os << ldelim << preset << rdelim;
372 } else if (!preset.empty()) {
373 docstring ldelim = arg.ldelim.empty() ?
374 from_ascii("[") : arg.ldelim;
375 docstring rdelim = arg.rdelim.empty() ?
376 from_ascii("]") : arg.rdelim;
377 os << ldelim << preset << rdelim;
378 } else if (find(required.begin(), required.end(),
379 (*lait).first) != required.end()) {
380 docstring ldelim = arg.ldelim.empty() ?
381 from_ascii("[") : arg.ldelim;
382 docstring rdelim = arg.rdelim.empty() ?
383 from_ascii("]") : arg.rdelim;
384 os << ldelim << rdelim;
397 void latexArgInsets(Paragraph const & par, otexstream & os,
398 OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
400 map<int, InsetArgument const *> ilist;
401 vector<string> required;
403 InsetList::const_iterator it = par.insetList().begin();
404 InsetList::const_iterator end = par.insetList().end();
405 for (; it != end; ++it) {
406 if (it->inset->lyxCode() == ARG_CODE) {
407 InsetArgument const * ins =
408 static_cast<InsetArgument const *>(it->inset);
409 if (ins->name().empty())
410 LYXERR0("Error: Unnamed argument inset!");
412 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
413 unsigned int const nr = convert<unsigned int>(name);
415 Layout::LaTeXArgMap::const_iterator const lit =
416 latexargs.find(ins->name());
417 if (lit != latexargs.end()) {
418 Layout::latexarg const & arg = (*lit).second;
419 if (!arg.requires.empty()) {
420 vector<string> req = getVectorFromString(arg.requires);
421 required.insert(required.end(), req.begin(), req.end());
427 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
431 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
432 otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
433 string const & prefix)
435 map<int, InsetArgument const *> ilist;
436 vector<string> required;
438 depth_type const current_depth = pit->params().depth();
439 Layout const current_layout = pit->layout();
441 // get the first paragraph in sequence with this layout and depth
444 if (boost::prior(pit, offset) == pars.begin())
446 ParagraphList::const_iterator priorpit = boost::prior(pit, offset + 1);
447 if (priorpit->layout() == current_layout
448 && priorpit->params().depth() == current_depth)
454 ParagraphList::const_iterator spit = boost::prior(pit, offset);
456 for (; spit != pars.end(); ++spit) {
457 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
459 if (spit->params().depth() > current_depth)
461 InsetList::const_iterator it = spit->insetList().begin();
462 InsetList::const_iterator end = spit->insetList().end();
463 for (; it != end; ++it) {
464 if (it->inset->lyxCode() == ARG_CODE) {
465 InsetArgument const * ins =
466 static_cast<InsetArgument const *>(it->inset);
467 if (ins->name().empty())
468 LYXERR0("Error: Unnamed argument inset!");
470 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
471 unsigned int const nr = convert<unsigned int>(name);
472 if (ilist.find(nr) == ilist.end())
474 Layout::LaTeXArgMap::const_iterator const lit =
475 latexargs.find(ins->name());
476 if (lit != latexargs.end()) {
477 Layout::latexarg const & arg = (*lit).second;
478 if (!arg.requires.empty()) {
479 vector<string> req = getVectorFromString(arg.requires);
480 required.insert(required.end(), req.begin(), req.end());
487 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
492 // output the proper paragraph start according to latextype.
493 void parStartCommand(Paragraph const & par, otexstream & os,
494 OutputParams const & runparams, Layout const & style)
496 switch (style.latextype) {
498 os << '\\' << from_ascii(style.latexname());
501 if (!style.latexargs().empty())
502 latexArgInsets(par, os, runparams, style.latexargs());
503 os << from_ascii(style.latexparam());
505 case LATEX_ITEM_ENVIRONMENT:
506 case LATEX_LIST_ENVIRONMENT:
507 os << "\\" + style.itemcommand();
509 if (!style.itemargs().empty())
510 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
513 case LATEX_BIB_ENVIRONMENT:
514 // ignore this, the inset will write itself
523 // FIXME: this should be anonymous
524 void TeXOnePar(Buffer const & buf,
528 OutputParams const & runparams_in,
529 string const & everypar,
530 int start_pos, int end_pos)
532 BufferParams const & bparams = runparams_in.is_child
533 ? buf.masterParams() : buf.params();
534 ParagraphList const & paragraphs = text.paragraphs();
535 Paragraph const & par = paragraphs.at(pit);
536 // FIXME This check should not really be needed.
537 // Perhaps we should issue an error if it is.
538 Layout const style = text.inset().forcePlainLayout() ?
539 bparams.documentClass().plainLayout() : par.layout();
541 if (style.inpreamble)
544 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
547 OutputParams runparams = runparams_in;
548 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
549 // We reinitialze par begin and end to be on the safe side
550 // with embedded inset as we don't know if they set those
552 runparams.par_begin = 0;
553 runparams.par_end = 0;
555 bool const maintext = text.isMainText();
556 // we are at the beginning of an inset and CJK is already open;
557 // we count inheritation levels to get the inset nesting right.
558 if (pit == 0 && !maintext
559 && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
561 open_encoding_ = none;
564 if (text.inset().isPassThru()) {
565 Font const outerfont = text.outerFont(pit);
567 // No newline before first paragraph in this lyxtext
570 if (!text.inset().getLayout().parbreakIsNewline())
574 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
578 Paragraph const * nextpar = runparams.isLastPar
579 ? 0 : ¶graphs.at(pit + 1);
581 if (style.pass_thru) {
582 Font const outerfont = text.outerFont(pit);
583 parStartCommand(par, os, runparams, style);
585 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
587 // I did not create a parEndCommand for this minuscule
588 // task because in the other user of parStartCommand
589 // the code is different (JMarc)
590 if (style.isCommand())
594 if (!style.parbreak_is_newline) {
596 } else if (nextpar && !style.isEnvironment()) {
597 Layout const nextstyle = text.inset().forcePlainLayout()
598 ? bparams.documentClass().plainLayout()
600 if (nextstyle.name() != style.name())
607 // This paragraph's language
608 Language const * const par_language = par.getParLanguage(bparams);
609 // The document's language
610 Language const * const doc_language = bparams.language;
611 // The language that was in effect when the environment this paragraph is
612 // inside of was opened
613 Language const * const outer_language =
614 (runparams.local_font != 0) ?
615 runparams.local_font->language() : doc_language;
617 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
619 // The previous language that was in effect is the language of the
620 // previous paragraph, unless the previous paragraph is inside an
621 // environment with nesting depth greater than (or equal to, but with
622 // a different layout) the current one. If there is no previous
623 // paragraph, the previous language is the outer language.
624 bool const use_prev_env_language = prev_env_language_ != 0
626 && priorpar->layout().isEnvironment()
627 && (priorpar->getDepth() > par.getDepth()
628 || (priorpar->getDepth() == par.getDepth()
629 && priorpar->layout() != par.layout()));
630 Language const * const prev_language =
632 ? (use_prev_env_language ? prev_env_language_
633 : priorpar->getParLanguage(bparams))
637 bool const use_polyglossia = runparams.use_polyglossia;
638 string const par_lang = use_polyglossia ?
639 getPolyglossiaEnvName(par_language): par_language->babel();
640 string const prev_lang = use_polyglossia ?
641 getPolyglossiaEnvName(prev_language) : prev_language->babel();
642 string const doc_lang = use_polyglossia ?
643 getPolyglossiaEnvName(doc_language) : doc_language->babel();
644 string const outer_lang = use_polyglossia ?
645 getPolyglossiaEnvName(outer_language) : outer_language->babel();
646 string lang_begin_command = use_polyglossia ?
647 "\\begin{$$lang}" : lyxrc.language_command_begin;
648 string lang_end_command = use_polyglossia ?
649 "\\end{$$lang}" : lyxrc.language_command_end;
650 // the '%' is necessary to prevent unwanted whitespace
651 string lang_command_termination = "%\n";
653 // In some insets (such as Arguments), we cannot use \selectlanguage
654 bool const localswitch = !use_polyglossia
655 && text.inset().getLayout().forcelocalfontswitch();
657 lang_begin_command = lyxrc.language_command_local;
658 lang_end_command = "}";
659 lang_command_termination.clear();
662 if (par_lang != prev_lang
663 // check if we already put language command in TeXEnvironment()
664 && !(style.isEnvironment()
665 && (pit == 0 || (priorpar->layout() != par.layout()
666 && priorpar->getDepth() <= par.getDepth())
667 || priorpar->getDepth() < par.getDepth())))
669 if (!lang_end_command.empty() &&
670 prev_lang != outer_lang &&
673 os << from_ascii(subst(lang_end_command,
676 << lang_command_termination;
679 // We need to open a new language if we couldn't close the previous
680 // one (because there's no language_command_end); and even if we closed
681 // the previous one, if the current language is different than the
682 // outer_language (which is currently in effect once the previous one
684 if ((lang_end_command.empty() || par_lang != outer_lang)
685 && !par_lang.empty()) {
686 // If we're inside an inset, and that inset is within an \L or \R
687 // (or equivalents), then within the inset, too, any opposite
688 // language paragraph should appear within an \L or \R (in addition
689 // to, outside of, the normal language switch commands).
690 // This behavior is not correct for ArabTeX, though.
693 && par_language->lang() != "arabic_arabtex"
694 && outer_language->lang() != "arabic_arabtex"
695 // are we in an inset?
696 && runparams.local_font != 0
697 // is the inset within an \L or \R?
699 // FIXME: currently, we don't check this; this means that
700 // we'll have unnnecessary \L and \R commands, but that
701 // doesn't seem to hurt (though latex will complain)
703 // is this paragraph in the opposite direction?
704 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
705 // FIXME: I don't have a working copy of the Arabi package, so
706 // I'm not sure if the farsi and arabic_arabi stuff is correct
708 if (par_language->lang() == "farsi")
710 else if (outer_language->lang() == "farsi")
712 else if (par_language->lang() == "arabic_arabi")
714 else if (outer_language->lang() == "arabic_arabi")
716 // remaining RTL languages currently is hebrew
717 else if (par_language->rightToLeft())
722 // With CJK, the CJK tag has to be closed first (see below)
723 if (runparams.encoding->package() != Encoding::CJK
724 && !par_lang.empty()) {
725 os << from_ascii(subst(
730 && !par_language->polyglossiaOpts().empty())
732 << from_ascii(par_language->polyglossiaOpts())
734 os << lang_command_termination;
739 // Switch file encoding if necessary; no need to do this for "default"
740 // encoding, since this only affects the position of the outputted
741 // \inputencoding command; the encoding switch will occur when necessary
742 if (bparams.inputenc == "auto"
743 && runparams.encoding->package() != Encoding::none) {
744 // Look ahead for future encoding changes.
745 // We try to output them at the beginning of the paragraph,
746 // since the \inputencoding command is not allowed e.g. in
747 // sections. For this reason we only set runparams.moving_arg
748 // after checking for the encoding change, otherwise the
749 // change would be always avoided by switchEncoding().
750 for (pos_type i = 0; i < par.size(); ++i) {
751 char_type const c = par.getChar(i);
752 Encoding const * const encoding =
753 par.getFontSettings(bparams, i).language()->encoding();
754 if (encoding->package() != Encoding::CJK
755 && runparams.encoding->package() == Encoding::inputenc
760 // All characters before c are in the ASCII range, and
761 // c is non-ASCII (but no inset), so change the
762 // encoding to that required by the language of c.
763 // With CJK, only add switch if we have CJK content at the beginning
765 if (i != 0 && encoding->package() == Encoding::CJK)
768 pair<bool, int> enc_switch = switchEncoding(os.os(),
769 bparams, runparams, *encoding);
770 // the following is necessary after a CJK environment in a multilingual
771 // context (nesting issue).
772 if (par_language->encoding()->package() == Encoding::CJK
773 && open_encoding_ != CJK && cjk_inherited_ == 0) {
774 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
775 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
776 open_encoding_ = CJK;
778 if (encoding->package() != Encoding::none && enc_switch.first) {
779 if (enc_switch.second > 0) {
780 // the '%' is necessary to prevent unwanted whitespace
783 // With CJK, the CJK tag had to be closed first (see above)
784 if (runparams.encoding->package() == Encoding::CJK
785 && !par_lang.empty()) {
786 os << from_ascii(subst(
790 << lang_command_termination;
792 runparams.encoding = encoding;
798 runparams.moving_arg |= style.needprotect;
799 Encoding const * const prev_encoding = runparams.encoding;
801 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
802 if (par.allowParagraphCustomization()) {
803 if (par.params().startOfAppendix()) {
804 os << "\n\\appendix\n";
807 if (!par.params().spacing().isDefault()
808 && (pit == 0 || !priorpar->hasSameLayout(par)))
810 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
814 if (style.isCommand()) {
819 parStartCommand(par, os, runparams, style);
820 Font const outerfont = text.outerFont(pit);
823 os << from_utf8(everypar);
824 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
826 // Make sure that \\par is done with the font of the last
827 // character if this has another size as the default.
828 // This is necessary because LaTeX (and LyX on the screen)
829 // calculates the space between the baselines according
830 // to this font. (Matthias)
832 // Is this really needed ? (Dekel)
833 // We do not need to use to change the font for the last paragraph
836 Font const font = par.empty()
837 ? par.getLayoutFont(bparams, outerfont)
838 : par.getFont(bparams, par.size() - 1, outerfont);
840 bool const is_command = style.isCommand();
842 if (style.resfont.size() != font.fontInfo().size()
846 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
847 } else if (is_command) {
849 if (!style.postcommandargs().empty())
850 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
851 if (runparams.encoding != prev_encoding) {
852 runparams.encoding = prev_encoding;
853 if (!runparams.isFullUnicode())
854 os << setEncoding(prev_encoding->iconvName());
858 bool pending_newline = false;
859 bool unskip_newline = false;
860 switch (style.latextype) {
861 case LATEX_ITEM_ENVIRONMENT:
862 case LATEX_LIST_ENVIRONMENT:
863 if (nextpar && par.params().depth() < nextpar->params().depth())
864 pending_newline = true;
866 case LATEX_ENVIRONMENT: {
867 // if its the last paragraph of the current environment
868 // skip it otherwise fall through
870 && (nextpar->layout() != par.layout()
871 || nextpar->params().depth() != par.params().depth()))
875 // fall through possible
877 // we don't need it for the last paragraph!!!
879 pending_newline = true;
882 if (par.allowParagraphCustomization()) {
883 if (!par.params().spacing().isDefault()
884 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
888 string const endtag =
889 par.params().spacing().writeEnvirEnd(useSetSpace);
890 if (prefixIs(endtag, "\\end{"))
893 os << from_ascii(endtag);
894 pending_newline = true;
898 // Closing the language is needed for the last paragraph; it is also
899 // needed if we're within an \L or \R that we may have opened above (not
900 // necessarily in this paragraph) and are about to close.
901 bool closing_rtl_ltr_environment = !use_polyglossia
903 && (par_language->lang() != "arabic_arabtex"
904 && outer_language->lang() != "arabic_arabtex")
905 // have we opened an \L or \R environment?
906 && runparams.local_font != 0
907 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
908 // are we about to close the language?
909 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
910 || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
912 if (closing_rtl_ltr_environment
913 || (runparams.isLastPar
914 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
915 || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
916 // Since \selectlanguage write the language to the aux file,
917 // we need to reset the language at the end of footnote or
923 // when the paragraph uses CJK, the language has to be closed earlier
924 if (font.language()->encoding()->package() != Encoding::CJK) {
925 if (lang_end_command.empty()) {
926 // If this is a child, we should restore the
927 // master language after the last paragraph.
928 Language const * const current_language =
929 (runparams.isLastPar && runparams.master_language)
930 ? runparams.master_language
932 string const current_lang = use_polyglossia
933 ? getPolyglossiaEnvName(current_language)
934 : current_language->babel();
935 if (!current_lang.empty()) {
936 os << from_ascii(subst(
940 pending_newline = !localswitch;
941 unskip_newline = !localswitch;
943 } else if (!par_lang.empty()) {
944 os << from_ascii(subst(
948 pending_newline = !localswitch;
949 unskip_newline = !localswitch;
953 if (closing_rtl_ltr_environment)
956 bool const last_was_separator =
957 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
959 if (pending_newline) {
961 // prevent unwanted whitespace
963 if (!os.afterParbreak() && !last_was_separator)
967 // if this is a CJK-paragraph and the next isn't, close CJK
968 // also if the next paragraph is a multilingual environment (because of nesting)
970 && open_encoding_ == CJK
971 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
972 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
973 // inbetween environments, CJK has to be closed later (nesting!)
974 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
975 os << "\\end{CJK}\n";
976 open_encoding_ = none;
979 // If this is the last paragraph, close the CJK environment
980 // if necessary. If it's an environment, we'll have to \end that first.
981 if (runparams.isLastPar && !style.isEnvironment()) {
982 switch (open_encoding_) {
984 // do nothing at the end of child documents
985 if (maintext && buf.masterBuffer() != &buf)
989 os << "\n\\end{CJK}\n";
993 open_encoding_ = none;
998 open_encoding_ = none;
1008 // If this is the last paragraph, and a local_font was set upon entering
1009 // the inset, and we're using "auto" or "default" encoding, the encoding
1010 // should be set back to that local_font's encoding.
1011 // However, do not change the encoding when a fully unicode aware backend
1012 // such as XeTeX is used.
1013 if (runparams.isLastPar && runparams_in.local_font != 0
1014 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1015 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1016 && (!runparams.isFullUnicode())) {
1017 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1018 os << setEncoding(runparams_in.encoding->iconvName());
1020 // Otherwise, the current encoding should be set for the next paragraph.
1022 runparams_in.encoding = runparams.encoding;
1025 // we don't need a newline for the last paragraph!!!
1026 // Note from JMarc: we will re-add a \n explicitly in
1027 // TeXEnvironment, because it is needed in this case
1028 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1029 // Make sure to start a new line
1031 Layout const & next_layout = nextpar->layout();
1032 // A newline '\n' is always output before a command,
1033 // so avoid doubling it.
1034 if (!next_layout.isCommand()) {
1035 // Here we now try to avoid spurious empty lines by
1036 // outputting a paragraph break only if: (case 1) the
1037 // paragraph style allows parbreaks and no \begin, \end
1038 // or \item tags are going to follow (i.e., if the next
1039 // isn't the first or the current isn't the last
1040 // paragraph of an environment or itemize) and the
1041 // depth and alignment of the following paragraph is
1042 // unchanged, or (case 2) the following is a
1043 // non-environment paragraph whose depth is increased
1044 // but whose alignment is unchanged, or (case 3) the
1045 // paragraph is not an environment and the next one is a
1046 // non-itemize-like env at lower depth, or (case 4) the
1047 // paragraph is a command not followed by an environment
1048 // and the alignment of the current and next paragraph
1049 // is unchanged, or (case 5) the current alignment is
1050 // changed and a standard paragraph follows.
1051 DocumentClass const & tclass = bparams.documentClass();
1052 if ((style == next_layout
1053 && !style.parbreak_is_newline
1054 && style.latextype != LATEX_ITEM_ENVIRONMENT
1055 && style.latextype != LATEX_LIST_ENVIRONMENT
1056 && style.align == par.getAlign()
1057 && nextpar->getDepth() == par.getDepth()
1058 && nextpar->getAlign() == par.getAlign())
1059 || (!next_layout.isEnvironment()
1060 && nextpar->getDepth() > par.getDepth()
1061 && nextpar->getAlign() == par.getAlign())
1062 || (!style.isEnvironment()
1063 && next_layout.latextype == LATEX_ENVIRONMENT
1064 && nextpar->getDepth() < par.getDepth())
1065 || (style.isCommand()
1066 && !next_layout.isEnvironment()
1067 && style.align == par.getAlign()
1068 && next_layout.align == nextpar->getAlign())
1069 || (style.align != par.getAlign()
1070 && tclass.isDefaultLayout(next_layout))) {
1076 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1077 << &par << " next " << nextpar);
1083 // LaTeX all paragraphs
1084 void latexParagraphs(Buffer const & buf,
1087 OutputParams const & runparams,
1088 string const & everypar)
1090 LASSERT(runparams.par_begin <= runparams.par_end,
1091 { os << "% LaTeX Output Error\n"; return; } );
1093 BufferParams const & bparams = buf.params();
1095 bool const maintext = text.isMainText();
1096 bool const is_child = buf.masterBuffer() != &buf;
1098 // Open a CJK environment at the beginning of the main buffer
1099 // if the document's language is a CJK language
1100 // (but not in child documents)
1101 if (maintext && !is_child
1102 && bparams.encoding().package() == Encoding::CJK) {
1103 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1104 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1105 open_encoding_ = CJK;
1107 // if "auto begin" is switched off, explicitly switch the
1108 // language on at start
1109 string const mainlang = runparams.use_polyglossia
1110 ? getPolyglossiaEnvName(bparams.language)
1111 : bparams.language->babel();
1112 string const lang_begin_command = runparams.use_polyglossia ?
1113 "\\begin{$$lang}" : lyxrc.language_command_begin;
1115 if (maintext && !lyxrc.language_auto_begin &&
1116 !mainlang.empty()) {
1118 os << from_utf8(subst(lang_begin_command,
1121 if (runparams.use_polyglossia
1122 && !bparams.language->polyglossiaOpts().empty())
1124 << from_ascii(bparams.language->polyglossiaOpts())
1129 ParagraphList const & paragraphs = text.paragraphs();
1131 if (runparams.par_begin == runparams.par_end) {
1132 // The full doc will be exported but it is easier to just rely on
1133 // runparams range parameters that will be passed TeXEnvironment.
1134 runparams.par_begin = 0;
1135 runparams.par_end = paragraphs.size();
1138 pit_type pit = runparams.par_begin;
1139 // lastpit is for the language check after the loop.
1140 pit_type lastpit = pit;
1141 // variables used in the loop:
1142 bool was_title = false;
1143 bool already_title = false;
1144 DocumentClass const & tclass = bparams.documentClass();
1146 for (; pit < runparams.par_end; ++pit) {
1148 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1150 // FIXME This check should not be needed. We should
1151 // perhaps issue an error if it is.
1152 Layout const & layout = text.inset().forcePlainLayout() ?
1153 tclass.plainLayout() : par->layout();
1155 if (layout.intitle) {
1156 if (already_title) {
1157 LYXERR0("Error in latexParagraphs: You"
1158 " should not mix title layouts"
1159 " with normal ones.");
1160 } else if (!was_title) {
1162 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1164 << from_ascii(tclass.titlename())
1168 } else if (was_title && !already_title) {
1169 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1170 os << "\\end{" << from_ascii(tclass.titlename())
1174 os << "\\" << from_ascii(tclass.titlename())
1177 already_title = true;
1182 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1183 // This is a standard top level paragraph, TeX it and continue.
1184 TeXOnePar(buf, text, pit, os, runparams, everypar);
1188 TeXEnvironmentData const data =
1189 prepareEnvironment(buf, text, par, os, runparams);
1190 // pit can be changed in TeXEnvironment.
1191 TeXEnvironment(buf, text, runparams, pit, os);
1192 finishEnvironment(os, runparams, data);
1195 if (pit == runparams.par_end) {
1196 // Make sure that the last paragraph is
1197 // correctly terminated (because TeXOnePar does
1198 // not add a \n in this case)
1202 // It might be that we only have a title in this document
1203 if (was_title && !already_title) {
1204 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1205 os << "\\end{" << from_ascii(tclass.titlename())
1208 os << "\\" << from_ascii(tclass.titlename())
1213 // if "auto end" is switched off, explicitly close the language at the end
1214 // but only if the last par is in a babel language
1215 string const lang_end_command = runparams.use_polyglossia ?
1216 "\\end{$$lang}" : lyxrc.language_command_end;
1217 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1218 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1219 os << from_utf8(subst(lang_end_command,
1225 // If the last paragraph is an environment, we'll have to close
1226 // CJK at the very end to do proper nesting.
1227 if (maintext && !is_child && open_encoding_ == CJK) {
1228 os << "\\end{CJK}\n";
1229 open_encoding_ = none;
1232 // reset inherited encoding
1233 if (cjk_inherited_ > 0) {
1234 cjk_inherited_ -= 1;
1235 if (cjk_inherited_ == 0)
1236 open_encoding_ = CJK;
1241 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1242 OutputParams const & runparams, Encoding const & newEnc,
1245 Encoding const & oldEnc = *runparams.encoding;
1246 bool moving_arg = runparams.moving_arg;
1247 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1248 bool const from_to_cjk =
1249 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1250 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1251 if (!force && !from_to_cjk
1252 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1253 return make_pair(false, 0);
1255 // Do nothing if the encoding is unchanged.
1256 if (oldEnc.name() == newEnc.name())
1257 return make_pair(false, 0);
1259 // FIXME We ignore encoding switches from/to encodings that do
1260 // neither support the inputenc package nor the CJK package here.
1261 // This does of course only work in special cases (e.g. switch from
1262 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1263 // but it is the best we can do
1264 if (oldEnc.package() == Encoding::none
1265 || newEnc.package() == Encoding::none)
1266 return make_pair(false, 0);
1268 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1269 << oldEnc.name() << " to " << newEnc.name());
1270 os << setEncoding(newEnc.iconvName());
1271 if (bparams.inputenc == "default")
1272 return make_pair(true, 0);
1274 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1275 switch (newEnc.package()) {
1276 case Encoding::none:
1277 case Encoding::japanese:
1278 // shouldn't ever reach here, see above
1279 return make_pair(true, 0);
1280 case Encoding::inputenc: {
1281 int count = inputenc_arg.length();
1282 if (oldEnc.package() == Encoding::CJK &&
1283 open_encoding_ == CJK) {
1285 open_encoding_ = none;
1288 else if (oldEnc.package() == Encoding::inputenc &&
1289 open_encoding_ == inputenc) {
1291 open_encoding_ = none;
1294 if (runparams.local_font != 0
1295 && oldEnc.package() == Encoding::CJK) {
1296 // within insets, \inputenc switches need
1297 // to be embraced within \bgroup...\egroup;
1301 open_encoding_ = inputenc;
1303 // with the japanese option, inputenc is omitted.
1304 if (runparams.use_japanese)
1305 return make_pair(true, count);
1306 os << "\\inputencoding{" << inputenc_arg << '}';
1307 return make_pair(true, count + 16);
1309 case Encoding::CJK: {
1310 int count = inputenc_arg.length();
1311 if (oldEnc.package() == Encoding::CJK &&
1312 open_encoding_ == CJK) {
1316 if (oldEnc.package() == Encoding::inputenc &&
1317 open_encoding_ == inputenc) {
1321 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1322 << from_ascii(bparams.fonts_cjk) << "}";
1323 open_encoding_ = CJK;
1324 return make_pair(true, count + 15);
1327 // Dead code to avoid a warning:
1328 return make_pair(true, 0);