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