]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
Provide proper fallback if a bibliography processor is not found
[lyx.git] / src / output_latex.cpp
1 /**
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.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "BiblioInfo.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "Encoding.h"
19 #include "Font.h"
20 #include "InsetList.h"
21 #include "Language.h"
22 #include "LaTeXFeatures.h"
23 #include "Layout.h"
24 #include "LyXRC.h"
25 #include "OutputParams.h"
26 #include "Paragraph.h"
27 #include "ParagraphParameters.h"
28 #include "texstream.h"
29 #include "TextClass.h"
30
31 #include "insets/InsetBibitem.h"
32 #include "insets/InsetArgument.h"
33
34 #include "frontends/alert.h"
35
36 #include "support/lassert.h"
37 #include "support/convert.h"
38 #include "support/debug.h"
39 #include "support/lstrings.h"
40 #include "support/lyxalgo.h"
41 #include "support/textutils.h"
42 #include "support/gettext.h"
43
44 #include <QThreadStorage>
45
46 #include <list>
47 #include <stack>
48
49 using namespace std;
50 using namespace lyx::support;
51
52
53 namespace lyx {
54
55 namespace {
56
57 enum OpenEncoding {
58         none,
59         inputenc,
60         CJK
61 };
62
63
64 struct OutputState
65 {
66         OutputState() : open_encoding_(none), cjk_inherited_(0),
67                         prev_env_language_(0), nest_level_(0)
68         {
69         }
70         OpenEncoding open_encoding_;
71         int cjk_inherited_;
72         Language const * prev_env_language_;
73         int nest_level_;
74         stack<int> lang_switch_depth_;          // Both are always empty when
75         stack<string> open_polyglossia_lang_;   // not using polyglossia
76 };
77
78
79 OutputState * getOutputState()
80 {
81         // FIXME An instance of OutputState should be kept around for each export
82         //       instead of using local thread storage
83         static QThreadStorage<OutputState *> outputstate;
84         if (!outputstate.hasLocalData())
85                 outputstate.setLocalData(new OutputState);
86         return outputstate.localData();
87 }
88
89
90 string const & openLanguageName(OutputState const * state)
91 {
92         // Return a reference to the last active language opened with
93         // polyglossia or when using begin/end commands. If none or when
94         // using babel with only a begin command, return a reference to
95         // an empty string.
96
97         static string const empty;
98
99         return state->open_polyglossia_lang_.empty()
100                 ? empty
101                 : state->open_polyglossia_lang_.top();
102 }
103
104
105 bool atSameLastLangSwitchDepth(OutputState const * state)
106 {
107         // Return true if the actual nest level is the same at which the
108         // language was switched when using polyglossia or begin/end
109         // commands. Instead, return always true when using babel with
110         // only a begin command.
111
112         return state->lang_switch_depth_.size() == 0
113                         ? true
114                         : abs(state->lang_switch_depth_.top()) == state->nest_level_;
115 }
116
117
118 bool isLocalSwitch(OutputState const * state)
119 {
120         // Return true if the language was opened by a local command switch.
121
122         return state->lang_switch_depth_.size()
123                 && state->lang_switch_depth_.top() < 0;
124 }
125
126
127 bool langOpenedAtThisLevel(OutputState const * state)
128 {
129         // Return true if the language was opened at the current nesting level.
130
131         return state->lang_switch_depth_.size()
132                 && abs(state->lang_switch_depth_.top()) == state->nest_level_;
133 }
134
135
136 string const getPolyglossiaEnvName(Language const * lang)
137 {
138         string result = lang->polyglossia();
139         if (result == "arabic")
140                 // exceptional spelling; see polyglossia docs.
141                 result = "Arabic";
142         return result;
143 }
144
145
146 string const getPolyglossiaBegin(string const & lang_begin_command,
147                                  string const & lang, string const & opts,
148                                  bool const localswitch = false)
149 {
150         string result;
151         if (!lang.empty()) {
152                 // we need to revert the upcasing done in getPolyglossiaEnvName()
153                 // in case we have a local polyglossia command (\textarabic).
154                 string language = localswitch ? ascii_lowercase(lang) : lang;
155                 result = subst(lang_begin_command, "$$lang", language);
156         }
157         string options = opts.empty() ?
158                     string() : "[" + opts + "]";
159         result = subst(result, "$$opts", options);
160
161         return result;
162 }
163
164
165 struct TeXEnvironmentData
166 {
167         bool cjk_nested;
168         Layout const * style;
169         Language const * par_language;
170         Encoding const * prev_encoding;
171         bool leftindent_open;
172 };
173
174
175 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
176                                         Text const & text,
177                                         ParagraphList::const_iterator pit,
178                                         otexstream & os,
179                                         OutputParams const & runparams)
180 {
181         TeXEnvironmentData data;
182
183         BufferParams const & bparams = buf.params();
184
185         // FIXME This test should not be necessary.
186         // We should perhaps issue an error if it is.
187         Layout const & style = text.inset().forcePlainLayout() ?
188                 bparams.documentClass().plainLayout() : pit->layout();
189
190         ParagraphList const & paragraphs = text.paragraphs();
191         ParagraphList::const_iterator const priorpit =
192                 pit == paragraphs.begin() ? pit : prev(pit, 1);
193
194         OutputState * state = getOutputState();
195         bool const use_prev_env_language = state->prev_env_language_ != 0
196                         && priorpit->layout().isEnvironment()
197                         && (priorpit->getDepth() > pit->getDepth()
198                             || (priorpit->getDepth() == pit->getDepth()
199                                 && priorpit->layout() != pit->layout()));
200
201         data.prev_encoding = runparams.encoding;
202         data.par_language = pit->getParLanguage(bparams);
203         Language const * const doc_language = bparams.language;
204         Language const * const prev_par_language =
205                 (pit != paragraphs.begin())
206                 ? (use_prev_env_language ? state->prev_env_language_
207                                          : priorpit->getParLanguage(bparams))
208                 : doc_language;
209
210         bool const use_polyglossia = runparams.use_polyglossia;
211         string const par_lang = use_polyglossia ?
212                 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
213         string const prev_par_lang = use_polyglossia ?
214                 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
215         string const doc_lang = use_polyglossia ?
216                 getPolyglossiaEnvName(doc_language) : doc_language->babel();
217         string const lang_begin_command = use_polyglossia ?
218                 "\\begin{$$lang}" : lyxrc.language_command_begin;
219         string const lang_end_command = use_polyglossia ?
220                 "\\end{$$lang}" : lyxrc.language_command_end;
221         bool const using_begin_end = use_polyglossia ||
222                                         !lang_end_command.empty();
223
224         // For polyglossia, switch language outside of environment, if possible.
225         if (par_lang != prev_par_lang) {
226                 if ((!using_begin_end || langOpenedAtThisLevel(state)) &&
227                     !lang_end_command.empty() &&
228                     prev_par_lang != doc_lang &&
229                     !prev_par_lang.empty()) {
230                         os << from_ascii(subst(
231                                 lang_end_command,
232                                 "$$lang",
233                                 prev_par_lang))
234                           // the '%' is necessary to prevent unwanted whitespace
235                           << "%\n";
236                         if (using_begin_end)
237                                 popLanguageName();
238                 }
239
240                 // If no language was explicitly opened and we are using
241                 // polyglossia or begin/end commands, then the current
242                 // language is the document language.
243                 string const & cur_lang = using_begin_end
244                                           && state->lang_switch_depth_.size()
245                                                   ? openLanguageName(state)
246                                                   : doc_lang;
247
248                 if ((lang_end_command.empty() ||
249                     par_lang != doc_lang ||
250                     par_lang != cur_lang) &&
251                     !par_lang.empty()) {
252                             string bc = use_polyglossia ?
253                                         getPolyglossiaBegin(lang_begin_command, par_lang,
254                                                             data.par_language->polyglossiaOpts())
255                                       : subst(lang_begin_command, "$$lang", par_lang);
256                             os << bc;
257                             // the '%' is necessary to prevent unwanted whitespace
258                             os << "%\n";
259                             if (using_begin_end)
260                                     pushLanguageName(par_lang);
261                 }
262         }
263
264         data.leftindent_open = false;
265         if (!pit->params().leftIndent().zero()) {
266                 os << "\\begin{LyXParagraphLeftIndent}{"
267                    << from_ascii(pit->params().leftIndent().asLatexString())
268                    << "}\n";
269                 data.leftindent_open = true;
270         }
271
272         if (style.isEnvironment())
273                 state->nest_level_ += 1;
274
275         if (style.isEnvironment() && !style.latexname().empty()) {
276                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
277                 if (!style.latexargs().empty()) {
278                         OutputParams rp = runparams;
279                         rp.local_font = &pit->getFirstFontSettings(bparams);
280                         latexArgInsets(paragraphs, pit, os, rp, style.latexargs());
281                 }
282                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
283                         os << '{'
284                            << pit->params().labelWidthString()
285                            << "}\n";
286                 } else if (style.labeltype == LABEL_BIBLIO) {
287                         if (pit->params().labelWidthString().empty())
288                                 os << '{' << bibitemWidest(buf, runparams) << "}\n";
289                         else
290                                 os << '{'
291                                   << pit->params().labelWidthString()
292                                   << "}\n";
293                 } else
294                         os << from_ascii(style.latexparam()) << '\n';
295         }
296         data.style = &style;
297
298         // in multilingual environments, the CJK tags have to be nested properly
299         data.cjk_nested = false;
300         if (data.par_language->encoding()->package() == Encoding::CJK &&
301             state->open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
302                 if (prev_par_language->encoding()->package() == Encoding::CJK) {
303                         docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
304                                                   && LaTeXFeatures::isAvailable("CJKutf8")) ?
305                                                         from_ascii("UTF8")
306                                                       : from_ascii(data.par_language->encoding()->latexName());
307                         os << "\\begin{CJK}{" << cjkenc
308                            << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
309                 }
310                 state->open_encoding_ = CJK;
311                 data.cjk_nested = true;
312         }
313         return data;
314 }
315
316
317 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
318                               TeXEnvironmentData const & data)
319 {
320         OutputState * state = getOutputState();
321         // BufferParams const & bparams = buf.params(); // FIXME: for speedup shortcut below, would require passing of "buf" as argument
322         if (state->open_encoding_ == CJK && data.cjk_nested) {
323                 // We need to close the encoding even if it does not change
324                 // to do correct environment nesting
325                 os << "\\end{CJK}\n";
326                 state->open_encoding_ = none;
327         }
328
329         if (data.style->isEnvironment()) {
330                 os << breakln;
331                 bool const using_begin_end =
332                         runparams.use_polyglossia ||
333                                 !lyxrc.language_command_end.empty();
334                 // Close any language opened at this nest level
335                 if (using_begin_end) {
336                         while (langOpenedAtThisLevel(state)) {
337                                 if (isLocalSwitch(state)) {
338                                         os << "}";
339                                 } else {
340                                         os << "\\end{"
341                                            << openLanguageName(state)
342                                            << "}%\n";
343                                 }
344                                 popLanguageName();
345                         }
346                 }
347                 if (data.style->latextype == LATEX_BIB_ENVIRONMENT)
348                         // bibliography needs a blank line after
349                         // each item for backref to function properly
350                         // (see #12041)
351                         os << '\n';
352                 state->nest_level_ -= 1;
353                 string const & name = data.style->latexname();
354                 if (!name.empty())
355                         os << "\\end{" << from_ascii(name) << "}\n";
356                 state->prev_env_language_ = data.par_language;
357                 if (runparams.encoding != data.prev_encoding) {
358                         runparams.encoding = data.prev_encoding;
359                         os << setEncoding(data.prev_encoding->iconvName());
360                 }
361         }
362
363         if (data.leftindent_open) {
364                 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
365                 state->prev_env_language_ = data.par_language;
366                 if (runparams.encoding != data.prev_encoding) {
367                         runparams.encoding = data.prev_encoding;
368                         os << setEncoding(data.prev_encoding->iconvName());
369                 }
370         }
371
372         // Check whether we should output a blank line after the environment
373         if (!data.style->nextnoindent)
374                 os << '\n';
375 }
376
377
378 void TeXEnvironment(Buffer const & buf, Text const & text,
379                     OutputParams const & runparams,
380                     pit_type & pit, otexstream & os)
381 {
382         ParagraphList const & paragraphs = text.paragraphs();
383         ParagraphList::const_iterator par = paragraphs.constIterator(pit);
384         LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
385
386         Layout const & current_layout = par->layout();
387         depth_type const current_depth = par->params().depth();
388         Length const & current_left_indent = par->params().leftIndent();
389
390         // This is for debugging purpose at the end.
391         pit_type const par_begin = pit;
392         for (; pit < runparams.par_end; ++pit) {
393                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
394
395                 // check first if this is an higher depth paragraph.
396                 bool go_out = (par->params().depth() < current_depth);
397                 if (par->params().depth() == current_depth) {
398                         // This environment is finished.
399                         go_out |= (par->layout() != current_layout);
400                         go_out |= (par->params().leftIndent() != current_left_indent);
401                 }
402                 if (go_out) {
403                         // nothing to do here, restore pit and go out.
404                         pit--;
405                         break;
406                 }
407
408                 if (par->layout() == current_layout
409                         && par->params().depth() == current_depth
410                         && par->params().leftIndent() == current_left_indent) {
411                         // We are still in the same environment so TeXOnePar and continue;
412                         TeXOnePar(buf, text, pit, os, runparams);
413                         continue;
414                 }
415
416                 // We are now in a deeper environment.
417                 // Either par->layout() != current_layout
418                 // Or     par->params().depth() > current_depth
419                 // Or     par->params().leftIndent() != current_left_indent)
420
421                 // FIXME This test should not be necessary.
422                 // We should perhaps issue an error if it is.
423                 bool const force_plain_layout = text.inset().forcePlainLayout();
424                 Layout const & style = force_plain_layout
425                         ? buf.params().documentClass().plainLayout()
426                         : par->layout();
427
428                 if (!style.isEnvironment()) {
429                         // This is a standard paragraph, no need to call TeXEnvironment.
430                         TeXOnePar(buf, text, pit, os, runparams);
431                         continue;
432                 }
433
434                 // This is a new environment.
435                 TeXEnvironmentData const data =
436                         prepareEnvironment(buf, text, par, os, runparams);
437                 // Recursive call to TeXEnvironment!
438                 TeXEnvironment(buf, text, runparams, pit, os);
439                 finishEnvironment(os, runparams, data);
440         }
441
442         if (pit != runparams.par_end)
443                 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
444 }
445
446
447 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
448                   map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
449 {
450         unsigned int const argnr = latexargs.size();
451         if (argnr == 0)
452                 return;
453
454         // Default and preset args are always output, so if they require
455         // other arguments, consider this.
456         Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
457         Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
458         for (; lit != lend; ++lit) {
459                 Layout::latexarg arg = (*lit).second;
460                 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
461                                 vector<string> req = getVectorFromString(arg.requires);
462                                 required.insert(required.end(), req.begin(), req.end());
463                         }
464         }
465
466         for (unsigned int i = 1; i <= argnr; ++i) {
467                 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
468                 bool inserted = false;
469                 if (lit != ilist.end()) {
470                         InsetArgument const * ins = (*lit).second;
471                         if (ins) {
472                                 Layout::LaTeXArgMap::const_iterator const lait =
473                                                 latexargs.find(ins->name());
474                                 if (lait != latexargs.end()) {
475                                         Layout::latexarg arg = (*lait).second;
476                                         docstring ldelim = arg.mandatory ?
477                                                         from_ascii("{") : from_ascii("[");
478                                         docstring rdelim = arg.mandatory ?
479                                                         from_ascii("}") : from_ascii("]");
480                                         if (!arg.ldelim.empty())
481                                                 ldelim = arg.ldelim;
482                                         if (!arg.rdelim.empty())
483                                                 rdelim = arg.rdelim;
484                                         ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
485                                         inserted = true;
486                                 }
487                         }
488                 }
489                 if (!inserted) {
490                         Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
491                         Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
492                         for (; lait != laend; ++lait) {
493                                 string const name = prefix + convert<string>(i);
494                                 if ((*lait).first == name) {
495                                         Layout::latexarg arg = (*lait).second;
496                                         docstring preset = arg.presetarg;
497                                         if (!arg.defaultarg.empty()) {
498                                                 if (!preset.empty())
499                                                         preset += ",";
500                                                 preset += arg.defaultarg;
501                                         }
502                                         if (arg.mandatory) {
503                                                 docstring ldelim = arg.ldelim.empty() ?
504                                                                 from_ascii("{") : arg.ldelim;
505                                                 docstring rdelim = arg.rdelim.empty() ?
506                                                                 from_ascii("}") : arg.rdelim;
507                                                 os << ldelim << preset << rdelim;
508                                         } else if (!preset.empty()) {
509                                                 docstring ldelim = arg.ldelim.empty() ?
510                                                                 from_ascii("[") : arg.ldelim;
511                                                 docstring rdelim = arg.rdelim.empty() ?
512                                                                 from_ascii("]") : arg.rdelim;
513                                                 os << ldelim << preset << rdelim;
514                                         } else if (find(required.begin(), required.end(),
515                                                    (*lait).first) != required.end()) {
516                                                 docstring ldelim = arg.ldelim.empty() ?
517                                                                 from_ascii("[") : arg.ldelim;
518                                                 docstring rdelim = arg.rdelim.empty() ?
519                                                                 from_ascii("]") : arg.rdelim;
520                                                 os << ldelim << rdelim;
521                                         } else
522                                                 break;
523                                 }
524                         }
525                 }
526         }
527 }
528
529
530 } // namespace
531
532
533 void pushLanguageName(string const & lang_name, bool localswitch)
534 {
535         OutputState * state = getOutputState();
536
537         int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
538         state->lang_switch_depth_.push(nest_level);
539         state->open_polyglossia_lang_.push(lang_name);
540 }
541
542
543 void popLanguageName()
544 {
545         OutputState * state = getOutputState();
546
547         state->lang_switch_depth_.pop();
548         state->open_polyglossia_lang_.pop();
549 }
550
551
552 string const & openLanguageName()
553 {
554         OutputState * state = getOutputState();
555
556         return openLanguageName(state);
557 }
558
559
560 namespace {
561
562 void addArgInsets(Paragraph const & par, string const & prefix,
563                  Layout::LaTeXArgMap const & latexargs,
564                  map<int, InsetArgument const *> & ilist,
565                  vector<string> & required)
566 {
567         for (auto const & table : par.insetList()) {
568                 InsetArgument const * arg = table.inset->asInsetArgument();
569                 if (!arg)
570                         continue;
571                 if (arg->name().empty()) {
572                         LYXERR0("Error: Unnamed argument inset!");
573                         continue;
574                 }
575                 string const name = prefix.empty() ?
576                         arg->name() : split(arg->name(), ':');
577                 // why converting into an integer?
578                 unsigned int const nr = convert<unsigned int>(name);
579                 if (ilist.find(nr) == ilist.end())
580                         ilist[nr] = arg;
581                 Layout::LaTeXArgMap::const_iterator const lit =
582                         latexargs.find(arg->name());
583                 if (lit != latexargs.end()) {
584                         Layout::latexarg const & larg = lit->second;
585                         vector<string> req = getVectorFromString(larg.requires);
586                         move(req.begin(), req.end(), back_inserter(required));
587                 }
588         }
589 }
590
591 } // namespace
592
593
594 void latexArgInsets(Paragraph const & par, otexstream & os,
595                     OutputParams const & runparams,
596                     Layout::LaTeXArgMap const & latexargs,
597                     string const & prefix)
598 {
599         map<int, InsetArgument const *> ilist;
600         vector<string> required;
601         addArgInsets(par, prefix, latexargs, ilist, required);
602         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
603 }
604
605
606 void latexArgInsets(ParagraphList const & pars,
607                     ParagraphList::const_iterator pit,
608                     otexstream & os, OutputParams const & runparams,
609                     Layout::LaTeXArgMap const & latexargs,
610                     string const & prefix)
611 {
612         map<int, InsetArgument const *> ilist;
613         vector<string> required;
614
615         depth_type const current_depth = pit->params().depth();
616         Layout const current_layout = pit->layout();
617
618         // get the first paragraph in sequence with this layout and depth
619         pit_type offset = 0;
620         while (true) {
621                 if (lyx::prev(pit, offset) == pars.begin())
622                         break;
623                 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
624                 if (priorpit->layout() == current_layout
625                     && priorpit->params().depth() == current_depth)
626                         ++offset;
627                 else
628                         break;
629         }
630
631         ParagraphList::const_iterator spit = lyx::prev(pit, offset);
632
633         for (; spit != pars.end(); ++spit) {
634                 if (spit->layout() != current_layout ||
635                     spit->params().depth() < current_depth)
636                         break;
637                 if (spit->params().depth() > current_depth)
638                         continue;
639                 addArgInsets(*spit, prefix, latexargs, ilist, required);
640         }
641         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
642 }
643
644
645 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
646                              OutputParams const & runparams,
647                              Layout::LaTeXArgMap const & latexargs,
648                              string const & prefix)
649 {
650         map<int, InsetArgument const *> ilist;
651         vector<string> required;
652
653         for (Paragraph const & par : pars) {
654                 if (par.layout().hasArgs())
655                         // The InsetArguments inside this paragraph refer to this paragraph
656                         continue;
657                 addArgInsets(par, prefix, latexargs, ilist, required);
658         }
659         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
660 }
661
662
663 namespace {
664
665 // output the proper paragraph start according to latextype.
666 void parStartCommand(Paragraph const & par, otexstream & os,
667                      OutputParams const & runparams, Layout const & style)
668 {
669         switch (style.latextype) {
670         case LATEX_COMMAND:
671                 os << '\\' << from_ascii(style.latexname());
672
673                 // Command arguments
674                 if (!style.latexargs().empty())
675                         latexArgInsets(par, os, runparams, style.latexargs());
676                 os << from_ascii(style.latexparam());
677                 break;
678         case LATEX_ITEM_ENVIRONMENT:
679         case LATEX_LIST_ENVIRONMENT:
680                 os << "\\" + style.itemcommand();
681                 // Item arguments
682                 if (!style.itemargs().empty())
683                         latexArgInsets(par, os, runparams, style.itemargs(), "item:");
684                 os << " ";
685                 break;
686         case LATEX_BIB_ENVIRONMENT:
687                 // ignore this, the inset will write itself
688                 break;
689         default:
690                 break;
691         }
692 }
693
694 } // namespace
695
696 // FIXME: this should be anonymous
697 void TeXOnePar(Buffer const & buf,
698                Text const & text,
699                pit_type pit,
700                otexstream & os,
701                OutputParams const & runparams_in,
702                string const & everypar,
703                int start_pos, int end_pos,
704                bool const force)
705 {
706         BufferParams const & bparams = runparams_in.is_child
707                 ? buf.masterParams() : buf.params();
708         ParagraphList const & paragraphs = text.paragraphs();
709         Paragraph const & par = paragraphs.at(pit);
710         // FIXME This check should not really be needed.
711         // Perhaps we should issue an error if it is.
712         Layout const & style = text.inset().forcePlainLayout() ?
713                 bparams.documentClass().plainLayout() : par.layout();
714
715         if (style.inpreamble && !force)
716                 return;
717
718         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
719                 << everypar << "'");
720
721         OutputParams runparams = runparams_in;
722         runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
723         // We reinitialze par begin and end to be on the safe side
724         // with embedded inset as we don't know if they set those
725         // value correctly.
726         runparams.par_begin = 0;
727         runparams.par_end = 0;
728
729         bool const maintext = text.isMainText();
730         // we are at the beginning of an inset and CJK is already open;
731         // we count inheritation levels to get the inset nesting right.
732         OutputState * state = getOutputState();
733         if (pit == 0 && !maintext
734             && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
735                 state->cjk_inherited_ += 1;
736                 state->open_encoding_ = none;
737         }
738
739         if (text.inset().isPassThru()) {
740                 Font const outerfont = text.outerFont(pit);
741
742                 // No newline before first paragraph in this lyxtext
743                 if (pit > 0) {
744                         os << '\n';
745                         if (!text.inset().getLayout().parbreakIsNewline())
746                                 os << '\n';
747                 }
748
749                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
750                 return;
751         }
752
753         Paragraph const * nextpar = runparams.isLastPar
754                 ? 0 : &paragraphs.at(pit + 1);
755
756         bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
757         // Intitle commands switch languages locally, thus increase
758         // language nesting level
759         if (intitle_command)
760                 state->nest_level_ += 1;
761
762         if (style.pass_thru) {
763                 Font const outerfont = text.outerFont(pit);
764                 parStartCommand(par, os, runparams, style);
765                 if (intitle_command)
766                         os << '{';
767
768                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
769
770                 // I did not create a parEndCommand for this minuscule
771                 // task because in the other user of parStartCommand
772                 // the code is different (JMarc)
773                 if (style.isCommand())
774                         os << "}\n";
775                 else
776                         os << '\n';
777                 if (!style.parbreak_is_newline) {
778                         os << '\n';
779                 } else if (nextpar && !style.isEnvironment()) {
780                         Layout const nextstyle = text.inset().forcePlainLayout()
781                                 ? bparams.documentClass().plainLayout()
782                                 : nextpar->layout();
783                         if (nextstyle.name() != style.name())
784                                 os << '\n';
785                 }
786
787                 return;
788         }
789
790         // This paragraph's language
791         Language const * const par_language = par.getParLanguage(bparams);
792         Language const * const nextpar_language = nextpar ?
793                 nextpar->getParLanguage(bparams) : 0;
794         // The document's language
795         Language const * const doc_language = bparams.language;
796         // The language that was in effect when the environment this paragraph is
797         // inside of was opened
798         Language const * const outer_language =
799                 (runparams.local_font != 0) ?
800                         runparams.local_font->language() : doc_language;
801
802         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
803
804         // The previous language that was in effect is the language of the
805         // previous paragraph, unless the previous paragraph is inside an
806         // environment with nesting depth greater than (or equal to, but with
807         // a different layout) the current one. If there is no previous
808         // paragraph, the previous language is the outer language.
809         // Note further that we take the outer language also if the prior par
810         // is PassThru, since in that case it has latex_language, and all secondary
811         // languages have been closed (#10793).
812         bool const use_prev_env_language = state->prev_env_language_ != 0
813                         && priorpar
814                         && priorpar->layout().isEnvironment()
815                         && (priorpar->getDepth() > par.getDepth()
816                             || (priorpar->getDepth() == par.getDepth()
817                                     && priorpar->layout() != par.layout()));
818
819         // We need to ignore previous intitle commands since languages
820         // are switched locally there (# 11514)
821         // There might be paragraphs before the title, so we check this.
822         Paragraph * prior_nontitle_par = nullptr;
823         if (!intitle_command) {
824                 pit_type ppit = pit;
825                 while (ppit > 0) {
826                         --ppit;
827                         Paragraph const * tmppar = &paragraphs.at(ppit);
828                         if (tmppar->layout().intitle && tmppar->layout().isCommand())
829                                 continue;
830                         prior_nontitle_par = const_cast<Paragraph*>(tmppar);
831                         break;
832                 }
833         }
834         Language const * const prev_language =
835                 runparams_in.for_search 
836                         ? languages.getLanguage("ignore")
837                         : (prior_nontitle_par && !prior_nontitle_par->isPassThru())
838                                 ? (use_prev_env_language 
839                                         ? state->prev_env_language_
840                                         : prior_nontitle_par->getParLanguage(bparams))
841                                 : outer_language;
842
843         bool const use_polyglossia = runparams.use_polyglossia;
844         string const par_lang = use_polyglossia ?
845                 getPolyglossiaEnvName(par_language): par_language->babel();
846         string const prev_lang = use_polyglossia ?
847                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
848         string const outer_lang = use_polyglossia ?
849                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
850         string const nextpar_lang = nextpar_language ? (use_polyglossia ?
851                 getPolyglossiaEnvName(nextpar_language) :
852                 nextpar_language->babel()) : string();
853         string lang_begin_command = use_polyglossia ?
854                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
855         string lang_end_command = use_polyglossia ?
856                 "\\end{$$lang}" : lyxrc.language_command_end;
857         // the '%' is necessary to prevent unwanted whitespace
858         string lang_command_termination = "%\n";
859         bool const using_begin_end = use_polyglossia ||
860                                         !lang_end_command.empty();
861
862         // For InTitle commands, we need to switch the language inside the command
863         // (see #10849); thus open the command here.
864         if (intitle_command) {
865                 parStartCommand(par, os, runparams, style);
866                 os << '{';
867         }
868
869         // In some insets (such as Arguments), we cannot use \selectlanguage.
870         // Also, if an RTL language is set via environment in polyglossia,
871         // only a nested \\text<lang> command will reset the direction for LTR
872         // languages (see # 10111).
873         bool const in_polyglossia_rtl_env =
874                 use_polyglossia
875                 && runparams.local_font != 0
876                 && outer_language->rightToLeft()
877                 && !par_language->rightToLeft();
878         bool const localswitch = text.inset().forceLocalFontSwitch()
879                         || (using_begin_end && text.inset().forcePlainLayout())
880                         || in_polyglossia_rtl_env;
881         if (localswitch) {
882                 lang_begin_command = use_polyglossia ?
883                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
884                 lang_end_command = "}";
885                 lang_command_termination.clear();
886         }
887         
888         bool const localswitch_needed = localswitch && par_lang != outer_lang;
889
890         // localswitches need to be closed and reopened at each par
891         if ((par_lang != prev_lang || localswitch_needed)
892              // check if we already put language command in TeXEnvironment()
893              && !(style.isEnvironment()
894                   && (pit == 0 || (priorpar->layout() != par.layout()
895                                    && priorpar->getDepth() <= par.getDepth())
896                       || priorpar->getDepth() < par.getDepth()))) {
897                 if (!localswitch
898                     && (!using_begin_end || langOpenedAtThisLevel(state))
899                     && !lang_end_command.empty()
900                     && prev_lang != outer_lang 
901                     && !prev_lang.empty()
902                     && (!using_begin_end || !style.isEnvironment())) {
903                         os << from_ascii(subst(lang_end_command,
904                                                "$$lang",
905                                                prev_lang))
906                            << lang_command_termination;
907                         if (using_begin_end)
908                                 popLanguageName();
909                 }
910
911                 // We need to open a new language if we couldn't close the previous
912                 // one (because there's no language_command_end); and even if we closed
913                 // the previous one, if the current language is different than the
914                 // outer_language (which is currently in effect once the previous one
915                 // is closed).
916                 if ((lang_end_command.empty() || par_lang != outer_lang
917                      || (!using_begin_end
918                          || (style.isEnvironment() && par_lang != prev_lang)))
919                         && !par_lang.empty()) {
920                         // If we're inside an inset, and that inset is within an \L or \R
921                         // (or equivalents), then within the inset, too, any opposite
922                         // language paragraph should appear within an \L or \R (in addition
923                         // to, outside of, the normal language switch commands).
924                         // This behavior is not correct for ArabTeX, though.
925                         if (!using_begin_end
926                             // not for ArabTeX
927                                 && par_language->lang() != "arabic_arabtex"
928                                 && outer_language->lang() != "arabic_arabtex"
929                             // are we in an inset?
930                             && runparams.local_font != 0
931                             // is the inset within an \L or \R?
932                             //
933                             // FIXME: currently, we don't check this; this means that
934                             // we'll have unnnecessary \L and \R commands, but that
935                             // doesn't seem to hurt (though latex will complain)
936                             //
937                             // is this paragraph in the opposite direction?
938                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
939                                 // FIXME: I don't have a working copy of the Arabi package, so
940                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
941                                 // or not...
942                                 if (par_language->lang() == "farsi")
943                                         os << "\\textFR{";
944                                 else if (outer_language->lang() == "farsi")
945                                         os << "\\textLR{";
946                                 else if (par_language->lang() == "arabic_arabi")
947                                         os << "\\textAR{";
948                                 else if (outer_language->lang() == "arabic_arabi")
949                                         os << "\\textLR{";
950                                 // remaining RTL languages currently is hebrew
951                                 else if (par_language->rightToLeft())
952                                         os << "\\R{";
953                                 else
954                                         os << "\\L{";
955                         }
956                         // With CJK, the CJK tag has to be closed first (see below)
957                         if (runparams.encoding->package() != Encoding::CJK
958                             && (par_lang != openLanguageName(state) || localswitch || intitle_command)
959                             && !par_lang.empty()) {
960                                 string bc = use_polyglossia ?
961                                           getPolyglossiaBegin(lang_begin_command, par_lang,
962                                                               par_language->polyglossiaOpts(),
963                                                               localswitch)
964                                           : subst(lang_begin_command, "$$lang", par_lang);
965                                 os << bc;
966                                 os << lang_command_termination;
967                                 if (using_begin_end)
968                                         pushLanguageName(par_lang, localswitch);
969                         }
970                 }
971         }
972
973         // Switch file encoding if necessary; no need to do this for "default"
974         // encoding, since this only affects the position of the outputted
975         // \inputencoding command; the encoding switch will occur when necessary
976         if (bparams.inputenc == "auto"
977                 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding  (see also switchEncoding())
978                 && runparams.encoding->package() != Encoding::none) {
979                 // Look ahead for future encoding changes.
980                 // We try to output them at the beginning of the paragraph,
981                 // since the \inputencoding command is not allowed e.g. in
982                 // sections. For this reason we only set runparams.moving_arg
983                 // after checking for the encoding change, otherwise the
984                 // change would be always avoided by switchEncoding().
985                 for (pos_type i = 0; i < par.size(); ++i) {
986                         char_type const c = par.getChar(i);
987                         Encoding const * const encoding =
988                                 par.getFontSettings(bparams, i).language()->encoding();
989                         if (encoding->package() != Encoding::CJK
990                                 && runparams.encoding->package() == Encoding::inputenc
991                                 && isASCII(c))
992                                 continue;
993                         if (par.isInset(i))
994                                 break;
995                         // All characters before c are in the ASCII range, and
996                         // c is non-ASCII (but no inset), so change the
997                         // encoding to that required by the language of c.
998                         // With CJK, only add switch if we have CJK content at the beginning
999                         // of the paragraph
1000                         if (i != 0 && encoding->package() == Encoding::CJK)
1001                                 continue;
1002
1003                         pair<bool, int> enc_switch = switchEncoding(os.os(),
1004                                                 bparams, runparams, *encoding);
1005                         // the following is necessary after a CJK environment in a multilingual
1006                         // context (nesting issue).
1007                         if (par_language->encoding()->package() == Encoding::CJK
1008                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1009                                 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1010                                                           && LaTeXFeatures::isAvailable("CJKutf8")) ?
1011                                                                 from_ascii("UTF8")
1012                                                               : from_ascii(par_language->encoding()->latexName());
1013                                 os << "\\begin{CJK}{" << cjkenc
1014                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1015                                 state->open_encoding_ = CJK;
1016                         }
1017                         if (encoding->package() != Encoding::none && enc_switch.first) {
1018                                 if (enc_switch.second > 0) {
1019                                         // the '%' is necessary to prevent unwanted whitespace
1020                                         os << "%\n";
1021                                 }
1022                                 // With CJK, the CJK tag had to be closed first (see above)
1023                                 if (runparams.encoding->package() == Encoding::CJK
1024                                     && par_lang != openLanguageName(state)
1025                                     && !par_lang.empty()) {
1026                                         string bc = use_polyglossia ?
1027                                                     getPolyglossiaBegin(lang_begin_command, par_lang,
1028                                                                         par_language->polyglossiaOpts(),
1029                                                                         localswitch)
1030                                                     : subst(lang_begin_command, "$$lang", par_lang);
1031                                         os << bc
1032                                            << lang_command_termination;
1033                                         if (using_begin_end)
1034                                                 pushLanguageName(par_lang, localswitch);
1035                                 }
1036                                 runparams.encoding = encoding;
1037                         }
1038                         break;
1039                 }
1040         }
1041
1042         runparams.moving_arg |= style.needprotect;
1043         Encoding const * const prev_encoding = runparams.encoding;
1044
1045         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
1046         if (par.allowParagraphCustomization()) {
1047                 if (par.params().startOfAppendix()) {
1048                         os << "\n\\appendix\n";
1049                 }
1050
1051                 // InTitle commands must use switches (not environments)
1052                 // inside the commands (see #9332)
1053                 if (style.intitle) {
1054                         if (!par.params().spacing().isDefault())
1055                         {
1056                                 if (runparams.moving_arg)
1057                                         os << "\\protect";
1058                                 os << from_ascii(par.params().spacing().writeCmd(useSetSpace));
1059                         }
1060                 } else {
1061                         if (!par.params().spacing().isDefault()
1062                                 && (pit == 0 || !priorpar->hasSameLayout(par)))
1063                         {
1064                                 os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
1065                                     << '\n';
1066                         }
1067
1068                         if (style.isCommand()) {
1069                                 os << '\n';
1070                         }
1071                 }
1072         }
1073
1074         // For InTitle commands, we already started the command before
1075         // the language switch
1076         if (!intitle_command)
1077                 parStartCommand(par, os, runparams, style);
1078
1079         Font const outerfont = text.outerFont(pit);
1080
1081         // FIXME UNICODE
1082         os << from_utf8(everypar);
1083         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
1084
1085         Font const font = par.empty()
1086                  ? par.getLayoutFont(bparams, outerfont)
1087                  : par.getFont(bparams, par.size() - 1, outerfont);
1088
1089         bool const is_command = style.isCommand();
1090
1091         // InTitle commands need to be closed after the language has been closed.
1092         if (!intitle_command) {
1093                 if (is_command) {
1094                         os << '}';
1095                         if (!style.postcommandargs().empty())
1096                                 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1097                         if (runparams.encoding != prev_encoding) {
1098                                 runparams.encoding = prev_encoding;
1099                                 os << setEncoding(prev_encoding->iconvName());
1100                         }
1101                 }
1102         }
1103
1104         bool pending_newline = false;
1105         bool unskip_newline = false;
1106         bool close_lang_switch = false;
1107         switch (style.latextype) {
1108         case LATEX_ITEM_ENVIRONMENT:
1109         case LATEX_LIST_ENVIRONMENT:
1110                 if ((nextpar && par_lang != nextpar_lang
1111                              && nextpar->getDepth() == par.getDepth())
1112                     || (atSameLastLangSwitchDepth(state) && nextpar
1113                             && nextpar->getDepth() < par.getDepth()))
1114                         close_lang_switch = using_begin_end;
1115                 if (nextpar && par.params().depth() < nextpar->params().depth())
1116                         pending_newline = true;
1117                 break;
1118         case LATEX_ENVIRONMENT: {
1119                 // if its the last paragraph of the current environment
1120                 // skip it otherwise fall through
1121                 if (nextpar
1122                     && ((nextpar->layout() != par.layout()
1123                            || nextpar->params().depth() != par.params().depth())
1124                         || (!using_begin_end || par_lang != nextpar_lang)))
1125                 {
1126                         close_lang_switch = using_begin_end;
1127                         break;
1128                 }
1129         }
1130         // possible
1131         // fall through
1132         default:
1133                 // we don't need it for the last paragraph and in InTitle commands!!!
1134                 if (nextpar && !intitle_command)
1135                         pending_newline = true;
1136         }
1137
1138         // InTitle commands use switches (not environments) for space settings
1139         if (par.allowParagraphCustomization() && !style.intitle) {
1140                 if (!par.params().spacing().isDefault()
1141                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
1142                         if (pending_newline)
1143                                 os << '\n';
1144
1145                         string const endtag =
1146                                 par.params().spacing().writeEnvirEnd(useSetSpace);
1147                         if (prefixIs(endtag, "\\end{"))
1148                                 os << breakln;
1149
1150                         os << from_ascii(endtag);
1151                         pending_newline = true;
1152                 }
1153         }
1154
1155         // Closing the language is needed for the last paragraph in a given language
1156         // as well as for any InTitleCommand (since these set the language locally);
1157         // it is also needed if we're within an \L or \R that we may have opened above
1158         // (not necessarily in this paragraph) and are about to close.
1159         bool closing_rtl_ltr_environment = !using_begin_end
1160                 // not for ArabTeX
1161                 && (par_language->lang() != "arabic_arabtex"
1162                     && outer_language->lang() != "arabic_arabtex")
1163                 // have we opened an \L or \R environment?
1164                 && runparams.local_font != 0
1165                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
1166                 // are we about to close the language?
1167                 &&((nextpar && par_lang != nextpar_lang)
1168                    || (runparams.isLastPar && par_lang != outer_lang));
1169
1170         if (localswitch_needed
1171             || (intitle_command && using_begin_end)
1172             || closing_rtl_ltr_environment
1173             || (((runparams.isLastPar && !runparams.inbranch) || close_lang_switch)
1174                 && (par_lang != outer_lang || (using_begin_end
1175                                                 && style.isEnvironment()
1176                                                 && par_lang != nextpar_lang)))) {
1177                 // Since \selectlanguage write the language to the aux file,
1178                 // we need to reset the language at the end of footnote or
1179                 // float.
1180
1181                 if (!localswitch && (pending_newline || close_lang_switch))
1182                         os << '\n';
1183
1184                 // when the paragraph uses CJK, the language has to be closed earlier
1185                 if (font.language()->encoding()->package() != Encoding::CJK) {
1186                         if (lang_end_command.empty()) {
1187                                 // If this is a child, we should restore the
1188                                 // master language after the last paragraph.
1189                                 Language const * const current_language =
1190                                         (runparams.isLastPar && runparams.master_language)
1191                                                 ? runparams.master_language
1192                                                 : outer_language;
1193                                 string const current_lang = use_polyglossia
1194                                         ? getPolyglossiaEnvName(current_language)
1195                                         : current_language->babel();
1196                                 if (!current_lang.empty()
1197                                     && current_lang != openLanguageName(state)) {
1198                                         string bc = use_polyglossia ?
1199                                                     getPolyglossiaBegin(lang_begin_command, current_lang,
1200                                                                         current_language->polyglossiaOpts(),
1201                                                                         localswitch)
1202                                                   : subst(lang_begin_command, "$$lang", current_lang);
1203                                         os << bc;
1204                                         pending_newline = !localswitch;
1205                                         unskip_newline = !localswitch;
1206                                         if (using_begin_end)
1207                                                 pushLanguageName(current_lang, localswitch);
1208                                 }
1209                         } else if ((!using_begin_end ||
1210                                     langOpenedAtThisLevel(state)) &&
1211                                    !par_lang.empty()) {
1212                                 // If we are in an environment, we have to
1213                                 // close the "outer" language afterwards
1214                                 string const & cur_lang = openLanguageName(state);
1215                                 if (!style.isEnvironment()
1216                                     || (close_lang_switch
1217                                         && atSameLastLangSwitchDepth(state)
1218                                         && par_lang != outer_lang
1219                                         && (par_lang != cur_lang
1220                                             || (cur_lang != outer_lang
1221                                                 && nextpar
1222                                                 && style != nextpar->layout())))
1223                                     || (atSameLastLangSwitchDepth(state)
1224                                         && state->lang_switch_depth_.size()
1225                                         && cur_lang != par_lang)
1226                                     || in_polyglossia_rtl_env)
1227                                 {
1228                                         if (using_begin_end && !localswitch)
1229                                                 os << breakln;
1230                                         os << from_ascii(subst(
1231                                                 lang_end_command,
1232                                                 "$$lang",
1233                                                 par_lang));
1234                                         pending_newline = !localswitch;
1235                                         unskip_newline = !localswitch;
1236                                         if (using_begin_end)
1237                                                 popLanguageName();
1238                                 }
1239                         }
1240                 }
1241         }
1242         if (closing_rtl_ltr_environment)
1243                 os << "}";
1244
1245         // InTitle commands need to be closed after the language has been closed.
1246         if (intitle_command) {
1247                 if (is_command) {
1248                         os << '}';
1249                         if (!style.postcommandargs().empty())
1250                                 latexArgInsets(par, os, runparams, style.postcommandargs(), "post:");
1251                         if (runparams.encoding != prev_encoding) {
1252                                 runparams.encoding = prev_encoding;
1253                                 os << setEncoding(prev_encoding->iconvName());
1254                         }
1255                 }
1256         }
1257
1258         bool const last_was_separator =
1259                 par.size() > 0 && par.isEnvSeparator(par.size() - 1);
1260
1261         if (pending_newline) {
1262                 if (unskip_newline)
1263                         // prevent unwanted whitespace
1264                         os << '%';
1265                 if (!os.afterParbreak() && !last_was_separator)
1266                         os << '\n';
1267         }
1268
1269         // if this is a CJK-paragraph and the next isn't, close CJK
1270         // also if the next paragraph is a multilingual environment (because of nesting)
1271         if (nextpar
1272                 && state->open_encoding_ == CJK
1273                 && (nextpar_language->encoding()->package() != Encoding::CJK
1274                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1275                 // inbetween environments, CJK has to be closed later (nesting!)
1276                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1277                 os << "\\end{CJK}\n";
1278                 state->open_encoding_ = none;
1279         }
1280
1281         // If this is the last paragraph, close the CJK environment
1282         // if necessary. If it's an environment, we'll have to \end that first.
1283         if (runparams.isLastPar && !style.isEnvironment()) {
1284                 switch (state->open_encoding_) {
1285                         case CJK: {
1286                                 // do nothing at the end of child documents
1287                                 if (maintext && buf.masterBuffer() != &buf)
1288                                         break;
1289                                 // end of main text
1290                                 if (maintext) {
1291                                         os << "\n\\end{CJK}\n";
1292                                 // end of an inset
1293                                 } else
1294                                         os << "\\end{CJK}";
1295                                 state->open_encoding_ = none;
1296                                 break;
1297                         }
1298                         case inputenc: {
1299                                 os << "\\egroup";
1300                                 state->open_encoding_ = none;
1301                                 break;
1302                         }
1303                         case none:
1304                         default:
1305                                 // do nothing
1306                                 break;
1307                 }
1308         }
1309
1310         // If this is the last paragraph, and a local_font was set upon entering
1311         // the inset, and we're using "auto" or "default" encoding, and not
1312         // compiling with XeTeX or LuaTeX, the encoding
1313         // should be set back to that local_font's encoding.
1314         if (runparams.isLastPar && runparams_in.local_font != 0
1315             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1316             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1317                 && !runparams.isFullUnicode()
1318            ) {
1319                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1320                 os << setEncoding(runparams_in.encoding->iconvName());
1321         }
1322         // Otherwise, the current encoding should be set for the next paragraph.
1323         else
1324                 runparams_in.encoding = runparams.encoding;
1325
1326         // These need to be passed upstream as well
1327         runparams_in.need_maketitle = runparams.need_maketitle;
1328         runparams_in.have_maketitle = runparams.have_maketitle;
1329
1330         // we don't need a newline for the last paragraph!!!
1331         // Note from JMarc: we will re-add a \n explicitly in
1332         // TeXEnvironment, because it is needed in this case
1333         if (nextpar && !os.afterParbreak() && !last_was_separator) {
1334                 // Make sure to start a new line
1335                 os << breakln;
1336                 Layout const & next_layout = nextpar->layout();
1337                 // A newline '\n' is always output before a command,
1338                 // so avoid doubling it.
1339                 if (!next_layout.isCommand()) {
1340                         // Here we now try to avoid spurious empty lines by
1341                         // outputting a paragraph break only if: (case 1) the
1342                         // paragraph style allows parbreaks and no \begin, \end
1343                         // or \item tags are going to follow (i.e., if the next
1344                         // isn't the first or the current isn't the last
1345                         // paragraph of an environment or itemize) and the
1346                         // depth and alignment of the following paragraph is
1347                         // unchanged, or (case 2) the following is a
1348                         // non-environment paragraph whose depth is increased
1349                         // but whose alignment is unchanged, or (case 3) the
1350                         // paragraph is not an environment and the next one is a
1351                         // non-itemize-like env at lower depth, or (case 4) the
1352                         // paragraph is a command not followed by an environment
1353                         // and the alignment of the current and next paragraph
1354                         // is unchanged, or (case 5) the current alignment is
1355                         // changed and a standard paragraph follows.
1356                         DocumentClass const & tclass = bparams.documentClass();
1357                         if ((style == next_layout
1358                              && !style.parbreak_is_newline
1359                              && !text.inset().getLayout().parbreakIsNewline()
1360                              && style.latextype != LATEX_ITEM_ENVIRONMENT
1361                              && style.latextype != LATEX_LIST_ENVIRONMENT
1362                              && style.align == par.getAlign(bparams)
1363                              && nextpar->getDepth() == par.getDepth()
1364                              && nextpar->getAlign(bparams) == par.getAlign(bparams))
1365                             || (!next_layout.isEnvironment()
1366                                 && nextpar->getDepth() > par.getDepth()
1367                                 && nextpar->getAlign(bparams) == next_layout.align)
1368                             || (!style.isEnvironment()
1369                                 && next_layout.latextype == LATEX_ENVIRONMENT
1370                                 && nextpar->getDepth() < par.getDepth())
1371                             || (style.isCommand()
1372                                 && !next_layout.isEnvironment()
1373                                 && style.align == par.getAlign(bparams)
1374                                 && next_layout.align == nextpar->getAlign(bparams))
1375                             || (style.align != par.getAlign(bparams)
1376                                 && tclass.isDefaultLayout(next_layout))) {
1377                                 os << '\n';
1378                         }
1379                 }
1380         }
1381
1382         // Reset language nesting level after intitle command
1383         if (intitle_command)
1384                 state->nest_level_ -= 1;
1385
1386         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1387                 << &par << " next " << nextpar);
1388
1389         return;
1390 }
1391
1392
1393 // LaTeX all paragraphs
1394 void latexParagraphs(Buffer const & buf,
1395                      Text const & text,
1396                      otexstream & os,
1397                      OutputParams const & runparams,
1398                      string const & everypar)
1399 {
1400         LASSERT(runparams.par_begin <= runparams.par_end,
1401                 { os << "% LaTeX Output Error\n"; return; } );
1402
1403         BufferParams const & bparams = buf.params();
1404         BufferParams const & mparams = buf.masterParams();
1405
1406         bool const maintext = text.isMainText();
1407         bool const is_child = buf.masterBuffer() != &buf;
1408         bool const multibib_child = maintext && is_child
1409                         && mparams.multibib == "child";
1410
1411         if (multibib_child && mparams.useBiblatex())
1412                 os << "\\newrefsection";
1413         else if (multibib_child && mparams.useBibtopic()
1414                  && !buf.masterBibInfo().empty()) {
1415                 os << "\\begin{btUnit}\n";
1416                 runparams.openbtUnit = true;
1417         }
1418
1419         // Open a CJK environment at the beginning of the main buffer
1420         // if the document's language is a CJK language
1421         // (but not in child documents)
1422         OutputState * state = getOutputState();
1423         if (maintext && !is_child && !bparams.useNonTeXFonts
1424             && bparams.language->encoding()->package() == Encoding::CJK
1425             && (bparams.encoding().name() == "utf8-cjk"
1426                 || bparams.encoding().iconvName() != "UTF-8")) {
1427                 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1428                                           && LaTeXFeatures::isAvailable("CJKutf8")) ?
1429                                                 from_ascii("UTF8")
1430                                               : from_ascii(bparams.encoding().latexName());
1431                 os << "\\begin{CJK}{" << cjkenc
1432                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1433                 state->open_encoding_ = CJK;
1434         }
1435         // if "auto begin" is switched off, explicitly switch the
1436         // language on at start
1437         string const mainlang = runparams.use_polyglossia
1438                 ? getPolyglossiaEnvName(bparams.language)
1439                 : bparams.language->babel();
1440         string const lang_begin_command = runparams.use_polyglossia ?
1441                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1442         string const lang_end_command = runparams.use_polyglossia ?
1443                 "\\end{$$lang}" : lyxrc.language_command_end;
1444         bool const using_begin_end = runparams.use_polyglossia ||
1445                                         !lang_end_command.empty();
1446
1447         if (maintext && !lyxrc.language_auto_begin &&
1448             !mainlang.empty()) {
1449                 // FIXME UNICODE
1450                 string bc = runparams.use_polyglossia ?
1451                             getPolyglossiaBegin(lang_begin_command, mainlang,
1452                                                 bparams.language->polyglossiaOpts())
1453                           : subst(lang_begin_command, "$$lang", mainlang);
1454                 os << bc;
1455                 os << '\n';
1456                 if (using_begin_end)
1457                         pushLanguageName(mainlang);
1458         }
1459
1460         ParagraphList const & paragraphs = text.paragraphs();
1461
1462         if (runparams.par_begin == runparams.par_end) {
1463                 // The full doc will be exported but it is easier to just rely on
1464                 // runparams range parameters that will be passed TeXEnvironment.
1465                 runparams.par_begin = 0;
1466                 runparams.par_end = paragraphs.size();
1467         }
1468
1469         pit_type pit = runparams.par_begin;
1470         // lastpit is for the language check after the loop.
1471         pit_type lastpit = pit;
1472         DocumentClass const & tclass = bparams.documentClass();
1473
1474         // Did we already warn about inTitle layout mixing? (we only warn once)
1475         bool gave_layout_warning = false;
1476         for (; pit < runparams.par_end; ++pit) {
1477                 lastpit = pit;
1478                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1479
1480                 // FIXME This check should not be needed. We should
1481                 // perhaps issue an error if it is.
1482                 Layout const & layout = text.inset().forcePlainLayout() ?
1483                                 tclass.plainLayout() : par->layout();
1484
1485                 if (layout.intitle) {
1486                         if (runparams.have_maketitle) {
1487                                 if (!gave_layout_warning && !runparams.dryrun) {
1488                                         gave_layout_warning = true;
1489                                         frontend::Alert::warning(_("Error in latexParagraphs"),
1490                                                         bformat(_("You are using at least one "
1491                                                           "layout (%1$s) intended for the title, "
1492                                                           "after using non-title layouts. This "
1493                                                           "could lead to missing or incorrect output."
1494                                                           ), layout.name()));
1495                                 }
1496                         } else if (!runparams.need_maketitle) {
1497                                 runparams.need_maketitle = true;
1498                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1499                                         os << "\\begin{"
1500                                                         << from_ascii(tclass.titlename())
1501                                                         << "}\n";
1502                                 }
1503                         }
1504                 } else if (runparams.need_maketitle && !runparams.have_maketitle
1505                            && !layout.inpreamble && !text.inset().isInTitle()) {
1506                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1507                                 os << "\\end{" << from_ascii(tclass.titlename())
1508                                                 << "}\n";
1509                         }
1510                         else {
1511                                 os << "\\" << from_ascii(tclass.titlename())
1512                                                 << "\n";
1513                         }
1514                         runparams.have_maketitle = true;
1515                         runparams.need_maketitle = false;
1516                 }
1517
1518                 if (layout.isCommand() && !layout.latexname().empty()
1519                     && layout.latexname() == bparams.multibib) {
1520                         if (runparams.openbtUnit)
1521                                 os << "\\end{btUnit}\n";
1522                         if (!bparams.useBiblatex()
1523                             && !buf.masterBibInfo().empty()) {
1524                                 os << '\n' << "\\begin{btUnit}\n";
1525                                 runparams.openbtUnit = true;
1526                         }
1527                 }
1528
1529                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1530                         // This is a standard top level paragraph, TeX it and continue.
1531                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1532                         continue;
1533                 }
1534
1535                 TeXEnvironmentData const data =
1536                         prepareEnvironment(buf, text, par, os, runparams);
1537                 // pit can be changed in TeXEnvironment.
1538                 TeXEnvironment(buf, text, runparams, pit, os);
1539                 finishEnvironment(os, runparams, data);
1540         }
1541
1542         if (pit == runparams.par_end) {
1543                         // Make sure that the last paragraph is
1544                         // correctly terminated (because TeXOnePar does
1545                         // not add a \n in this case)
1546                         //os << '\n';
1547         }
1548
1549         // It might be that we only have a title in this document.
1550         // But if we're in an inset, this is not the end of
1551         // the document. (There may be some other checks of this
1552         // kind that are needed.)
1553         if (runparams.need_maketitle && !runparams.have_maketitle && maintext) {
1554                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1555                         os << "\\end{" << from_ascii(tclass.titlename())
1556                            << "}\n";
1557                 } else {
1558                         os << "\\" << from_ascii(tclass.titlename())
1559                            << "\n";
1560                 }
1561         }
1562
1563         if (maintext && !is_child && runparams.openbtUnit)
1564                 os << "\\end{btUnit}\n";
1565
1566         // if "auto end" is switched off, explicitly close the language at the end
1567         // but only if the last par is in a babel or polyglossia language
1568         Language const * const lastpar_language =
1569                         paragraphs.at(lastpit).getParLanguage(bparams);
1570         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1571                 lastpar_language->encoding()->package() != Encoding::CJK) {
1572                 os << from_utf8(subst(lang_end_command,
1573                                         "$$lang",
1574                                         mainlang))
1575                         << '\n';
1576                 // If we have language_auto_begin, the stack will
1577                 // already be empty, nothing to pop()
1578                 if (using_begin_end && !lyxrc.language_auto_begin)
1579                         popLanguageName();
1580         }
1581
1582         // If the last paragraph is an environment, we'll have to close
1583         // CJK at the very end to do proper nesting.
1584         if (maintext && !is_child && state->open_encoding_ == CJK) {
1585                 os << "\\end{CJK}\n";
1586                 state->open_encoding_ = none;
1587         }
1588         // Likewise for polyglossia or when using begin/end commands
1589         // or at the very end of an active branch inset with a language switch
1590         Language const * const outer_language = (runparams.local_font != 0)
1591                         ? runparams.local_font->language() : bparams.language;
1592         string const & prev_lang = runparams.use_polyglossia
1593                         ? getPolyglossiaEnvName(outer_language)
1594                         : outer_language->babel();
1595         string const lastpar_lang = runparams.use_polyglossia ?
1596                 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1597         string const & cur_lang = openLanguageName(state);
1598         if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1599              || (maintext && !is_child)) && !cur_lang.empty()) {
1600                 os << from_utf8(subst(lang_end_command,
1601                                         "$$lang",
1602                                         cur_lang))
1603                    << '\n';
1604                 if (using_begin_end)
1605                         popLanguageName();
1606         } else if (runparams.inbranch && !using_begin_end
1607                    && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1608                 // with !using_begin_end, cur_lang is empty, so we need to
1609                 // compare against the paragraph language (and we are in the
1610                 // last paragraph at this point)
1611                 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1612         }
1613
1614         // reset inherited encoding
1615         if (state->cjk_inherited_ > 0) {
1616                 state->cjk_inherited_ -= 1;
1617                 if (state->cjk_inherited_ == 0)
1618                         state->open_encoding_ = CJK;
1619         }
1620
1621         if (multibib_child && mparams.useBibtopic()) {
1622                 os << "\\end{btUnit}\n";
1623                 runparams.openbtUnit = false;
1624         }
1625 }
1626
1627
1628 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1629                    OutputParams const & runparams, Encoding const & newEnc,
1630                    bool force)
1631 {
1632         // XeTeX/LuaTeX use only one encoding per document:
1633         // * with useNonTeXFonts: "utf8plain",
1634         // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1635         // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1636         if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1637                 return make_pair(false, 0);
1638
1639         Encoding const & oldEnc = *runparams.encoding;
1640         bool moving_arg = runparams.moving_arg;
1641         // If we switch from/to CJK, we need to switch anyway, despite custom inputenc,
1642         // except if we use CJKutf8
1643         bool const from_to_cjk =
1644                 ((oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1645                 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK))
1646                 && (bparams.encoding().name() != "utf8-cjk" || !LaTeXFeatures::isAvailable("CJKutf8"));
1647         if (!force && !from_to_cjk
1648             && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1649                 return make_pair(false, 0);
1650
1651         // Do nothing if the encoding is unchanged.
1652         if (oldEnc.name() == newEnc.name())
1653                 return make_pair(false, 0);
1654
1655         // FIXME We ignore encoding switches from/to encodings that do
1656         // neither support the inputenc package nor the CJK package here.
1657         // This does of course only work in special cases (e.g. switch from
1658         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1659         // but it is the best we can do
1660         if (oldEnc.package() == Encoding::none
1661                 || newEnc.package() == Encoding::none)
1662                 return make_pair(false, 0);
1663
1664         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1665                 << oldEnc.name() << " to " << newEnc.name());
1666         os << setEncoding(newEnc.iconvName());
1667         if (bparams.inputenc == "default")
1668                 return make_pair(true, 0);
1669
1670         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1671         OutputState * state = getOutputState();
1672         switch (newEnc.package()) {
1673                 case Encoding::none:
1674                 case Encoding::japanese:
1675                         // shouldn't ever reach here, see above
1676                         return make_pair(true, 0);
1677                 case Encoding::inputenc: {
1678                         int count = inputenc_arg.length();
1679                         if (oldEnc.package() == Encoding::CJK &&
1680                             state->open_encoding_ == CJK) {
1681                                 os << "\\end{CJK}";
1682                                 state->open_encoding_ = none;
1683                                 count += 9;
1684                         }
1685                         else if (oldEnc.package() == Encoding::inputenc &&
1686                                  state->open_encoding_ == inputenc) {
1687                                 os << "\\egroup";
1688                                 state->open_encoding_ = none;
1689                                 count += 7;
1690                         }
1691                         if (runparams.local_font != 0
1692                             &&  oldEnc.package() == Encoding::CJK) {
1693                                 // within insets, \inputenc switches need
1694                                 // to be embraced within \bgroup...\egroup;
1695                                 // else CJK fails.
1696                                 os << "\\bgroup";
1697                                 count += 7;
1698                                 state->open_encoding_ = inputenc;
1699                         }
1700                         // with the japanese option, inputenc is omitted.
1701                         if (runparams.use_japanese)
1702                                 return make_pair(true, count);
1703                         os << "\\inputencoding{" << inputenc_arg << '}';
1704                         return make_pair(true, count + 16);
1705                 }
1706                 case Encoding::CJK: {
1707                         int count = inputenc_arg.length();
1708                         if (oldEnc.package() == Encoding::CJK &&
1709                             state->open_encoding_ == CJK) {
1710                                 os << "\\end{CJK}";
1711                                 count += 9;
1712                         }
1713                         if (oldEnc.package() == Encoding::inputenc &&
1714                             state->open_encoding_ == inputenc) {
1715                                 os << "\\egroup";
1716                                 count += 7;
1717                         }
1718                         docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1719                                                   && LaTeXFeatures::isAvailable("CJKutf8")) ?
1720                                                         from_ascii("UTF8")
1721                                                       : from_ascii(bparams.encoding().latexName());
1722                         os << "\\begin{CJK}{" << cjkenc << "}{"
1723                            << from_ascii(bparams.fonts_cjk) << "}";
1724                         state->open_encoding_ = CJK;
1725                         return make_pair(true, count + 15);
1726                 }
1727         }
1728         // Dead code to avoid a warning:
1729         return make_pair(true, 0);
1730
1731 }
1732
1733 } // namespace lyx