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/lyxalgo.h"
37 #include "support/textutils.h"
39 #include <QThreadStorage>
44 using namespace lyx::support;
60 OutputState() : open_encoding_(none), cjk_inherited_(0),
61 prev_env_language_(0), open_polyglossia_lang_("")
66 Language const * prev_env_language_;
67 string open_polyglossia_lang_;
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 string const getPolyglossiaBegin(string const & lang_begin_command,
93 string const & lang, string const & opts)
97 result = subst(lang_begin_command, "$$lang", lang);
98 string options = opts.empty() ?
99 string() : "[" + opts + "]";
100 result = subst(result, "$$opts", options);
106 struct TeXEnvironmentData
109 Layout const * style;
110 Language const * par_language;
111 Encoding const * prev_encoding;
112 bool leftindent_open;
116 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
118 ParagraphList::const_iterator pit,
120 OutputParams const & runparams)
122 TeXEnvironmentData data;
124 BufferParams const & bparams = buf.params();
126 // FIXME This test should not be necessary.
127 // We should perhaps issue an error if it is.
128 Layout const & style = text.inset().forcePlainLayout() ?
129 bparams.documentClass().plainLayout() : pit->layout();
131 ParagraphList const & paragraphs = text.paragraphs();
132 ParagraphList::const_iterator const priorpit =
133 pit == paragraphs.begin() ? pit : prev(pit, 1);
135 OutputState * state = getOutputState();
136 bool const use_prev_env_language = state->prev_env_language_ != 0
137 && priorpit->layout().isEnvironment()
138 && (priorpit->getDepth() > pit->getDepth()
139 || (priorpit->getDepth() == pit->getDepth()
140 && priorpit->layout() != pit->layout()));
142 data.prev_encoding = runparams.encoding;
143 data.par_language = pit->getParLanguage(bparams);
144 Language const * const doc_language = bparams.language;
145 Language const * const prev_par_language =
146 (pit != paragraphs.begin())
147 ? (use_prev_env_language ? state->prev_env_language_
148 : priorpit->getParLanguage(bparams))
151 bool const use_polyglossia = runparams.use_polyglossia;
152 string const par_lang = use_polyglossia ?
153 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
154 string const prev_par_lang = use_polyglossia ?
155 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
156 string const doc_lang = use_polyglossia ?
157 getPolyglossiaEnvName(doc_language) : doc_language->babel();
158 string const lang_begin_command = use_polyglossia ?
159 "\\begin{$$lang}" : lyxrc.language_command_begin;
160 string const lang_end_command = use_polyglossia ?
161 "\\end{$$lang}" : lyxrc.language_command_end;
163 if (par_lang != prev_par_lang) {
164 if (!lang_end_command.empty() &&
165 prev_par_lang != doc_lang &&
166 !prev_par_lang.empty()) {
167 os << from_ascii(subst(
171 // the '%' is necessary to prevent unwanted whitespace
175 if ((lang_end_command.empty() ||
176 par_lang != doc_lang) &&
178 string bc = use_polyglossia ?
179 getPolyglossiaBegin(lang_begin_command, par_lang,
180 data.par_language->polyglossiaOpts())
181 : subst(lang_begin_command, "$$lang", par_lang);
183 // the '%' is necessary to prevent unwanted whitespace
188 data.leftindent_open = false;
189 if (!pit->params().leftIndent().zero()) {
190 os << "\\begin{LyXParagraphLeftIndent}{"
191 << from_ascii(pit->params().leftIndent().asLatexString())
193 data.leftindent_open = true;
196 if (style.isEnvironment()) {
197 if (par_lang != doc_lang)
198 state->open_polyglossia_lang_ = par_lang;
199 os << "\\begin{" << from_ascii(style.latexname()) << '}';
200 if (!style.latexargs().empty()) {
201 OutputParams rp = runparams;
202 rp.local_font = &pit->getFirstFontSettings(bparams);
203 latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
205 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
207 << pit->params().labelWidthString()
209 } else if (style.labeltype == LABEL_BIBLIO) {
210 if (pit->params().labelWidthString().empty())
211 os << '{' << bibitemWidest(buf, runparams) << "}\n";
214 << pit->params().labelWidthString()
217 os << from_ascii(style.latexparam()) << '\n';
221 // in multilingual environments, the CJK tags have to be nested properly
222 data.cjk_nested = false;
223 if (data.par_language->encoding()->package() == Encoding::CJK &&
224 state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
225 if (prev_par_language->encoding()->package() == Encoding::CJK)
226 os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
227 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
228 state->open_encoding_ = CJK;
229 data.cjk_nested = true;
235 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
236 TeXEnvironmentData const & data)
238 OutputState * state = getOutputState();
239 if (state->open_encoding_ == CJK && data.cjk_nested) {
240 // We need to close the encoding even if it does not change
241 // to do correct environment nesting
242 os << "\\end{CJK}\n";
243 state->open_encoding_ = none;
246 if (data.style->isEnvironment()) {
248 << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
249 state->prev_env_language_ = data.par_language;
250 if (runparams.encoding != data.prev_encoding) {
251 runparams.encoding = data.prev_encoding;
252 if (!runparams.isFullUnicode())
253 os << setEncoding(data.prev_encoding->iconvName());
257 if (data.leftindent_open) {
258 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
259 state->prev_env_language_ = data.par_language;
260 if (runparams.encoding != data.prev_encoding) {
261 runparams.encoding = data.prev_encoding;
262 if (!runparams.isFullUnicode())
263 os << setEncoding(data.prev_encoding->iconvName());
267 // Check whether we should output a blank line after the environment
268 if (!data.style->nextnoindent)
273 void TeXEnvironment(Buffer const & buf, Text const & text,
274 OutputParams const & runparams,
275 pit_type & pit, otexstream & os)
277 ParagraphList const & paragraphs = text.paragraphs();
278 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
279 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
281 Layout const & current_layout = par->layout();
282 depth_type const current_depth = par->params().depth();
283 Length const & current_left_indent = par->params().leftIndent();
285 // This is for debugging purpose at the end.
286 pit_type const par_begin = pit;
287 for (; pit < runparams.par_end; ++pit) {
288 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
290 // check first if this is an higher depth paragraph.
291 bool go_out = (par->params().depth() < current_depth);
292 if (par->params().depth() == current_depth) {
293 // This environment is finished.
294 go_out |= (par->layout() != current_layout);
295 go_out |= (par->params().leftIndent() != current_left_indent);
298 // nothing to do here, restore pit and go out.
303 if (par->layout() == current_layout
304 && par->params().depth() == current_depth
305 && par->params().leftIndent() == current_left_indent) {
306 // We are still in the same environment so TeXOnePar and continue;
307 TeXOnePar(buf, text, pit, os, runparams);
311 // We are now in a deeper environment.
312 // Either par->layout() != current_layout
313 // Or par->params().depth() > current_depth
314 // Or par->params().leftIndent() != current_left_indent)
316 // FIXME This test should not be necessary.
317 // We should perhaps issue an error if it is.
318 bool const force_plain_layout = text.inset().forcePlainLayout();
319 Layout const & style = force_plain_layout
320 ? buf.params().documentClass().plainLayout()
323 if (!style.isEnvironment()) {
324 // This is a standard paragraph, no need to call TeXEnvironment.
325 TeXOnePar(buf, text, pit, os, runparams);
329 // This is a new environment.
330 TeXEnvironmentData const data =
331 prepareEnvironment(buf, text, par, os, runparams);
332 // Recursive call to TeXEnvironment!
333 TeXEnvironment(buf, text, runparams, pit, os);
334 finishEnvironment(os, runparams, data);
337 if (pit != runparams.par_end)
338 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
342 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
343 map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
345 unsigned int const argnr = latexargs.size();
349 // Default and preset args are always output, so if they require
350 // other arguments, consider this.
351 Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
352 Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
353 for (; lit != lend; ++lit) {
354 Layout::latexarg arg = (*lit).second;
355 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
356 vector<string> req = getVectorFromString(arg.requires);
357 required.insert(required.end(), req.begin(), req.end());
361 for (unsigned int i = 1; i <= argnr; ++i) {
362 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
363 bool inserted = false;
364 if (lit != ilist.end()) {
365 InsetArgument const * ins = (*lit).second;
367 Layout::LaTeXArgMap::const_iterator const lait =
368 latexargs.find(ins->name());
369 if (lait != latexargs.end()) {
370 Layout::latexarg arg = (*lait).second;
371 docstring ldelim = arg.mandatory ?
372 from_ascii("{") : from_ascii("[");
373 docstring rdelim = arg.mandatory ?
374 from_ascii("}") : from_ascii("]");
375 if (!arg.ldelim.empty())
377 if (!arg.rdelim.empty())
379 ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
385 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
386 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
387 for (; lait != laend; ++lait) {
388 string const name = prefix + convert<string>(i);
389 if ((*lait).first == name) {
390 Layout::latexarg arg = (*lait).second;
391 docstring preset = arg.presetarg;
392 if (!arg.defaultarg.empty()) {
395 preset += arg.defaultarg;
398 docstring ldelim = arg.ldelim.empty() ?
399 from_ascii("{") : arg.ldelim;
400 docstring rdelim = arg.rdelim.empty() ?
401 from_ascii("}") : arg.rdelim;
402 os << ldelim << preset << rdelim;
403 } else if (!preset.empty()) {
404 docstring ldelim = arg.ldelim.empty() ?
405 from_ascii("[") : arg.ldelim;
406 docstring rdelim = arg.rdelim.empty() ?
407 from_ascii("]") : arg.rdelim;
408 os << ldelim << preset << rdelim;
409 } else if (find(required.begin(), required.end(),
410 (*lait).first) != required.end()) {
411 docstring ldelim = arg.ldelim.empty() ?
412 from_ascii("[") : arg.ldelim;
413 docstring rdelim = arg.rdelim.empty() ?
414 from_ascii("]") : arg.rdelim;
415 os << ldelim << rdelim;
428 void latexArgInsets(Paragraph const & par, otexstream & os,
429 OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, string const & prefix)
431 map<int, InsetArgument const *> ilist;
432 vector<string> required;
434 InsetList::const_iterator it = par.insetList().begin();
435 InsetList::const_iterator end = par.insetList().end();
436 for (; it != end; ++it) {
437 if (it->inset->lyxCode() == ARG_CODE) {
438 InsetArgument const * ins =
439 static_cast<InsetArgument const *>(it->inset);
440 if (ins->name().empty())
441 LYXERR0("Error: Unnamed argument inset!");
443 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
444 unsigned int const nr = convert<unsigned int>(name);
446 Layout::LaTeXArgMap::const_iterator const lit =
447 latexargs.find(ins->name());
448 if (lit != latexargs.end()) {
449 Layout::latexarg const & arg = (*lit).second;
450 if (!arg.requires.empty()) {
451 vector<string> req = getVectorFromString(arg.requires);
452 required.insert(required.end(), req.begin(), req.end());
458 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
462 void latexArgInsets(ParagraphList const & pars, ParagraphList::const_iterator pit,
463 otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
464 string const & prefix)
466 map<int, InsetArgument const *> ilist;
467 vector<string> required;
469 depth_type const current_depth = pit->params().depth();
470 Layout const current_layout = pit->layout();
472 // get the first paragraph in sequence with this layout and depth
475 if (prev(pit, offset) == pars.begin())
477 ParagraphList::const_iterator priorpit = prev(pit, offset + 1);
478 if (priorpit->layout() == current_layout
479 && priorpit->params().depth() == current_depth)
485 ParagraphList::const_iterator spit = prev(pit, offset);
487 for (; spit != pars.end(); ++spit) {
488 if (spit->layout() != current_layout || spit->params().depth() < current_depth)
490 if (spit->params().depth() > current_depth)
492 InsetList::const_iterator it = spit->insetList().begin();
493 InsetList::const_iterator end = spit->insetList().end();
494 for (; it != end; ++it) {
495 if (it->inset->lyxCode() == ARG_CODE) {
496 InsetArgument const * ins =
497 static_cast<InsetArgument const *>(it->inset);
498 if (ins->name().empty())
499 LYXERR0("Error: Unnamed argument inset!");
501 string const name = prefix.empty() ? ins->name() : split(ins->name(), ':');
502 unsigned int const nr = convert<unsigned int>(name);
503 if (ilist.find(nr) == ilist.end())
505 Layout::LaTeXArgMap::const_iterator const lit =
506 latexargs.find(ins->name());
507 if (lit != latexargs.end()) {
508 Layout::latexarg const & arg = (*lit).second;
509 if (!arg.requires.empty()) {
510 vector<string> req = getVectorFromString(arg.requires);
511 required.insert(required.end(), req.begin(), req.end());
518 getArgInsets(os, runparams, latexargs, ilist, required, prefix);
523 // output the proper paragraph start according to latextype.
524 void parStartCommand(Paragraph const & par, otexstream & os,
525 OutputParams const & runparams, Layout const & style)
527 switch (style.latextype) {
529 os << '\\' << from_ascii(style.latexname());
532 if (!style.latexargs().empty())
533 latexArgInsets(par, os, runparams, style.latexargs());
534 os << from_ascii(style.latexparam());
536 case LATEX_ITEM_ENVIRONMENT:
537 case LATEX_LIST_ENVIRONMENT:
538 os << "\\" + style.itemcommand();
540 if (!style.itemargs().empty())
541 latexArgInsets(par, os, runparams, style.itemargs(), "item:");
544 case LATEX_BIB_ENVIRONMENT:
545 // ignore this, the inset will write itself
554 // FIXME: this should be anonymous
555 void TeXOnePar(Buffer const & buf,
559 OutputParams const & runparams_in,
560 string const & everypar,
561 int start_pos, int end_pos)
563 BufferParams const & bparams = runparams_in.is_child
564 ? buf.masterParams() : buf.params();
565 ParagraphList const & paragraphs = text.paragraphs();
566 Paragraph const & par = paragraphs.at(pit);
567 // FIXME This check should not really be needed.
568 // Perhaps we should issue an error if it is.
569 Layout const & style = text.inset().forcePlainLayout() ?
570 bparams.documentClass().plainLayout() : par.layout();
572 if (style.inpreamble)
575 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
578 OutputParams runparams = runparams_in;
579 runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
580 // We reinitialze par begin and end to be on the safe side
581 // with embedded inset as we don't know if they set those
583 runparams.par_begin = 0;
584 runparams.par_end = 0;
586 bool const maintext = text.isMainText();
587 // we are at the beginning of an inset and CJK is already open;
588 // we count inheritation levels to get the inset nesting right.
589 OutputState * state = getOutputState();
590 if (pit == 0 && !maintext
591 && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
592 state->cjk_inherited_ += 1;
593 state->open_encoding_ = none;
596 if (text.inset().isPassThru()) {
597 Font const outerfont = text.outerFont(pit);
599 // No newline before first paragraph in this lyxtext
602 if (!text.inset().getLayout().parbreakIsNewline())
606 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
610 Paragraph const * nextpar = runparams.isLastPar
611 ? 0 : ¶graphs.at(pit + 1);
613 if (style.pass_thru) {
614 Font const outerfont = text.outerFont(pit);
615 parStartCommand(par, os, runparams, style);
617 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
619 // I did not create a parEndCommand for this minuscule
620 // task because in the other user of parStartCommand
621 // the code is different (JMarc)
622 if (style.isCommand())
626 if (!style.parbreak_is_newline) {
628 } else if (nextpar && !style.isEnvironment()) {
629 Layout const nextstyle = text.inset().forcePlainLayout()
630 ? bparams.documentClass().plainLayout()
632 if (nextstyle.name() != style.name())
639 // This paragraph's language
640 Language const * const par_language = par.getParLanguage(bparams);
641 // The document's language
642 Language const * const doc_language = bparams.language;
643 // The language that was in effect when the environment this paragraph is
644 // inside of was opened
645 Language const * const outer_language =
646 (runparams.local_font != 0) ?
647 runparams.local_font->language() : doc_language;
649 Paragraph const * priorpar = (pit == 0) ? 0 : ¶graphs.at(pit - 1);
651 // The previous language that was in effect is the language of the
652 // previous paragraph, unless the previous paragraph is inside an
653 // environment with nesting depth greater than (or equal to, but with
654 // a different layout) the current one. If there is no previous
655 // paragraph, the previous language is the outer language.
656 bool const use_prev_env_language = state->prev_env_language_ != 0
658 && priorpar->layout().isEnvironment()
659 && (priorpar->getDepth() > par.getDepth()
660 || (priorpar->getDepth() == par.getDepth()
661 && priorpar->layout() != par.layout()));
662 Language const * const prev_language =
664 ? (use_prev_env_language ? state->prev_env_language_
665 : priorpar->getParLanguage(bparams))
669 bool const use_polyglossia = runparams.use_polyglossia;
670 string const par_lang = use_polyglossia ?
671 getPolyglossiaEnvName(par_language): par_language->babel();
672 string const prev_lang = use_polyglossia ?
673 getPolyglossiaEnvName(prev_language) : prev_language->babel();
674 string const doc_lang = use_polyglossia ?
675 getPolyglossiaEnvName(doc_language) : doc_language->babel();
676 string const outer_lang = use_polyglossia ?
677 getPolyglossiaEnvName(outer_language) : outer_language->babel();
678 string lang_begin_command = use_polyglossia ?
679 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
680 string lang_end_command = use_polyglossia ?
681 "\\end{$$lang}" : lyxrc.language_command_end;
682 // the '%' is necessary to prevent unwanted whitespace
683 string lang_command_termination = "%\n";
685 // In some insets (such as Arguments), we cannot use \selectlanguage
686 bool const localswitch = text.inset().forceLocalFontSwitch();
688 lang_begin_command = use_polyglossia ?
689 "\\text$$lang$$opts{" : lyxrc.language_command_local;
690 lang_end_command = "}";
691 lang_command_termination.clear();
694 if (par_lang != prev_lang
695 // check if we already put language command in TeXEnvironment()
696 && !(style.isEnvironment()
697 && (pit == 0 || (priorpar->layout() != par.layout()
698 && priorpar->getDepth() <= par.getDepth())
699 || priorpar->getDepth() < par.getDepth())))
701 if (!lang_end_command.empty() &&
702 prev_lang != outer_lang &&
705 os << from_ascii(subst(lang_end_command,
708 << lang_command_termination;
711 // We need to open a new language if we couldn't close the previous
712 // one (because there's no language_command_end); and even if we closed
713 // the previous one, if the current language is different than the
714 // outer_language (which is currently in effect once the previous one
716 if ((lang_end_command.empty() || par_lang != outer_lang)
717 && !par_lang.empty()) {
718 // If we're inside an inset, and that inset is within an \L or \R
719 // (or equivalents), then within the inset, too, any opposite
720 // language paragraph should appear within an \L or \R (in addition
721 // to, outside of, the normal language switch commands).
722 // This behavior is not correct for ArabTeX, though.
725 && par_language->lang() != "arabic_arabtex"
726 && outer_language->lang() != "arabic_arabtex"
727 // are we in an inset?
728 && runparams.local_font != 0
729 // is the inset within an \L or \R?
731 // FIXME: currently, we don't check this; this means that
732 // we'll have unnnecessary \L and \R commands, but that
733 // doesn't seem to hurt (though latex will complain)
735 // is this paragraph in the opposite direction?
736 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
737 // FIXME: I don't have a working copy of the Arabi package, so
738 // I'm not sure if the farsi and arabic_arabi stuff is correct
740 if (par_language->lang() == "farsi")
742 else if (outer_language->lang() == "farsi")
744 else if (par_language->lang() == "arabic_arabi")
746 else if (outer_language->lang() == "arabic_arabi")
748 // remaining RTL languages currently is hebrew
749 else if (par_language->rightToLeft())
754 // With CJK, the CJK tag has to be closed first (see below)
755 if (runparams.encoding->package() != Encoding::CJK
756 && !par_lang.empty()) {
757 string bc = use_polyglossia ?
758 getPolyglossiaBegin(lang_begin_command, par_lang, par_language->polyglossiaOpts())
759 : subst(lang_begin_command, "$$lang", par_lang);
761 os << lang_command_termination;
766 // Switch file encoding if necessary; no need to do this for "default"
767 // encoding, since this only affects the position of the outputted
768 // \inputencoding command; the encoding switch will occur when necessary
769 if (bparams.inputenc == "auto"
770 && runparams.encoding->package() != Encoding::none) {
771 // Look ahead for future encoding changes.
772 // We try to output them at the beginning of the paragraph,
773 // since the \inputencoding command is not allowed e.g. in
774 // sections. For this reason we only set runparams.moving_arg
775 // after checking for the encoding change, otherwise the
776 // change would be always avoided by switchEncoding().
777 for (pos_type i = 0; i < par.size(); ++i) {
778 char_type const c = par.getChar(i);
779 Encoding const * const encoding =
780 par.getFontSettings(bparams, i).language()->encoding();
781 if (encoding->package() != Encoding::CJK
782 && runparams.encoding->package() == Encoding::inputenc
787 // All characters before c are in the ASCII range, and
788 // c is non-ASCII (but no inset), so change the
789 // encoding to that required by the language of c.
790 // With CJK, only add switch if we have CJK content at the beginning
792 if (i != 0 && encoding->package() == Encoding::CJK)
795 pair<bool, int> enc_switch = switchEncoding(os.os(),
796 bparams, runparams, *encoding);
797 // the following is necessary after a CJK environment in a multilingual
798 // context (nesting issue).
799 if (par_language->encoding()->package() == Encoding::CJK
800 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
801 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
802 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
803 state->open_encoding_ = CJK;
805 if (encoding->package() != Encoding::none && enc_switch.first) {
806 if (enc_switch.second > 0) {
807 // the '%' is necessary to prevent unwanted whitespace
810 // With CJK, the CJK tag had to be closed first (see above)
811 if (runparams.encoding->package() == Encoding::CJK
812 && !par_lang.empty()) {
813 os << from_ascii(subst(
817 << lang_command_termination;
819 runparams.encoding = encoding;
825 runparams.moving_arg |= style.needprotect;
826 Encoding const * const prev_encoding = runparams.encoding;
828 bool const useSetSpace = bparams.documentClass().provides("SetSpace");
829 if (par.allowParagraphCustomization()) {
830 if (par.params().startOfAppendix()) {
831 os << "\n\\appendix\n";
834 if (!par.params().spacing().isDefault()
835 && (pit == 0 || !priorpar->hasSameLayout(par)))
837 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
841 if (style.isCommand()) {
846 parStartCommand(par, os, runparams, style);
847 Font const outerfont = text.outerFont(pit);
850 os << from_utf8(everypar);
851 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
853 // Make sure that \\par is done with the font of the last
854 // character if this has another size as the default.
855 // This is necessary because LaTeX (and LyX on the screen)
856 // calculates the space between the baselines according
857 // to this font. (Matthias)
859 // We must not change the font for the last paragraph
860 // of non-multipar insets, tabular cells or commands,
861 // since this produces unwanted whitespace.
863 Font const font = par.empty()
864 ? par.getLayoutFont(bparams, outerfont)
865 : par.getFont(bparams, par.size() - 1, outerfont);
867 bool const is_command = style.isCommand();
869 if (style.resfont.size() != font.fontInfo().size()
870 && (nextpar || maintext
871 || (text.inset().paragraphs().size() > 1
872 && text.inset().lyxCode() != CELL_CODE))
875 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
876 } else if (is_command) {
878 if (!style.postcommandargs().empty())
879 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
880 if (runparams.encoding != prev_encoding) {
881 runparams.encoding = prev_encoding;
882 if (!runparams.isFullUnicode())
883 os << setEncoding(prev_encoding->iconvName());
887 bool pending_newline = false;
888 bool unskip_newline = false;
889 switch (style.latextype) {
890 case LATEX_ITEM_ENVIRONMENT:
891 case LATEX_LIST_ENVIRONMENT:
892 if (nextpar && par.params().depth() < nextpar->params().depth())
893 pending_newline = true;
895 case LATEX_ENVIRONMENT: {
896 // if its the last paragraph of the current environment
897 // skip it otherwise fall through
899 && (nextpar->layout() != par.layout()
900 || nextpar->params().depth() != par.params().depth()))
904 // fall through possible
906 // we don't need it for the last paragraph!!!
908 pending_newline = true;
911 if (par.allowParagraphCustomization()) {
912 if (!par.params().spacing().isDefault()
913 && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
917 string const endtag =
918 par.params().spacing().writeEnvirEnd(useSetSpace);
919 if (prefixIs(endtag, "\\end{"))
922 os << from_ascii(endtag);
923 pending_newline = true;
927 // Closing the language is needed for the last paragraph; it is also
928 // needed if we're within an \L or \R that we may have opened above (not
929 // necessarily in this paragraph) and are about to close.
930 bool closing_rtl_ltr_environment = !use_polyglossia
932 && (par_language->lang() != "arabic_arabtex"
933 && outer_language->lang() != "arabic_arabtex")
934 // have we opened an \L or \R environment?
935 && runparams.local_font != 0
936 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
937 // are we about to close the language?
938 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
939 || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
941 if (closing_rtl_ltr_environment
942 || (runparams.isLastPar
943 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
944 || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
945 // Since \selectlanguage write the language to the aux file,
946 // we need to reset the language at the end of footnote or
952 // when the paragraph uses CJK, the language has to be closed earlier
953 if (font.language()->encoding()->package() != Encoding::CJK) {
954 if (lang_end_command.empty()) {
955 // If this is a child, we should restore the
956 // master language after the last paragraph.
957 Language const * const current_language =
958 (runparams.isLastPar && runparams.master_language)
959 ? runparams.master_language
961 string const current_lang = use_polyglossia
962 ? getPolyglossiaEnvName(current_language)
963 : current_language->babel();
964 if (!current_lang.empty()) {
965 string bc = use_polyglossia ?
966 getPolyglossiaBegin(lang_begin_command, current_lang,
967 current_language->polyglossiaOpts())
968 : subst(lang_begin_command, "$$lang", current_lang);
970 pending_newline = !localswitch;
971 unskip_newline = !localswitch;
973 } else if (!par_lang.empty()) {
974 // If we are in an environment, we have to close the "outer" language afterwards
975 if (!style.isEnvironment() || state->open_polyglossia_lang_ != par_lang) {
976 os << from_ascii(subst(
980 pending_newline = !localswitch;
981 unskip_newline = !localswitch;
986 if (closing_rtl_ltr_environment)
989 bool const last_was_separator =
990 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
992 if (pending_newline) {
994 // prevent unwanted whitespace
996 if (!os.afterParbreak() && !last_was_separator)
1000 // if this is a CJK-paragraph and the next isn't, close CJK
1001 // also if the next paragraph is a multilingual environment (because of nesting)
1003 && state->open_encoding_ == CJK
1004 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
1005 || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1006 // inbetween environments, CJK has to be closed later (nesting!)
1007 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1008 os << "\\end{CJK}\n";
1009 state->open_encoding_ = none;
1012 // If this is the last paragraph, close the CJK environment
1013 // if necessary. If it's an environment, we'll have to \end that first.
1014 if (runparams.isLastPar && !style.isEnvironment()) {
1015 switch (state->open_encoding_) {
1017 // do nothing at the end of child documents
1018 if (maintext && buf.masterBuffer() != &buf)
1022 os << "\n\\end{CJK}\n";
1026 state->open_encoding_ = none;
1031 state->open_encoding_ = none;
1041 // If this is the last paragraph, and a local_font was set upon entering
1042 // the inset, and we're using "auto" or "default" encoding, the encoding
1043 // should be set back to that local_font's encoding.
1044 // However, do not change the encoding when a fully unicode aware backend
1045 // such as XeTeX is used.
1046 if (runparams.isLastPar && runparams_in.local_font != 0
1047 && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1048 && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1049 && (!runparams.isFullUnicode())) {
1050 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1051 os << setEncoding(runparams_in.encoding->iconvName());
1053 // Otherwise, the current encoding should be set for the next paragraph.
1055 runparams_in.encoding = runparams.encoding;
1058 // we don't need a newline for the last paragraph!!!
1059 // Note from JMarc: we will re-add a \n explicitly in
1060 // TeXEnvironment, because it is needed in this case
1061 if (nextpar && !os.afterParbreak() && !last_was_separator) {
1062 // Make sure to start a new line
1064 Layout const & next_layout = nextpar->layout();
1065 // A newline '\n' is always output before a command,
1066 // so avoid doubling it.
1067 if (!next_layout.isCommand()) {
1068 // Here we now try to avoid spurious empty lines by
1069 // outputting a paragraph break only if: (case 1) the
1070 // paragraph style allows parbreaks and no \begin, \end
1071 // or \item tags are going to follow (i.e., if the next
1072 // isn't the first or the current isn't the last
1073 // paragraph of an environment or itemize) and the
1074 // depth and alignment of the following paragraph is
1075 // unchanged, or (case 2) the following is a
1076 // non-environment paragraph whose depth is increased
1077 // but whose alignment is unchanged, or (case 3) the
1078 // paragraph is not an environment and the next one is a
1079 // non-itemize-like env at lower depth, or (case 4) the
1080 // paragraph is a command not followed by an environment
1081 // and the alignment of the current and next paragraph
1082 // is unchanged, or (case 5) the current alignment is
1083 // changed and a standard paragraph follows.
1084 DocumentClass const & tclass = bparams.documentClass();
1085 if ((style == next_layout
1086 && !style.parbreak_is_newline
1087 && !text.inset().getLayout().parbreakIsNewline()
1088 && style.latextype != LATEX_ITEM_ENVIRONMENT
1089 && style.latextype != LATEX_LIST_ENVIRONMENT
1090 && style.align == par.getAlign()
1091 && nextpar->getDepth() == par.getDepth()
1092 && nextpar->getAlign() == par.getAlign())
1093 || (!next_layout.isEnvironment()
1094 && nextpar->getDepth() > par.getDepth()
1095 && nextpar->getAlign() == par.getAlign())
1096 || (!style.isEnvironment()
1097 && next_layout.latextype == LATEX_ENVIRONMENT
1098 && nextpar->getDepth() < par.getDepth())
1099 || (style.isCommand()
1100 && !next_layout.isEnvironment()
1101 && style.align == par.getAlign()
1102 && next_layout.align == nextpar->getAlign())
1103 || (style.align != par.getAlign()
1104 && tclass.isDefaultLayout(next_layout))) {
1110 LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1111 << &par << " next " << nextpar);
1117 // LaTeX all paragraphs
1118 void latexParagraphs(Buffer const & buf,
1121 OutputParams const & runparams,
1122 string const & everypar)
1124 LASSERT(runparams.par_begin <= runparams.par_end,
1125 { os << "% LaTeX Output Error\n"; return; } );
1127 BufferParams const & bparams = buf.params();
1129 bool const maintext = text.isMainText();
1130 bool const is_child = buf.masterBuffer() != &buf;
1132 // Open a CJK environment at the beginning of the main buffer
1133 // if the document's language is a CJK language
1134 // (but not in child documents)
1135 OutputState * state = getOutputState();
1136 if (maintext && !is_child
1137 && bparams.encoding().package() == Encoding::CJK) {
1138 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
1139 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1140 state->open_encoding_ = CJK;
1142 // if "auto begin" is switched off, explicitly switch the
1143 // language on at start
1144 string const mainlang = runparams.use_polyglossia
1145 ? getPolyglossiaEnvName(bparams.language)
1146 : bparams.language->babel();
1147 string const lang_begin_command = runparams.use_polyglossia ?
1148 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1150 if (maintext && !lyxrc.language_auto_begin &&
1151 !mainlang.empty()) {
1153 string bc = runparams.use_polyglossia ?
1154 getPolyglossiaBegin(lang_begin_command, mainlang,
1155 bparams.language->polyglossiaOpts())
1156 : subst(lang_begin_command, "$$lang", mainlang);
1161 ParagraphList const & paragraphs = text.paragraphs();
1163 if (runparams.par_begin == runparams.par_end) {
1164 // The full doc will be exported but it is easier to just rely on
1165 // runparams range parameters that will be passed TeXEnvironment.
1166 runparams.par_begin = 0;
1167 runparams.par_end = paragraphs.size();
1170 pit_type pit = runparams.par_begin;
1171 // lastpit is for the language check after the loop.
1172 pit_type lastpit = pit;
1173 // variables used in the loop:
1174 bool was_title = false;
1175 bool already_title = false;
1176 DocumentClass const & tclass = bparams.documentClass();
1178 for (; pit < runparams.par_end; ++pit) {
1180 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1182 // FIXME This check should not be needed. We should
1183 // perhaps issue an error if it is.
1184 Layout const & layout = text.inset().forcePlainLayout() ?
1185 tclass.plainLayout() : par->layout();
1187 if (layout.intitle) {
1188 if (already_title) {
1189 LYXERR0("Error in latexParagraphs: You"
1190 " should not mix title layouts"
1191 " with normal ones.");
1192 } else if (!was_title) {
1194 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1196 << from_ascii(tclass.titlename())
1200 } else if (was_title && !already_title) {
1201 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1202 os << "\\end{" << from_ascii(tclass.titlename())
1206 os << "\\" << from_ascii(tclass.titlename())
1209 already_title = true;
1214 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1215 // This is a standard top level paragraph, TeX it and continue.
1216 TeXOnePar(buf, text, pit, os, runparams, everypar);
1220 TeXEnvironmentData const data =
1221 prepareEnvironment(buf, text, par, os, runparams);
1222 // pit can be changed in TeXEnvironment.
1223 TeXEnvironment(buf, text, runparams, pit, os);
1224 finishEnvironment(os, runparams, data);
1227 if (pit == runparams.par_end) {
1228 // Make sure that the last paragraph is
1229 // correctly terminated (because TeXOnePar does
1230 // not add a \n in this case)
1234 // It might be that we only have a title in this document
1235 if (was_title && !already_title) {
1236 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1237 os << "\\end{" << from_ascii(tclass.titlename())
1240 os << "\\" << from_ascii(tclass.titlename())
1245 // if "auto end" is switched off, explicitly close the language at the end
1246 // but only if the last par is in a babel language
1247 string const lang_end_command = runparams.use_polyglossia ?
1248 "\\end{$$lang}" : lyxrc.language_command_end;
1249 if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1250 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1251 os << from_utf8(subst(lang_end_command,
1257 // If the last paragraph is an environment, we'll have to close
1258 // CJK at the very end to do proper nesting.
1259 if (maintext && !is_child && state->open_encoding_ == CJK) {
1260 os << "\\end{CJK}\n";
1261 state->open_encoding_ = none;
1263 // Likewise for polyglossia
1264 if (maintext && !is_child && state->open_polyglossia_lang_ != "") {
1265 os << "\\end{" << state->open_polyglossia_lang_ << "}\n";
1266 state->open_polyglossia_lang_ = "";
1269 // reset inherited encoding
1270 if (state->cjk_inherited_ > 0) {
1271 state->cjk_inherited_ -= 1;
1272 if (state->cjk_inherited_ == 0)
1273 state->open_encoding_ = CJK;
1278 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1279 OutputParams const & runparams, Encoding const & newEnc,
1282 Encoding const & oldEnc = *runparams.encoding;
1283 bool moving_arg = runparams.moving_arg;
1284 // If we switch from/to CJK, we need to switch anyway, despite custom inputenc
1285 bool const from_to_cjk =
1286 (oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1287 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK);
1288 if (!force && !from_to_cjk
1289 && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1290 return make_pair(false, 0);
1292 // Do nothing if the encoding is unchanged.
1293 if (oldEnc.name() == newEnc.name())
1294 return make_pair(false, 0);
1296 // FIXME We ignore encoding switches from/to encodings that do
1297 // neither support the inputenc package nor the CJK package here.
1298 // This does of course only work in special cases (e.g. switch from
1299 // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1300 // but it is the best we can do
1301 if (oldEnc.package() == Encoding::none
1302 || newEnc.package() == Encoding::none)
1303 return make_pair(false, 0);
1305 LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1306 << oldEnc.name() << " to " << newEnc.name());
1307 os << setEncoding(newEnc.iconvName());
1308 if (bparams.inputenc == "default")
1309 return make_pair(true, 0);
1311 docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1312 OutputState * state = getOutputState();
1313 switch (newEnc.package()) {
1314 case Encoding::none:
1315 case Encoding::japanese:
1316 // shouldn't ever reach here, see above
1317 return make_pair(true, 0);
1318 case Encoding::inputenc: {
1319 int count = inputenc_arg.length();
1320 if (oldEnc.package() == Encoding::CJK &&
1321 state->open_encoding_ == CJK) {
1323 state->open_encoding_ = none;
1326 else if (oldEnc.package() == Encoding::inputenc &&
1327 state->open_encoding_ == inputenc) {
1329 state->open_encoding_ = none;
1332 if (runparams.local_font != 0
1333 && oldEnc.package() == Encoding::CJK) {
1334 // within insets, \inputenc switches need
1335 // to be embraced within \bgroup...\egroup;
1339 state->open_encoding_ = inputenc;
1341 // with the japanese option, inputenc is omitted.
1342 if (runparams.use_japanese)
1343 return make_pair(true, count);
1344 os << "\\inputencoding{" << inputenc_arg << '}';
1345 return make_pair(true, count + 16);
1347 case Encoding::CJK: {
1348 int count = inputenc_arg.length();
1349 if (oldEnc.package() == Encoding::CJK &&
1350 state->open_encoding_ == CJK) {
1354 if (oldEnc.package() == Encoding::inputenc &&
1355 state->open_encoding_ == inputenc) {
1359 os << "\\begin{CJK}{" << inputenc_arg << "}{"
1360 << from_ascii(bparams.fonts_cjk) << "}";
1361 state->open_encoding_ = CJK;
1362 return make_pair(true, count + 15);
1365 // Dead code to avoid a warning:
1366 return make_pair(true, 0);