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());
238 void TeXEnvironment(Buffer const & buf, Text const & text,
239 OutputParams const & runparams,
240 pit_type & pit, otexstream & os)
242 ParagraphList const & paragraphs = text.paragraphs();
243 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
244 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
246 Layout const & current_layout = par->layout();
247 depth_type const current_depth = par->params().depth();
248 Length const & current_left_indent = par->params().leftIndent();
250 // This is for debugging purpose at the end.
251 pit_type const par_begin = pit;
252 for (; pit < runparams.par_end; ++pit) {
253 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
255 // check first if this is an higher depth paragraph.
256 bool go_out = (par->params().depth() < current_depth);
257 if (par->params().depth() == current_depth) {
258 // This environment is finished.
259 go_out |= (par->layout() != current_layout);
260 go_out |= (par->params().leftIndent() != current_left_indent);
263 // nothing to do here, restore pit and go out.
268 if (par->layout() == current_layout
269 && par->params().depth() == current_depth
270 && par->params().leftIndent() == current_left_indent) {
271 // We are still in the same environment so TeXOnePar and continue;
272 TeXOnePar(buf, text, pit, os, runparams);
276 // We are now in a deeper environment.
277 // Either par->layout() != current_layout
278 // Or par->params().depth() > current_depth
279 // Or par->params().leftIndent() != current_left_indent)
281 // FIXME This test should not be necessary.
282 // We should perhaps issue an error if it is.
283 bool const force_plain_layout = text.inset().forcePlainLayout();
284 Layout const & style = force_plain_layout
285 ? buf.params().documentClass().plainLayout()
288 if (!style.isEnvironment()) {
289 // This is a standard paragraph, no need to call TeXEnvironment.
290 TeXOnePar(buf, text, pit, os, runparams);
291 // Unless the current or following paragraph are inside
292 // \begin..\end tags and the nesting layout is not of
293 // an itemize kind, we have to output a paragraph break
294 // (we already are at the beginning of a new line)
295 if (pit + 1 < runparams.par_end) {
296 ParagraphList::const_iterator nextpar =
297 paragraphs.constIterator(pit + 1);
298 if (nextpar->layout() == current_layout
299 && nextpar->getDepth() == current_depth
300 && current_layout.latextype != LATEX_ITEM_ENVIRONMENT
301 && current_layout.latextype != LATEX_LIST_ENVIRONMENT
302 && par->getAlign() == style.align
303 && nextpar->getAlign() == nextpar->layout().align)
309 // This is a new environment.
310 TeXEnvironmentData const data =
311 prepareEnvironment(buf, text, par, os, runparams);
312 // Recursive call to TeXEnvironment!
313 TeXEnvironment(buf, text, runparams, pit, os);
314 finishEnvironment(os, runparams, data);
317 if (pit != runparams.par_end)
318 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
322 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
323 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
325 unsigned int const argnr = latexargs.size();
329 for (unsigned int i = 1; i <= argnr; ++i) {
330 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
331 bool inserted = false;
332 if (lit != ilist.end()) {
333 InsetArgument const * ins = (*lit).second;
335 Layout::LaTeXArgMap::const_iterator const lait =
336 latexargs.find(ins->name());
337 if (lait != latexargs.end()) {
338 Layout::latexarg arg = (*lait).second;
339 docstring ldelim = arg.mandatory ?
340 from_ascii("{") : from_ascii("[");
341 docstring rdelim = arg.mandatory ?
342 from_ascii("}") : from_ascii("]");
343 if (!arg.ldelim.empty())
345 if (!arg.rdelim.empty())
347 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
353 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
354 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
355 for (; lait != laend; ++lait) {
356 string const name = prefix + convert<string>(i);
357 if ((*lait).first == name) {
358 Layout::latexarg arg = (*lait).second;
359 docstring preset = arg.presetarg;
360 if (!arg.defaultarg.empty()) {
363 preset += arg.defaultarg;
366 docstring ldelim = arg.ldelim.empty() ?
367 from_ascii("{") : arg.ldelim;
368 docstring rdelim = arg.rdelim.empty() ?
369 from_ascii("}") : arg.rdelim;
370 os << ldelim << preset << rdelim;
371 } else if (!preset.empty()) {
372 docstring ldelim = arg.ldelim.empty() ?
373 from_ascii("[") : arg.ldelim;
374 docstring rdelim = arg.rdelim.empty() ?
375 from_ascii("]") : arg.rdelim;
376 os << ldelim << preset << rdelim;
377 } else if (find(required.begin(), required.end(),
378 (*lait).first) != required.end()) {
379 docstring ldelim = arg.ldelim.empty() ?
380 from_ascii("[") : arg.ldelim;
381 docstring rdelim = arg.rdelim.empty() ?
382 from_ascii("]") : arg.rdelim;
383 os << ldelim << rdelim;
396 void latexArgInsets(Paragraph const & par, otexstream & os,
397 OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
399 map<int, InsetArgument const *> ilist;
400 vector<string> required;
402 InsetList::const_iterator it = par.insetList().begin();
403 InsetList::const_iterator end = par.insetList().end();
404 for (; it != end; ++it) {
405 if (it->inset->lyxCode() == ARG_CODE) {
406 InsetArgument const * ins =
407 static_cast<InsetArgument const *>(it->inset);
408 if (ins->name().empty())
409 LYXERR0("Error: Unnamed argument inset!");
411 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
412 unsigned int const nr = convert<unsigned int>(name);
414 Layout::LaTeXArgMap::const_iterator const lit =
415 latexargs.find(ins->name());
416 if (lit != latexargs.end()) {
417 Layout::latexarg const & arg = (*lit).second;
418 if (!arg.requires.empty()) {
419 vector<string> req = getVectorFromString(arg.requires);
420 required.insert(required.end(), req.begin(), req.end());
426 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
430 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
431 otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
432 string const & prefix)
434 map<int, InsetArgument const *> ilist;
435 vector<string> required;
437 depth_type const current_depth = pit->params().depth();
438 Layout const current_layout = pit->layout();
440 // get the first paragraph in sequence with this layout and depth
443 if (boost::prior(pit, offset) == pars.begin())
445 ParagraphList::const_iterator priorpit = boost::prior(pit, offset + 1);
446 if (priorpit->layout() == current_layout
447 && priorpit->params().depth() == current_depth)
453 ParagraphList::const_iterator spit = boost::prior(pit, offset);
455 for (; spit != pars.end(); ++spit) {
456 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
458 if (spit->params().depth() > current_depth)
460 InsetList::const_iterator it = spit->insetList().begin();
461 InsetList::const_iterator end = spit->insetList().end();
462 for (; it != end; ++it) {
463 if (it->inset->lyxCode() == ARG_CODE) {
464 InsetArgument const * ins =
465 static_cast<InsetArgument const *>(it->inset);
466 if (ins->name().empty())
467 LYXERR0("Error: Unnamed argument inset!");
469 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
470 unsigned int const nr = convert<unsigned int>(name);
471 if (ilist.find(nr) == ilist.end())
473 Layout::LaTeXArgMap::const_iterator const lit =
474 latexargs.find(ins->name());
475 if (lit != latexargs.end()) {
476 Layout::latexarg const & arg = (*lit).second;
477 if (!arg.requires.empty()) {
478 vector<string> req = getVectorFromString(arg.requires);
479 required.insert(required.end(), req.begin(), req.end());
486 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
491 // output the proper paragraph start according to latextype.
492 void parStartCommand(Paragraph const & par, otexstream & os,
493 OutputParams const & runparams, Layout const & style)
495 switch (style.latextype) {
497 os << '\\' << from_ascii(style.latexname());
500 if (!style.latexargs().empty())
501 latexArgInsets(par, os, runparams, style.latexargs());
502 os << from_ascii(style.latexparam());
504 case LATEX_ITEM_ENVIRONMENT:
505 case LATEX_LIST_ENVIRONMENT:
506 os << "\\" + style.itemcommand();
508 if (!style.itemargs().empty())
509 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
512 case LATEX_BIB_ENVIRONMENT:
513 // ignore this, the inset will write itself
522 // FIXME: this should be anonymous
523 void TeXOnePar(Buffer const & buf,
527 OutputParams const & runparams_in,
528 string const & everypar,
529 int start_pos, int end_pos)
531 BufferParams const & bparams = runparams_in.is_child
532 ? buf.masterParams() : buf.params();
533 ParagraphList const & paragraphs = text.paragraphs();
534 Paragraph const & par = paragraphs.at(pit);
535 // FIXME This check should not really be needed.
536 // Perhaps we should issue an error if it is.
537 Layout const style = text.inset().forcePlainLayout() ?
538 bparams.documentClass().plainLayout() : par.layout();
540 if (style.inpreamble)
543 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
546 OutputParams runparams = runparams_in;
547 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
548 // We reinitialze par begin and end to be on the safe side
549 // with embedded inset as we don't know if they set those
551 runparams.par_begin = 0;
552 runparams.par_end = 0;
554 bool const maintext = text.isMainText();
555 // we are at the beginning of an inset and CJK is already open;
556 // we count inheritation levels to get the inset nesting right.
557 if (pit == 0 && !maintext
558 && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
560 open_encoding_ = none;
563 if (text.inset().isPassThru()) {
564 Font const outerfont = text.outerFont(pit);
566 // No newline before first paragraph in this lyxtext
569 if (!text.inset().getLayout().parbreakIsNewline())
573 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
577 Paragraph const * nextpar = runparams.isLastPar
578 ? 0 : ¶graphs.at(pit + 1);
580 if (style.pass_thru) {
581 Font const outerfont = text.outerFont(pit);
582 parStartCommand(par, os, runparams, style);
584 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
586 // I did not create a parEndCommand for this minuscule
587 // task because in the other user of parStartCommand
588 // the code is different (JMarc)
589 if (style.isCommand())
593 if (!style.parbreak_is_newline) {
595 } else if (nextpar && !style.isEnvironment()) {
596 Layout const nextstyle = text.inset().forcePlainLayout()
597 ? bparams.documentClass().plainLayout()
599 if (nextstyle.name() != style.name())
606 // This paragraph's language
607 Language const * const par_language = par.getParLanguage(bparams);
608 // The document's language
609 Language const * const doc_language = bparams.language;
610 // The language that was in effect when the environment this paragraph is
611 // inside of was opened
612 Language const * const outer_language =
613 (runparams.local_font != 0) ?
614 runparams.local_font->language() : doc_language;
616 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
618 // The previous language that was in effect is the language of the
619 // previous paragraph, unless the previous paragraph is inside an
620 // environment with nesting depth greater than (or equal to, but with
621 // a different layout) the current one. If there is no previous
622 // paragraph, the previous language is the outer language.
623 bool const use_prev_env_language = prev_env_language_ != 0
625 && priorpar->layout().isEnvironment()
626 && (priorpar->getDepth() > par.getDepth()
627 || (priorpar->getDepth() == par.getDepth()
628 && priorpar->layout() != par.layout()));
629 Language const * const prev_language =
631 ? (use_prev_env_language ? prev_env_language_
632 : priorpar->getParLanguage(bparams))
636 bool const use_polyglossia = runparams.use_polyglossia;
637 string const par_lang = use_polyglossia ?
638 getPolyglossiaEnvName(par_language): par_language->babel();
639 string const prev_lang = use_polyglossia ?
640 getPolyglossiaEnvName(prev_language) : prev_language->babel();
641 string const doc_lang = use_polyglossia ?
642 getPolyglossiaEnvName(doc_language) : doc_language->babel();
643 string const outer_lang = use_polyglossia ?
644 getPolyglossiaEnvName(outer_language) : outer_language->babel();
645 string lang_begin_command = use_polyglossia ?
646 "\\begin{$$lang}" : lyxrc.language_command_begin;
647 string lang_end_command = use_polyglossia ?
648 "\\end{$$lang}" : lyxrc.language_command_end;
649 // the '%' is necessary to prevent unwanted whitespace
650 string lang_command_termination = "%\n";
652 // In some insets (such as Arguments), we cannot use \selectlanguage
653 bool const localswitch = !use_polyglossia
654 && text.inset().getLayout().forcelocalfontswitch();
656 lang_begin_command = lyxrc.language_command_local;
657 lang_end_command = "}";
658 lang_command_termination.clear();
661 if (par_lang != prev_lang
662 // check if we already put language command in TeXEnvironment()
663 && !(style.isEnvironment()
664 && (pit == 0 || (priorpar->layout() != par.layout()
665 && priorpar->getDepth() <= par.getDepth())
666 || priorpar->getDepth() < par.getDepth())))
668 if (!lang_end_command.empty() &&
669 prev_lang != outer_lang &&
672 os << from_ascii(subst(lang_end_command,
675 << lang_command_termination;
678 // We need to open a new language if we couldn't close the previous
679 // one (because there's no language_command_end); and even if we closed
680 // the previous one, if the current language is different than the
681 // outer_language (which is currently in effect once the previous one
683 if ((lang_end_command.empty() || par_lang != outer_lang)
684 && !par_lang.empty()) {
685 // If we're inside an inset, and that inset is within an \L or \R
686 // (or equivalents), then within the inset, too, any opposite
687 // language paragraph should appear within an \L or \R (in addition
688 // to, outside of, the normal language switch commands).
689 // This behavior is not correct for ArabTeX, though.
692 && par_language->lang() != "arabic_arabtex"
693 && outer_language->lang() != "arabic_arabtex"
694 // are we in an inset?
695 && runparams.local_font != 0
696 // is the inset within an \L or \R?
698 // FIXME: currently, we don't check this; this means that
699 // we'll have unnnecessary \L and \R commands, but that
700 // doesn't seem to hurt (though latex will complain)
702 // is this paragraph in the opposite direction?
703 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
704 // FIXME: I don't have a working copy of the Arabi package, so
705 // I'm not sure if the farsi and arabic_arabi stuff is correct
707 if (par_language->lang() == "farsi")
709 else if (outer_language->lang() == "farsi")
711 else if (par_language->lang() == "arabic_arabi")
713 else if (outer_language->lang() == "arabic_arabi")
715 // remaining RTL languages currently is hebrew
716 else if (par_language->rightToLeft())
721 // With CJK, the CJK tag has to be closed first (see below)
722 if (runparams.encoding->package() != Encoding::CJK
723 && !par_lang.empty()) {
724 os << from_ascii(subst(
729 && !par_language->polyglossiaOpts().empty())
731 << from_ascii(par_language->polyglossiaOpts())
733 os << lang_command_termination;
738 // Switch file encoding if necessary; no need to do this for "default"
739 // encoding, since this only affects the position of the outputted
740 // \inputencoding command; the encoding switch will occur when necessary
741 if (bparams.inputenc == "auto"
742 && runparams.encoding->package() != Encoding::none) {
743 // Look ahead for future encoding changes.
744 // We try to output them at the beginning of the paragraph,
745 // since the \inputencoding command is not allowed e.g. in
746 // sections. For this reason we only set runparams.moving_arg
747 // after checking for the encoding change, otherwise the
748 // change would be always avoided by switchEncoding().
749 for (pos_type i = 0; i < par.size(); ++i) {
750 char_type const c = par.getChar(i);
751 Encoding const * const encoding =
752 par.getFontSettings(bparams, i).language()->encoding();
753 if (encoding->package() != Encoding::CJK
754 && runparams.encoding->package() == Encoding::inputenc
759 // All characters before c are in the ASCII range, and
760 // c is non-ASCII (but no inset), so change the
761 // encoding to that required by the language of c.
762 // With CJK, only add switch if we have CJK content at the beginning
764 if (i != 0 && encoding->package() == Encoding::CJK)
767 pair<bool, int> enc_switch = switchEncoding(os.os(),
768 bparams, runparams, *encoding);
769 // the following is necessary after a CJK environment in a multilingual
770 // context (nesting issue).
771 if (par_language->encoding()->package() == Encoding::CJK
772 && open_encoding_ != CJK && cjk_inherited_ == 0) {
773 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
774 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
775 open_encoding_ = CJK;
777 if (encoding->package() != Encoding::none && enc_switch.first) {
778 if (enc_switch.second > 0) {
779 // the '%' is necessary to prevent unwanted whitespace
782 // With CJK, the CJK tag had to be closed first (see above)
783 if (runparams.encoding->package() == Encoding::CJK
784 && !par_lang.empty()) {
785 os << from_ascii(subst(
789 << lang_command_termination;
791 runparams.encoding = encoding;
797 runparams.moving_arg |= style.needprotect;
798 Encoding const * const prev_encoding = runparams.encoding;
800 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
801 if (par.allowParagraphCustomization()) {
802 if (par.params().startOfAppendix()) {
803 os << "\\appendix\n";
806 if (!par.params().spacing().isDefault()
807 && (pit == 0 || !priorpar->hasSameLayout(par)))
809 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
813 if (style.isCommand()) {
818 parStartCommand(par, os, runparams, style);
819 Font const outerfont = text.outerFont(pit);
822 os << from_utf8(everypar);
823 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
825 // Make sure that \\par is done with the font of the last
826 // character if this has another size as the default.
827 // This is necessary because LaTeX (and LyX on the screen)
828 // calculates the space between the baselines according
829 // to this font. (Matthias)
831 // Is this really needed ? (Dekel)
832 // We do not need to use to change the font for the last paragraph
835 Font const font = par.empty()
836 ? par.getLayoutFont(bparams, outerfont)
837 : par.getFont(bparams, par.size() - 1, outerfont);
839 bool const is_command = style.isCommand();
841 if (style.resfont.size() != font.fontInfo().size()
845 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
846 } else if (is_command) {
848 if (!style.postcommandargs().empty())
849 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
850 if (runparams.encoding != prev_encoding) {
851 runparams.encoding = prev_encoding;
852 if (!runparams.isFullUnicode())
853 os << setEncoding(prev_encoding->iconvName());
857 bool pending_newline = false;
858 bool unskip_newline = false;
859 switch (style.latextype) {
860 case LATEX_ITEM_ENVIRONMENT:
861 case LATEX_LIST_ENVIRONMENT:
863 && (par.params().depth() < nextpar->params().depth())
864 && !par.isEnvSeparator(par.size() - 1))
865 pending_newline = true;
867 case LATEX_ENVIRONMENT: {
868 // if its the last paragraph of the current environment
869 // skip it otherwise fall through
871 && (nextpar->layout() != par.layout()
872 || nextpar->params().depth() != par.params().depth()))
876 // fall through possible
878 // we don't need it for the last paragraph!!!
879 // or if the last thing is an environment separator
880 if (nextpar && !par.isEnvSeparator(par.size() - 1))
881 pending_newline = true;
884 if (par.allowParagraphCustomization()) {
885 if (!par.params().spacing().isDefault()
886 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
890 string const endtag =
891 par.params().spacing().writeEnvirEnd(useSetSpace);
892 if (prefixIs(endtag, "\\end{"))
895 os << from_ascii(endtag);
896 pending_newline = true;
900 // Closing the language is needed for the last paragraph; it is also
901 // needed if we're within an \L or \R that we may have opened above (not
902 // necessarily in this paragraph) and are about to close.
903 bool closing_rtl_ltr_environment = !use_polyglossia
905 && (par_language->lang() != "arabic_arabtex"
906 && outer_language->lang() != "arabic_arabtex")
907 // have we opened an \L or \R environment?
908 && runparams.local_font != 0
909 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
910 // are we about to close the language?
911 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
912 || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
914 if (closing_rtl_ltr_environment
915 || (runparams.isLastPar
916 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
917 || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
918 // Since \selectlanguage write the language to the aux file,
919 // we need to reset the language at the end of footnote or
925 // when the paragraph uses CJK, the language has to be closed earlier
926 if (font.language()->encoding()->package() != Encoding::CJK) {
927 if (lang_end_command.empty()) {
928 // If this is a child, we should restore the
929 // master language after the last paragraph.
930 Language const * const current_language =
931 (runparams.isLastPar && runparams.master_language)
932 ? runparams.master_language
934 string const current_lang = use_polyglossia
935 ? getPolyglossiaEnvName(current_language)
936 : current_language->babel();
937 if (!current_lang.empty()) {
938 os << from_ascii(subst(
942 pending_newline = !localswitch;
943 unskip_newline = !localswitch;
945 } else if (!par_lang.empty()) {
946 os << from_ascii(subst(
950 pending_newline = !localswitch;
951 unskip_newline = !localswitch;
955 if (closing_rtl_ltr_environment)
958 if (pending_newline) {
960 // prevent unwanted whitespace
965 // if this is a CJK-paragraph and the next isn't, close CJK
966 // also if the next paragraph is a multilingual environment (because of nesting)
968 && open_encoding_ == CJK
969 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
970 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
971 // inbetween environments, CJK has to be closed later (nesting!)
972 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
973 os << "\\end{CJK}\n";
974 open_encoding_ = none;
977 // If this is the last paragraph, close the CJK environment
978 // if necessary. If it's an environment, we'll have to \end that first.
979 if (runparams.isLastPar && !style.isEnvironment()) {
980 switch (open_encoding_) {
982 // do nothing at the end of child documents
983 if (maintext && buf.masterBuffer() != &buf)
987 os << "\n\\end{CJK}\n";
991 open_encoding_ = none;
996 open_encoding_ = none;
1006 // If this is the last paragraph, and a local_font was set upon entering
1007 // the inset, and we're using "auto" or "default" encoding, the encoding
1008 // should be set back to that local_font's encoding.
1009 // However, do not change the encoding when a fully unicode aware backend
1010 // such as XeTeX is used.
1011 if (runparams.isLastPar && runparams_in.local_font != 0
1012 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1013 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1014 && (!runparams.isFullUnicode())) {
1015 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1016 os << setEncoding(runparams_in.encoding->iconvName());
1018 // Otherwise, the current encoding should be set for the next paragraph.
1020 runparams_in.encoding = runparams.encoding;
1023 // we don't need a newline for the last paragraph!!!
1024 // Note from JMarc: we will re-add a \n explicitly in
1025 // TeXEnvironment, because it is needed in this case
1026 if (nextpar && !par.isEnvSeparator(par.size() - 1)) {
1027 // Make sure to start a new line
1029 // Here we now try to avoid spurious empty lines by outputting
1030 // a paragraph break only if: (case 1) the paragraph style
1031 // allows parbreaks and no \begin, \end or \item tags are
1032 // going to follow (i.e., if the next isn't the first
1033 // or the current isn't the last paragraph of an environment
1034 // or itemize) and the depth and alignment of the following
1035 // paragraph is unchanged, or (case 2) the following is a
1036 // non-environment paragraph whose depth is increased but
1037 // whose alignment is unchanged.
1038 Layout const & next_layout = nextpar->layout();
1039 if ((style == next_layout
1040 && !style.parbreak_is_newline
1041 && style.latextype != LATEX_ITEM_ENVIRONMENT
1042 && style.latextype != LATEX_LIST_ENVIRONMENT
1043 && style.align == par.getAlign()
1044 && nextpar->getDepth() == par.getDepth()
1045 && nextpar->getAlign() == par.getAlign())
1046 || (!next_layout.isEnvironment()
1047 && nextpar->getDepth() > par.getDepth()
1048 && nextpar->getAlign() == par.getAlign())) {
1053 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1054 << &par << " next " << nextpar);
1060 // LaTeX all paragraphs
1061 void latexParagraphs(Buffer const & buf,
1064 OutputParams const & runparams,
1065 string const & everypar)
1067 LASSERT(runparams.par_begin <= runparams.par_end,
1068 { os << "% LaTeX Output Error\n"; return; } );
1070 BufferParams const & bparams = buf.params();
1072 bool const maintext = text.isMainText();
1073 bool const is_child = buf.masterBuffer() != &buf;
1075 // Open a CJK environment at the beginning of the main buffer
1076 // if the document's language is a CJK language
1077 // (but not in child documents)
1078 if (maintext && !is_child
1079 && bparams.encoding().package() == Encoding::CJK) {
1080 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1081 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1082 open_encoding_ = CJK;
1084 // if "auto begin" is switched off, explicitly switch the
1085 // language on at start
1086 string const mainlang = runparams.use_polyglossia
1087 ? getPolyglossiaEnvName(bparams.language)
1088 : bparams.language->babel();
1089 string const lang_begin_command = runparams.use_polyglossia ?
1090 "\\begin{$$lang}" : lyxrc.language_command_begin;
1092 if (maintext && !lyxrc.language_auto_begin &&
1093 !mainlang.empty()) {
1095 os << from_utf8(subst(lang_begin_command,
1098 if (runparams.use_polyglossia
1099 && !bparams.language->polyglossiaOpts().empty())
1101 << from_ascii(bparams.language->polyglossiaOpts())
1106 ParagraphList const & paragraphs = text.paragraphs();
1108 if (runparams.par_begin == runparams.par_end) {
1109 // The full doc will be exported but it is easier to just rely on
1110 // runparams range parameters that will be passed TeXEnvironment.
1111 runparams.par_begin = 0;
1112 runparams.par_end = paragraphs.size();
1115 pit_type pit = runparams.par_begin;
1116 // lastpit is for the language check after the loop.
1117 pit_type lastpit = pit;
1118 // variables used in the loop:
1119 bool was_title = false;
1120 bool already_title = false;
1121 DocumentClass const & tclass = bparams.documentClass();
1123 for (; pit < runparams.par_end; ++pit) {
1125 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1127 // FIXME This check should not be needed. We should
1128 // perhaps issue an error if it is.
1129 Layout const & layout = text.inset().forcePlainLayout() ?
1130 tclass.plainLayout() : par->layout();
1132 if (layout.intitle) {
1133 if (already_title) {
1134 LYXERR0("Error in latexParagraphs: You"
1135 " should not mix title layouts"
1136 " with normal ones.");
1137 } else if (!was_title) {
1139 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1141 << from_ascii(tclass.titlename())
1145 } else if (was_title && !already_title) {
1146 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1147 os << "\\end{" << from_ascii(tclass.titlename())
1151 os << "\\" << from_ascii(tclass.titlename())
1154 already_title = true;
1159 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1160 // This is a standard top level paragraph, TeX it and continue.
1161 TeXOnePar(buf, text, pit, os, runparams, everypar);
1165 TeXEnvironmentData const data =
1166 prepareEnvironment(buf, text, par, os, runparams);
1167 // pit can be changed in TeXEnvironment.
1168 TeXEnvironment(buf, text, runparams, pit, os);
1169 finishEnvironment(os, runparams, data);
1172 if (pit == runparams.par_end) {
1173 // Make sure that the last paragraph is
1174 // correctly terminated (because TeXOnePar does
1175 // not add a \n in this case)
1179 // It might be that we only have a title in this document
1180 if (was_title && !already_title) {
1181 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1182 os << "\\end{" << from_ascii(tclass.titlename())
1185 os << "\\" << from_ascii(tclass.titlename())
1190 // if "auto end" is switched off, explicitly close the language at the end
1191 // but only if the last par is in a babel language
1192 string const lang_end_command = runparams.use_polyglossia ?
1193 "\\end{$$lang}" : lyxrc.language_command_end;
1194 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1195 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1196 os << from_utf8(subst(lang_end_command,
1202 // If the last paragraph is an environment, we'll have to close
1203 // CJK at the very end to do proper nesting.
1204 if (maintext && !is_child && open_encoding_ == CJK) {
1205 os << "\\end{CJK}\n";
1206 open_encoding_ = none;
1209 // reset inherited encoding
1210 if (cjk_inherited_ > 0) {
1211 cjk_inherited_ -= 1;
1212 if (cjk_inherited_ == 0)
1213 open_encoding_ = CJK;
1218 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1219 OutputParams const & runparams, Encoding const & newEnc,
1222 Encoding const & oldEnc = *runparams.encoding;
1223 bool moving_arg = runparams.moving_arg;
1224 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1225 bool const from_to_cjk =
1226 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1227 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1228 if (!force && !from_to_cjk
1229 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1230 return make_pair(false, 0);
1232 // Do nothing if the encoding is unchanged.
1233 if (oldEnc.name() == newEnc.name())
1234 return make_pair(false, 0);
1236 // FIXME We ignore encoding switches from/to encodings that do
1237 // neither support the inputenc package nor the CJK package here.
1238 // This does of course only work in special cases (e.g. switch from
1239 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1240 // but it is the best we can do
1241 if (oldEnc.package() == Encoding::none
1242 || newEnc.package() == Encoding::none)
1243 return make_pair(false, 0);
1245 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1246 << oldEnc.name() << " to " << newEnc.name());
1247 os << setEncoding(newEnc.iconvName());
1248 if (bparams.inputenc == "default")
1249 return make_pair(true, 0);
1251 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1252 switch (newEnc.package()) {
1253 case Encoding::none:
1254 case Encoding::japanese:
1255 // shouldn't ever reach here, see above
1256 return make_pair(true, 0);
1257 case Encoding::inputenc: {
1258 int count = inputenc_arg.length();
1259 if (oldEnc.package() == Encoding::CJK &&
1260 open_encoding_ == CJK) {
1262 open_encoding_ = none;
1265 else if (oldEnc.package() == Encoding::inputenc &&
1266 open_encoding_ == inputenc) {
1268 open_encoding_ = none;
1271 if (runparams.local_font != 0
1272 && oldEnc.package() == Encoding::CJK) {
1273 // within insets, \inputenc switches need
1274 // to be embraced within \bgroup...\egroup;
1278 open_encoding_ = inputenc;
1280 // with the japanese option, inputenc is omitted.
1281 if (runparams.use_japanese)
1282 return make_pair(true, count);
1283 os << "\\inputencoding{" << inputenc_arg << '}';
1284 return make_pair(true, count + 16);
1286 case Encoding::CJK: {
1287 int count = inputenc_arg.length();
1288 if (oldEnc.package() == Encoding::CJK &&
1289 open_encoding_ == CJK) {
1293 if (oldEnc.package() == Encoding::inputenc &&
1294 open_encoding_ == inputenc) {
1298 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1299 << from_ascii(bparams.fonts_cjk) << "}";
1300 open_encoding_ = CJK;
1301 return make_pair(true, count + 15);
1304 // Dead code to avoid a warning:
1305 return make_pair(true, 0);