]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
Correctly set language after intitle paragraphs
[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                 state->nest_level_ -= 1;
348                 string const & name = data.style->latexname();
349                 if (!name.empty())
350                         os << "\\end{" << from_ascii(name) << "}\n";
351                 state->prev_env_language_ = data.par_language;
352                 if (runparams.encoding != data.prev_encoding) {
353                         runparams.encoding = data.prev_encoding;
354                         os << setEncoding(data.prev_encoding->iconvName());
355                 }
356         }
357
358         if (data.leftindent_open) {
359                 os << breakln << "\\end{LyXParagraphLeftIndent}\n";
360                 state->prev_env_language_ = data.par_language;
361                 if (runparams.encoding != data.prev_encoding) {
362                         runparams.encoding = data.prev_encoding;
363                         os << setEncoding(data.prev_encoding->iconvName());
364                 }
365         }
366
367         // Check whether we should output a blank line after the environment
368         if (!data.style->nextnoindent)
369                 os << '\n';
370 }
371
372
373 void TeXEnvironment(Buffer const & buf, Text const & text,
374                     OutputParams const & runparams,
375                     pit_type & pit, otexstream & os)
376 {
377         ParagraphList const & paragraphs = text.paragraphs();
378         ParagraphList::const_iterator par = paragraphs.constIterator(pit);
379         LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
380
381         Layout const & current_layout = par->layout();
382         depth_type const current_depth = par->params().depth();
383         Length const & current_left_indent = par->params().leftIndent();
384
385         // This is for debugging purpose at the end.
386         pit_type const par_begin = pit;
387         for (; pit < runparams.par_end; ++pit) {
388                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
389
390                 // check first if this is an higher depth paragraph.
391                 bool go_out = (par->params().depth() < current_depth);
392                 if (par->params().depth() == current_depth) {
393                         // This environment is finished.
394                         go_out |= (par->layout() != current_layout);
395                         go_out |= (par->params().leftIndent() != current_left_indent);
396                 }
397                 if (go_out) {
398                         // nothing to do here, restore pit and go out.
399                         pit--;
400                         break;
401                 }
402
403                 if (par->layout() == current_layout
404                         && par->params().depth() == current_depth
405                         && par->params().leftIndent() == current_left_indent) {
406                         // We are still in the same environment so TeXOnePar and continue;
407                         TeXOnePar(buf, text, pit, os, runparams);
408                         continue;
409                 }
410
411                 // We are now in a deeper environment.
412                 // Either par->layout() != current_layout
413                 // Or     par->params().depth() > current_depth
414                 // Or     par->params().leftIndent() != current_left_indent)
415
416                 // FIXME This test should not be necessary.
417                 // We should perhaps issue an error if it is.
418                 bool const force_plain_layout = text.inset().forcePlainLayout();
419                 Layout const & style = force_plain_layout
420                         ? buf.params().documentClass().plainLayout()
421                         : par->layout();
422
423                 if (!style.isEnvironment()) {
424                         // This is a standard paragraph, no need to call TeXEnvironment.
425                         TeXOnePar(buf, text, pit, os, runparams);
426                         continue;
427                 }
428
429                 // This is a new environment.
430                 TeXEnvironmentData const data =
431                         prepareEnvironment(buf, text, par, os, runparams);
432                 // Recursive call to TeXEnvironment!
433                 TeXEnvironment(buf, text, runparams, pit, os);
434                 finishEnvironment(os, runparams, data);
435         }
436
437         if (pit != runparams.par_end)
438                 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
439 }
440
441
442 void getArgInsets(otexstream & os, OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs,
443                   map<int, lyx::InsetArgument const *> ilist, vector<string> required, string const & prefix)
444 {
445         unsigned int const argnr = latexargs.size();
446         if (argnr == 0)
447                 return;
448
449         // Default and preset args are always output, so if they require
450         // other arguments, consider this.
451         Layout::LaTeXArgMap::const_iterator lit = latexargs.begin();
452         Layout::LaTeXArgMap::const_iterator const lend = latexargs.end();
453         for (; lit != lend; ++lit) {
454                 Layout::latexarg arg = (*lit).second;
455                 if ((!arg.presetarg.empty() || !arg.defaultarg.empty()) && !arg.requires.empty()) {
456                                 vector<string> req = getVectorFromString(arg.requires);
457                                 required.insert(required.end(), req.begin(), req.end());
458                         }
459         }
460
461         for (unsigned int i = 1; i <= argnr; ++i) {
462                 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
463                 bool inserted = false;
464                 if (lit != ilist.end()) {
465                         InsetArgument const * ins = (*lit).second;
466                         if (ins) {
467                                 Layout::LaTeXArgMap::const_iterator const lait =
468                                                 latexargs.find(ins->name());
469                                 if (lait != latexargs.end()) {
470                                         Layout::latexarg arg = (*lait).second;
471                                         docstring ldelim = arg.mandatory ?
472                                                         from_ascii("{") : from_ascii("[");
473                                         docstring rdelim = arg.mandatory ?
474                                                         from_ascii("}") : from_ascii("]");
475                                         if (!arg.ldelim.empty())
476                                                 ldelim = arg.ldelim;
477                                         if (!arg.rdelim.empty())
478                                                 rdelim = arg.rdelim;
479                                         ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
480                                         inserted = true;
481                                 }
482                         }
483                 }
484                 if (!inserted) {
485                         Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
486                         Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
487                         for (; lait != laend; ++lait) {
488                                 string const name = prefix + convert<string>(i);
489                                 if ((*lait).first == name) {
490                                         Layout::latexarg arg = (*lait).second;
491                                         docstring preset = arg.presetarg;
492                                         if (!arg.defaultarg.empty()) {
493                                                 if (!preset.empty())
494                                                         preset += ",";
495                                                 preset += arg.defaultarg;
496                                         }
497                                         if (arg.mandatory) {
498                                                 docstring ldelim = arg.ldelim.empty() ?
499                                                                 from_ascii("{") : arg.ldelim;
500                                                 docstring rdelim = arg.rdelim.empty() ?
501                                                                 from_ascii("}") : arg.rdelim;
502                                                 os << ldelim << preset << rdelim;
503                                         } else if (!preset.empty()) {
504                                                 docstring ldelim = arg.ldelim.empty() ?
505                                                                 from_ascii("[") : arg.ldelim;
506                                                 docstring rdelim = arg.rdelim.empty() ?
507                                                                 from_ascii("]") : arg.rdelim;
508                                                 os << ldelim << preset << rdelim;
509                                         } else if (find(required.begin(), required.end(),
510                                                    (*lait).first) != required.end()) {
511                                                 docstring ldelim = arg.ldelim.empty() ?
512                                                                 from_ascii("[") : arg.ldelim;
513                                                 docstring rdelim = arg.rdelim.empty() ?
514                                                                 from_ascii("]") : arg.rdelim;
515                                                 os << ldelim << rdelim;
516                                         } else
517                                                 break;
518                                 }
519                         }
520                 }
521         }
522 }
523
524
525 } // namespace
526
527
528 void pushLanguageName(string const & lang_name, bool localswitch)
529 {
530         OutputState * state = getOutputState();
531
532         int nest_level = localswitch ? -state->nest_level_ : state->nest_level_;
533         state->lang_switch_depth_.push(nest_level);
534         state->open_polyglossia_lang_.push(lang_name);
535 }
536
537
538 void popLanguageName()
539 {
540         OutputState * state = getOutputState();
541
542         state->lang_switch_depth_.pop();
543         state->open_polyglossia_lang_.pop();
544 }
545
546
547 string const & openLanguageName()
548 {
549         OutputState * state = getOutputState();
550
551         return openLanguageName(state);
552 }
553
554
555 namespace {
556
557 void addArgInsets(Paragraph const & par, string const & prefix,
558                  Layout::LaTeXArgMap const & latexargs,
559                  map<int, InsetArgument const *> & ilist,
560                  vector<string> & required)
561 {
562         for (auto const & table : par.insetList()) {
563                 InsetArgument const * arg = table.inset->asInsetArgument();
564                 if (!arg)
565                         continue;
566                 if (arg->name().empty()) {
567                         LYXERR0("Error: Unnamed argument inset!");
568                         continue;
569                 }
570                 string const name = prefix.empty() ?
571                         arg->name() : split(arg->name(), ':');
572                 // why converting into an integer?
573                 unsigned int const nr = convert<unsigned int>(name);
574                 if (ilist.find(nr) == ilist.end())
575                         ilist[nr] = arg;
576                 Layout::LaTeXArgMap::const_iterator const lit =
577                         latexargs.find(arg->name());
578                 if (lit != latexargs.end()) {
579                         Layout::latexarg const & larg = lit->second;
580                         vector<string> req = getVectorFromString(larg.requires);
581                         move(req.begin(), req.end(), back_inserter(required));
582                 }
583         }
584 }
585
586 } // namespace
587
588
589 void latexArgInsets(Paragraph const & par, otexstream & os,
590                     OutputParams const & runparams,
591                     Layout::LaTeXArgMap const & latexargs,
592                     string const & prefix)
593 {
594         map<int, InsetArgument const *> ilist;
595         vector<string> required;
596         addArgInsets(par, prefix, latexargs, ilist, required);
597         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
598 }
599
600
601 void latexArgInsets(ParagraphList const & pars,
602                     ParagraphList::const_iterator pit,
603                     otexstream & os, OutputParams const & runparams,
604                     Layout::LaTeXArgMap const & latexargs,
605                     string const & prefix)
606 {
607         map<int, InsetArgument const *> ilist;
608         vector<string> required;
609
610         depth_type const current_depth = pit->params().depth();
611         Layout const current_layout = pit->layout();
612
613         // get the first paragraph in sequence with this layout and depth
614         pit_type offset = 0;
615         while (true) {
616                 if (lyx::prev(pit, offset) == pars.begin())
617                         break;
618                 ParagraphList::const_iterator priorpit = lyx::prev(pit, offset + 1);
619                 if (priorpit->layout() == current_layout
620                     && priorpit->params().depth() == current_depth)
621                         ++offset;
622                 else
623                         break;
624         }
625
626         ParagraphList::const_iterator spit = lyx::prev(pit, offset);
627
628         for (; spit != pars.end(); ++spit) {
629                 if (spit->layout() != current_layout ||
630                     spit->params().depth() < current_depth)
631                         break;
632                 if (spit->params().depth() > current_depth)
633                         continue;
634                 addArgInsets(*spit, prefix, latexargs, ilist, required);
635         }
636         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
637 }
638
639
640 void latexArgInsetsForParent(ParagraphList const & pars, otexstream & os,
641                              OutputParams const & runparams,
642                              Layout::LaTeXArgMap const & latexargs,
643                              string const & prefix)
644 {
645         map<int, InsetArgument const *> ilist;
646         vector<string> required;
647
648         for (Paragraph const & par : pars) {
649                 if (par.layout().hasArgs())
650                         // The InsetArguments inside this paragraph refer to this paragraph
651                         continue;
652                 addArgInsets(par, prefix, latexargs, ilist, required);
653         }
654         getArgInsets(os, runparams, latexargs, ilist, required, prefix);
655 }
656
657
658 namespace {
659
660 // output the proper paragraph start according to latextype.
661 void parStartCommand(Paragraph const & par, otexstream & os,
662                      OutputParams const & runparams, Layout const & style)
663 {
664         switch (style.latextype) {
665         case LATEX_COMMAND:
666                 os << '\\' << from_ascii(style.latexname());
667
668                 // Command arguments
669                 if (!style.latexargs().empty())
670                         latexArgInsets(par, os, runparams, style.latexargs());
671                 os << from_ascii(style.latexparam());
672                 break;
673         case LATEX_ITEM_ENVIRONMENT:
674         case LATEX_LIST_ENVIRONMENT:
675                 os << "\\" + style.itemcommand();
676                 // Item arguments
677                 if (!style.itemargs().empty())
678                         latexArgInsets(par, os, runparams, style.itemargs(), "item:");
679                 os << " ";
680                 break;
681         case LATEX_BIB_ENVIRONMENT:
682                 // ignore this, the inset will write itself
683                 break;
684         default:
685                 break;
686         }
687 }
688
689 } // namespace
690
691 // FIXME: this should be anonymous
692 void TeXOnePar(Buffer const & buf,
693                Text const & text,
694                pit_type pit,
695                otexstream & os,
696                OutputParams const & runparams_in,
697                string const & everypar,
698                int start_pos, int end_pos,
699                bool const force)
700 {
701         BufferParams const & bparams = runparams_in.is_child
702                 ? buf.masterParams() : buf.params();
703         ParagraphList const & paragraphs = text.paragraphs();
704         Paragraph const & par = paragraphs.at(pit);
705         // FIXME This check should not really be needed.
706         // Perhaps we should issue an error if it is.
707         Layout const & style = text.inset().forcePlainLayout() ?
708                 bparams.documentClass().plainLayout() : par.layout();
709
710         if (style.inpreamble && !force)
711                 return;
712
713         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
714                 << everypar << "'");
715
716         OutputParams runparams = runparams_in;
717         runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
718         // We reinitialze par begin and end to be on the safe side
719         // with embedded inset as we don't know if they set those
720         // value correctly.
721         runparams.par_begin = 0;
722         runparams.par_end = 0;
723
724         bool const maintext = text.isMainText();
725         // we are at the beginning of an inset and CJK is already open;
726         // we count inheritation levels to get the inset nesting right.
727         OutputState * state = getOutputState();
728         if (pit == 0 && !maintext
729             && (state->cjk_inherited_ > 0 || state->open_encoding_ == CJK)) {
730                 state->cjk_inherited_ += 1;
731                 state->open_encoding_ = none;
732         }
733
734         if (text.inset().isPassThru()) {
735                 Font const outerfont = text.outerFont(pit);
736
737                 // No newline before first paragraph in this lyxtext
738                 if (pit > 0) {
739                         os << '\n';
740                         if (!text.inset().getLayout().parbreakIsNewline())
741                                 os << '\n';
742                 }
743
744                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
745                 return;
746         }
747
748         Paragraph const * nextpar = runparams.isLastPar
749                 ? 0 : &paragraphs.at(pit + 1);
750
751         bool const intitle_command = style.intitle && style.latextype == LATEX_COMMAND;
752
753         if (style.pass_thru) {
754                 Font const outerfont = text.outerFont(pit);
755                 parStartCommand(par, os, runparams, style);
756                 if (intitle_command)
757                         os << '{';
758
759                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos, force);
760
761                 // I did not create a parEndCommand for this minuscule
762                 // task because in the other user of parStartCommand
763                 // the code is different (JMarc)
764                 if (style.isCommand())
765                         os << "}\n";
766                 else
767                         os << '\n';
768                 if (!style.parbreak_is_newline) {
769                         os << '\n';
770                 } else if (nextpar && !style.isEnvironment()) {
771                         Layout const nextstyle = text.inset().forcePlainLayout()
772                                 ? bparams.documentClass().plainLayout()
773                                 : nextpar->layout();
774                         if (nextstyle.name() != style.name())
775                                 os << '\n';
776                 }
777
778                 return;
779         }
780
781         // This paragraph's language
782         Language const * const par_language = par.getParLanguage(bparams);
783         Language const * const nextpar_language = nextpar ?
784                 nextpar->getParLanguage(bparams) : 0;
785         // The document's language
786         Language const * const doc_language = bparams.language;
787         // The language that was in effect when the environment this paragraph is
788         // inside of was opened
789         Language const * const outer_language =
790                 (runparams.local_font != 0) ?
791                         runparams.local_font->language() : doc_language;
792
793         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
794
795         // The previous language that was in effect is the language of the
796         // previous paragraph, unless the previous paragraph is inside an
797         // environment with nesting depth greater than (or equal to, but with
798         // a different layout) the current one. If there is no previous
799         // paragraph, the previous language is the outer language.
800         // Note further that we take the outer language also if the prior par
801         // is PassThru, since in that case it has latex_language, and all secondary
802         // languages have been closed (#10793).
803         bool const use_prev_env_language = state->prev_env_language_ != 0
804                         && priorpar
805                         && priorpar->layout().isEnvironment()
806                         && (priorpar->getDepth() > par.getDepth()
807                             || (priorpar->getDepth() == par.getDepth()
808                                     && priorpar->layout() != par.layout()));
809
810         // We need to ignore previous intitle commands since languages
811         // are switched locally there (# 11514)
812         // There might be paragraphs before the title, so we check this.
813         Paragraph * prior_nontitle_par = nullptr;
814         if (!intitle_command) {
815                 pit_type ppit = pit;
816                 while (ppit > 0) {
817                         --ppit;
818                         Paragraph const * tmppar = &paragraphs.at(ppit);
819                         if (tmppar->layout().intitle && tmppar->layout().isCommand())
820                                 continue;
821                         prior_nontitle_par = const_cast<Paragraph*>(tmppar);
822                         break;
823                 }
824         }
825         Language const * const prev_language =
826                 runparams_in.for_search 
827                         ? languages.getLanguage("ignore")
828                         : (prior_nontitle_par && !prior_nontitle_par->isPassThru())
829                                 ? (use_prev_env_language 
830                                         ? state->prev_env_language_
831                                         : prior_nontitle_par->getParLanguage(bparams))
832                                 : outer_language;
833
834         bool const use_polyglossia = runparams.use_polyglossia;
835         string const par_lang = use_polyglossia ?
836                 getPolyglossiaEnvName(par_language): par_language->babel();
837         string const prev_lang = use_polyglossia ?
838                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
839         string const outer_lang = use_polyglossia ?
840                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
841         string const nextpar_lang = nextpar_language ? (use_polyglossia ?
842                 getPolyglossiaEnvName(nextpar_language) :
843                 nextpar_language->babel()) : string();
844         string lang_begin_command = use_polyglossia ?
845                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
846         string lang_end_command = use_polyglossia ?
847                 "\\end{$$lang}" : lyxrc.language_command_end;
848         // the '%' is necessary to prevent unwanted whitespace
849         string lang_command_termination = "%\n";
850         bool const using_begin_end = use_polyglossia ||
851                                         !lang_end_command.empty();
852
853         // For InTitle commands, we need to switch the language inside the command
854         // (see #10849); thus open the command here.
855         if (intitle_command) {
856                 parStartCommand(par, os, runparams, style);
857                 os << '{';
858         }
859
860         // In some insets (such as Arguments), we cannot use \selectlanguage.
861         // Also, if an RTL language is set via environment in polyglossia,
862         // only a nested \\text<lang> command will reset the direction for LTR
863         // languages (see # 10111).
864         bool const in_polyglossia_rtl_env =
865                 use_polyglossia
866                 && runparams.local_font != 0
867                 && outer_language->rightToLeft()
868                 && !par_language->rightToLeft();
869         bool const localswitch = text.inset().forceLocalFontSwitch()
870                         || (using_begin_end && text.inset().forcePlainLayout())
871                         || in_polyglossia_rtl_env;
872         if (localswitch) {
873                 lang_begin_command = use_polyglossia ?
874                             "\\text$$lang$$opts{" : lyxrc.language_command_local;
875                 lang_end_command = "}";
876                 lang_command_termination.clear();
877         }
878         
879         bool const localswitch_needed = localswitch && par_lang != outer_lang;
880
881         // localswitches need to be closed and reopened at each par
882         if ((par_lang != prev_lang || localswitch_needed)
883              // check if we already put language command in TeXEnvironment()
884              && !(style.isEnvironment()
885                   && (pit == 0 || (priorpar->layout() != par.layout()
886                                    && priorpar->getDepth() <= par.getDepth())
887                       || priorpar->getDepth() < par.getDepth()))) {
888                 if (!localswitch
889                     && (!using_begin_end || langOpenedAtThisLevel(state))
890                     && !lang_end_command.empty()
891                     && prev_lang != outer_lang 
892                     && !prev_lang.empty()
893                     && (!using_begin_end || !style.isEnvironment())) {
894                         os << from_ascii(subst(lang_end_command,
895                                                "$$lang",
896                                                prev_lang))
897                            << lang_command_termination;
898                         if (using_begin_end)
899                                 popLanguageName();
900                 }
901
902                 // We need to open a new language if we couldn't close the previous
903                 // one (because there's no language_command_end); and even if we closed
904                 // the previous one, if the current language is different than the
905                 // outer_language (which is currently in effect once the previous one
906                 // is closed).
907                 if ((lang_end_command.empty() || par_lang != outer_lang
908                      || (!using_begin_end
909                          || (style.isEnvironment() && par_lang != prev_lang)))
910                         && !par_lang.empty()) {
911                         // If we're inside an inset, and that inset is within an \L or \R
912                         // (or equivalents), then within the inset, too, any opposite
913                         // language paragraph should appear within an \L or \R (in addition
914                         // to, outside of, the normal language switch commands).
915                         // This behavior is not correct for ArabTeX, though.
916                         if (!using_begin_end
917                             // not for ArabTeX
918                                 && par_language->lang() != "arabic_arabtex"
919                                 && outer_language->lang() != "arabic_arabtex"
920                             // are we in an inset?
921                             && runparams.local_font != 0
922                             // is the inset within an \L or \R?
923                             //
924                             // FIXME: currently, we don't check this; this means that
925                             // we'll have unnnecessary \L and \R commands, but that
926                             // doesn't seem to hurt (though latex will complain)
927                             //
928                             // is this paragraph in the opposite direction?
929                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
930                                 // FIXME: I don't have a working copy of the Arabi package, so
931                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
932                                 // or not...
933                                 if (par_language->lang() == "farsi")
934                                         os << "\\textFR{";
935                                 else if (outer_language->lang() == "farsi")
936                                         os << "\\textLR{";
937                                 else if (par_language->lang() == "arabic_arabi")
938                                         os << "\\textAR{";
939                                 else if (outer_language->lang() == "arabic_arabi")
940                                         os << "\\textLR{";
941                                 // remaining RTL languages currently is hebrew
942                                 else if (par_language->rightToLeft())
943                                         os << "\\R{";
944                                 else
945                                         os << "\\L{";
946                         }
947                         // With CJK, the CJK tag has to be closed first (see below)
948                         if (runparams.encoding->package() != Encoding::CJK
949                             && (par_lang != openLanguageName(state) || localswitch || intitle_command)
950                             && !par_lang.empty()) {
951                                 string bc = use_polyglossia ?
952                                           getPolyglossiaBegin(lang_begin_command, par_lang,
953                                                               par_language->polyglossiaOpts(),
954                                                               localswitch)
955                                           : subst(lang_begin_command, "$$lang", par_lang);
956                                 os << bc;
957                                 os << lang_command_termination;
958                                 if (using_begin_end)
959                                         pushLanguageName(par_lang, localswitch);
960                         }
961                 }
962         }
963
964         // Switch file encoding if necessary; no need to do this for "default"
965         // encoding, since this only affects the position of the outputted
966         // \inputencoding command; the encoding switch will occur when necessary
967         if (bparams.inputenc == "auto"
968                 && !runparams.isFullUnicode() // Xe/LuaTeX use one document-wide encoding  (see also switchEncoding())
969                 && runparams.encoding->package() != Encoding::none) {
970                 // Look ahead for future encoding changes.
971                 // We try to output them at the beginning of the paragraph,
972                 // since the \inputencoding command is not allowed e.g. in
973                 // sections. For this reason we only set runparams.moving_arg
974                 // after checking for the encoding change, otherwise the
975                 // change would be always avoided by switchEncoding().
976                 for (pos_type i = 0; i < par.size(); ++i) {
977                         char_type const c = par.getChar(i);
978                         Encoding const * const encoding =
979                                 par.getFontSettings(bparams, i).language()->encoding();
980                         if (encoding->package() != Encoding::CJK
981                                 && runparams.encoding->package() == Encoding::inputenc
982                                 && isASCII(c))
983                                 continue;
984                         if (par.isInset(i))
985                                 break;
986                         // All characters before c are in the ASCII range, and
987                         // c is non-ASCII (but no inset), so change the
988                         // encoding to that required by the language of c.
989                         // With CJK, only add switch if we have CJK content at the beginning
990                         // of the paragraph
991                         if (i != 0 && encoding->package() == Encoding::CJK)
992                                 continue;
993
994                         pair<bool, int> enc_switch = switchEncoding(os.os(),
995                                                 bparams, runparams, *encoding);
996                         // the following is necessary after a CJK environment in a multilingual
997                         // context (nesting issue).
998                         if (par_language->encoding()->package() == Encoding::CJK
999                                 && state->open_encoding_ != CJK && state->cjk_inherited_ == 0) {
1000                                 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1001                                                           && LaTeXFeatures::isAvailable("CJKutf8")) ?
1002                                                                 from_ascii("UTF8")
1003                                                               : from_ascii(par_language->encoding()->latexName());
1004                                 os << "\\begin{CJK}{" << cjkenc
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 && !runparams.inbranch) || 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) {
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
1264                 && (nextpar_language->encoding()->package() != Encoding::CJK
1265                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
1266                 // inbetween environments, CJK has to be closed later (nesting!)
1267                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
1268                 os << "\\end{CJK}\n";
1269                 state->open_encoding_ = none;
1270         }
1271
1272         // If this is the last paragraph, close the CJK environment
1273         // if necessary. If it's an environment, we'll have to \end that first.
1274         if (runparams.isLastPar && !style.isEnvironment()) {
1275                 switch (state->open_encoding_) {
1276                         case CJK: {
1277                                 // do nothing at the end of child documents
1278                                 if (maintext && buf.masterBuffer() != &buf)
1279                                         break;
1280                                 // end of main text
1281                                 if (maintext) {
1282                                         os << "\n\\end{CJK}\n";
1283                                 // end of an inset
1284                                 } else
1285                                         os << "\\end{CJK}";
1286                                 state->open_encoding_ = none;
1287                                 break;
1288                         }
1289                         case inputenc: {
1290                                 os << "\\egroup";
1291                                 state->open_encoding_ = none;
1292                                 break;
1293                         }
1294                         case none:
1295                         default:
1296                                 // do nothing
1297                                 break;
1298                 }
1299         }
1300
1301         // If this is the last paragraph, and a local_font was set upon entering
1302         // the inset, and we're using "auto" or "default" encoding, and not
1303         // compiling with XeTeX or LuaTeX, the encoding
1304         // should be set back to that local_font's encoding.
1305         if (runparams.isLastPar && runparams_in.local_font != 0
1306             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
1307             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
1308                 && !runparams.isFullUnicode()
1309            ) {
1310                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
1311                 os << setEncoding(runparams_in.encoding->iconvName());
1312         }
1313         // Otherwise, the current encoding should be set for the next paragraph.
1314         else
1315                 runparams_in.encoding = runparams.encoding;
1316
1317
1318         // we don't need a newline for the last paragraph!!!
1319         // Note from JMarc: we will re-add a \n explicitly in
1320         // TeXEnvironment, because it is needed in this case
1321         if (nextpar && !os.afterParbreak() && !last_was_separator) {
1322                 // Make sure to start a new line
1323                 os << breakln;
1324                 Layout const & next_layout = nextpar->layout();
1325                 // A newline '\n' is always output before a command,
1326                 // so avoid doubling it.
1327                 if (!next_layout.isCommand()) {
1328                         // Here we now try to avoid spurious empty lines by
1329                         // outputting a paragraph break only if: (case 1) the
1330                         // paragraph style allows parbreaks and no \begin, \end
1331                         // or \item tags are going to follow (i.e., if the next
1332                         // isn't the first or the current isn't the last
1333                         // paragraph of an environment or itemize) and the
1334                         // depth and alignment of the following paragraph is
1335                         // unchanged, or (case 2) the following is a
1336                         // non-environment paragraph whose depth is increased
1337                         // but whose alignment is unchanged, or (case 3) the
1338                         // paragraph is not an environment and the next one is a
1339                         // non-itemize-like env at lower depth, or (case 4) the
1340                         // paragraph is a command not followed by an environment
1341                         // and the alignment of the current and next paragraph
1342                         // is unchanged, or (case 5) the current alignment is
1343                         // changed and a standard paragraph follows.
1344                         DocumentClass const & tclass = bparams.documentClass();
1345                         if ((style == next_layout
1346                              && !style.parbreak_is_newline
1347                              && !text.inset().getLayout().parbreakIsNewline()
1348                              && style.latextype != LATEX_ITEM_ENVIRONMENT
1349                              && style.latextype != LATEX_LIST_ENVIRONMENT
1350                              && style.align == par.getAlign(bparams)
1351                              && nextpar->getDepth() == par.getDepth()
1352                              && nextpar->getAlign(bparams) == par.getAlign(bparams))
1353                             || (!next_layout.isEnvironment()
1354                                 && nextpar->getDepth() > par.getDepth()
1355                                 && nextpar->getAlign(bparams) == next_layout.align)
1356                             || (!style.isEnvironment()
1357                                 && next_layout.latextype == LATEX_ENVIRONMENT
1358                                 && nextpar->getDepth() < par.getDepth())
1359                             || (style.isCommand()
1360                                 && !next_layout.isEnvironment()
1361                                 && style.align == par.getAlign(bparams)
1362                                 && next_layout.align == nextpar->getAlign(bparams))
1363                             || (style.align != par.getAlign(bparams)
1364                                 && tclass.isDefaultLayout(next_layout))) {
1365                                 os << '\n';
1366                         }
1367                 }
1368         }
1369
1370         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
1371                 << &par << " next " << nextpar);
1372
1373         return;
1374 }
1375
1376
1377 // LaTeX all paragraphs
1378 void latexParagraphs(Buffer const & buf,
1379                      Text const & text,
1380                      otexstream & os,
1381                      OutputParams const & runparams,
1382                      string const & everypar)
1383 {
1384         LASSERT(runparams.par_begin <= runparams.par_end,
1385                 { os << "% LaTeX Output Error\n"; return; } );
1386
1387         BufferParams const & bparams = buf.params();
1388         BufferParams const & mparams = buf.masterParams();
1389
1390         bool const maintext = text.isMainText();
1391         bool const is_child = buf.masterBuffer() != &buf;
1392         bool const multibib_child = maintext && is_child
1393                         && mparams.multibib == "child";
1394
1395         if (multibib_child && mparams.useBiblatex())
1396                 os << "\\newrefsection";
1397         else if (multibib_child && mparams.useBibtopic()
1398                  && !buf.masterBibInfo().empty()) {
1399                 os << "\\begin{btUnit}\n";
1400                 runparams.openbtUnit = true;
1401         }
1402
1403         // Open a CJK environment at the beginning of the main buffer
1404         // if the document's language is a CJK language
1405         // (but not in child documents)
1406         OutputState * state = getOutputState();
1407         if (maintext && !is_child && !bparams.useNonTeXFonts
1408             && bparams.language->encoding()->package() == Encoding::CJK
1409             && (bparams.encoding().name() == "utf8-cjk"
1410                 || bparams.encoding().iconvName() != "UTF-8")) {
1411                 docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1412                                           && LaTeXFeatures::isAvailable("CJKutf8")) ?
1413                                                 from_ascii("UTF8")
1414                                               : from_ascii(bparams.encoding().latexName());
1415                 os << "\\begin{CJK}{" << cjkenc
1416                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
1417                 state->open_encoding_ = CJK;
1418         }
1419         // if "auto begin" is switched off, explicitly switch the
1420         // language on at start
1421         string const mainlang = runparams.use_polyglossia
1422                 ? getPolyglossiaEnvName(bparams.language)
1423                 : bparams.language->babel();
1424         string const lang_begin_command = runparams.use_polyglossia ?
1425                 "\\begin{$$lang}$$opts" : lyxrc.language_command_begin;
1426         string const lang_end_command = runparams.use_polyglossia ?
1427                 "\\end{$$lang}" : lyxrc.language_command_end;
1428         bool const using_begin_end = runparams.use_polyglossia ||
1429                                         !lang_end_command.empty();
1430
1431         if (maintext && !lyxrc.language_auto_begin &&
1432             !mainlang.empty()) {
1433                 // FIXME UNICODE
1434                 string bc = runparams.use_polyglossia ?
1435                             getPolyglossiaBegin(lang_begin_command, mainlang,
1436                                                 bparams.language->polyglossiaOpts())
1437                           : subst(lang_begin_command, "$$lang", mainlang);
1438                 os << bc;
1439                 os << '\n';
1440                 if (using_begin_end)
1441                         pushLanguageName(mainlang);
1442         }
1443
1444         ParagraphList const & paragraphs = text.paragraphs();
1445
1446         if (runparams.par_begin == runparams.par_end) {
1447                 // The full doc will be exported but it is easier to just rely on
1448                 // runparams range parameters that will be passed TeXEnvironment.
1449                 runparams.par_begin = 0;
1450                 runparams.par_end = paragraphs.size();
1451         }
1452
1453         pit_type pit = runparams.par_begin;
1454         // lastpit is for the language check after the loop.
1455         pit_type lastpit = pit;
1456         // variables used in the loop:
1457         bool was_title = false;
1458         bool already_title = false;
1459         DocumentClass const & tclass = bparams.documentClass();
1460
1461         // Did we already warn about inTitle layout mixing? (we only warn once)
1462         bool gave_layout_warning = false;
1463         for (; pit < runparams.par_end; ++pit) {
1464                 lastpit = pit;
1465                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1466
1467                 // FIXME This check should not be needed. We should
1468                 // perhaps issue an error if it is.
1469                 Layout const & layout = text.inset().forcePlainLayout() ?
1470                                 tclass.plainLayout() : par->layout();
1471
1472                 if (layout.intitle) {
1473                         if (already_title) {
1474                                 if (!gave_layout_warning && !runparams.dryrun) {
1475                                         gave_layout_warning = true;
1476                                         frontend::Alert::warning(_("Error in latexParagraphs"),
1477                                                         bformat(_("You are using at least one "
1478                                                           "layout (%1$s) intended for the title, "
1479                                                           "after using non-title layouts. This "
1480                                                           "could lead to missing or incorrect output."
1481                                                           ), layout.name()));
1482                                 }
1483                         } else if (!was_title) {
1484                                 was_title = true;
1485                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1486                                         os << "\\begin{"
1487                                                         << from_ascii(tclass.titlename())
1488                                                         << "}\n";
1489                                 }
1490                         }
1491                 } else if (was_title && !already_title && !layout.inpreamble) {
1492                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1493                                 os << "\\end{" << from_ascii(tclass.titlename())
1494                                                 << "}\n";
1495                         }
1496                         else {
1497                                 os << "\\" << from_ascii(tclass.titlename())
1498                                                 << "\n";
1499                         }
1500                         already_title = true;
1501                         was_title = false;
1502                 }
1503
1504                 if (layout.isCommand() && !layout.latexname().empty()
1505                     && layout.latexname() == bparams.multibib) {
1506                         if (runparams.openbtUnit)
1507                                 os << "\\end{btUnit}\n";
1508                         if (!bparams.useBiblatex()
1509                             && !buf.masterBibInfo().empty()) {
1510                                 os << '\n' << "\\begin{btUnit}\n";
1511                                 runparams.openbtUnit = true;
1512                         }
1513                 }
1514
1515                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1516                         // This is a standard top level paragraph, TeX it and continue.
1517                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1518                         continue;
1519                 }
1520
1521                 TeXEnvironmentData const data =
1522                         prepareEnvironment(buf, text, par, os, runparams);
1523                 // pit can be changed in TeXEnvironment.
1524                 TeXEnvironment(buf, text, runparams, pit, os);
1525                 finishEnvironment(os, runparams, data);
1526         }
1527
1528         if (pit == runparams.par_end) {
1529                         // Make sure that the last paragraph is
1530                         // correctly terminated (because TeXOnePar does
1531                         // not add a \n in this case)
1532                         //os << '\n';
1533         }
1534
1535         // It might be that we only have a title in this document
1536         if (was_title && !already_title) {
1537                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1538                         os << "\\end{" << from_ascii(tclass.titlename())
1539                            << "}\n";
1540                 } else {
1541                         os << "\\" << from_ascii(tclass.titlename())
1542                            << "\n";
1543                 }
1544         }
1545
1546         if (maintext && !is_child && runparams.openbtUnit)
1547                 os << "\\end{btUnit}\n";
1548
1549         // if "auto end" is switched off, explicitly close the language at the end
1550         // but only if the last par is in a babel or polyglossia language
1551         Language const * const lastpar_language =
1552                         paragraphs.at(lastpit).getParLanguage(bparams);
1553         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1554                 lastpar_language->encoding()->package() != Encoding::CJK) {
1555                 os << from_utf8(subst(lang_end_command,
1556                                         "$$lang",
1557                                         mainlang))
1558                         << '\n';
1559                 if (using_begin_end)
1560                         popLanguageName();
1561         }
1562
1563         // If the last paragraph is an environment, we'll have to close
1564         // CJK at the very end to do proper nesting.
1565         if (maintext && !is_child && state->open_encoding_ == CJK) {
1566                 os << "\\end{CJK}\n";
1567                 state->open_encoding_ = none;
1568         }
1569         // Likewise for polyglossia or when using begin/end commands
1570         // or at the very end of an active branch inset with a language switch
1571         Language const * const outer_language = (runparams.local_font != 0)
1572                         ? runparams.local_font->language() : bparams.language;
1573         string const & prev_lang = runparams.use_polyglossia
1574                         ? getPolyglossiaEnvName(outer_language)
1575                         : outer_language->babel();
1576         string const lastpar_lang = runparams.use_polyglossia ?
1577                 getPolyglossiaEnvName(lastpar_language): lastpar_language->babel();
1578         string const & cur_lang = openLanguageName(state);
1579         if (((runparams.inbranch && langOpenedAtThisLevel(state) && prev_lang != cur_lang)
1580              || (maintext && !is_child)) && !cur_lang.empty()) {
1581                 os << from_utf8(subst(lang_end_command,
1582                                         "$$lang",
1583                                         cur_lang))
1584                    << '\n';
1585                 if (using_begin_end)
1586                         popLanguageName();
1587         } else if (runparams.inbranch && !using_begin_end
1588                    && prev_lang != lastpar_lang && !lastpar_lang.empty()) {
1589                 // with !using_begin_end, cur_lang is empty, so we need to
1590                 // compare against the paragraph language (and we are in the
1591                 // last paragraph at this point)
1592                 os << subst(lang_begin_command, "$$lang", prev_lang) << '\n';
1593         }
1594
1595         // reset inherited encoding
1596         if (state->cjk_inherited_ > 0) {
1597                 state->cjk_inherited_ -= 1;
1598                 if (state->cjk_inherited_ == 0)
1599                         state->open_encoding_ = CJK;
1600         }
1601
1602         if (multibib_child && mparams.useBibtopic()) {
1603                 os << "\\end{btUnit}\n";
1604                 runparams.openbtUnit = false;
1605         }
1606 }
1607
1608
1609 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1610                    OutputParams const & runparams, Encoding const & newEnc,
1611                    bool force)
1612 {
1613         // XeTeX/LuaTeX use only one encoding per document:
1614         // * with useNonTeXFonts: "utf8plain",
1615         // * with XeTeX and TeX fonts: "ascii" (inputenc fails),
1616         // * with LuaTeX and TeX fonts: only one encoding accepted by luainputenc.
1617         if (runparams.isFullUnicode() || newEnc.name() == "inherit")
1618                 return make_pair(false, 0);
1619
1620         Encoding const & oldEnc = *runparams.encoding;
1621         bool moving_arg = runparams.moving_arg;
1622         // If we switch from/to CJK, we need to switch anyway, despite custom inputenc,
1623         // except if we use CJKutf8
1624         bool const from_to_cjk =
1625                 ((oldEnc.package() == Encoding::CJK && newEnc.package() != Encoding::CJK)
1626                 || (oldEnc.package() != Encoding::CJK && newEnc.package() == Encoding::CJK))
1627                 && (bparams.encoding().name() != "utf8-cjk" || !LaTeXFeatures::isAvailable("CJKutf8"));
1628         if (!force && !from_to_cjk
1629             && ((bparams.inputenc != "auto" && bparams.inputenc != "default") || moving_arg))
1630                 return make_pair(false, 0);
1631
1632         // Do nothing if the encoding is unchanged.
1633         if (oldEnc.name() == newEnc.name())
1634                 return make_pair(false, 0);
1635
1636         // FIXME We ignore encoding switches from/to encodings that do
1637         // neither support the inputenc package nor the CJK package here.
1638         // This does of course only work in special cases (e.g. switch from
1639         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1640         // but it is the best we can do
1641         if (oldEnc.package() == Encoding::none
1642                 || newEnc.package() == Encoding::none)
1643                 return make_pair(false, 0);
1644
1645         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1646                 << oldEnc.name() << " to " << newEnc.name());
1647         os << setEncoding(newEnc.iconvName());
1648         if (bparams.inputenc == "default")
1649                 return make_pair(true, 0);
1650
1651         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1652         OutputState * state = getOutputState();
1653         switch (newEnc.package()) {
1654                 case Encoding::none:
1655                 case Encoding::japanese:
1656                         // shouldn't ever reach here, see above
1657                         return make_pair(true, 0);
1658                 case Encoding::inputenc: {
1659                         int count = inputenc_arg.length();
1660                         if (oldEnc.package() == Encoding::CJK &&
1661                             state->open_encoding_ == CJK) {
1662                                 os << "\\end{CJK}";
1663                                 state->open_encoding_ = none;
1664                                 count += 9;
1665                         }
1666                         else if (oldEnc.package() == Encoding::inputenc &&
1667                                  state->open_encoding_ == inputenc) {
1668                                 os << "\\egroup";
1669                                 state->open_encoding_ = none;
1670                                 count += 7;
1671                         }
1672                         if (runparams.local_font != 0
1673                             &&  oldEnc.package() == Encoding::CJK) {
1674                                 // within insets, \inputenc switches need
1675                                 // to be embraced within \bgroup...\egroup;
1676                                 // else CJK fails.
1677                                 os << "\\bgroup";
1678                                 count += 7;
1679                                 state->open_encoding_ = inputenc;
1680                         }
1681                         // with the japanese option, inputenc is omitted.
1682                         if (runparams.use_japanese)
1683                                 return make_pair(true, count);
1684                         os << "\\inputencoding{" << inputenc_arg << '}';
1685                         return make_pair(true, count + 16);
1686                 }
1687                 case Encoding::CJK: {
1688                         int count = inputenc_arg.length();
1689                         if (oldEnc.package() == Encoding::CJK &&
1690                             state->open_encoding_ == CJK) {
1691                                 os << "\\end{CJK}";
1692                                 count += 9;
1693                         }
1694                         if (oldEnc.package() == Encoding::inputenc &&
1695                             state->open_encoding_ == inputenc) {
1696                                 os << "\\egroup";
1697                                 count += 7;
1698                         }
1699                         docstring const cjkenc = (bparams.encoding().name() == "utf8-cjk"
1700                                                   && LaTeXFeatures::isAvailable("CJKutf8")) ?
1701                                                         from_ascii("UTF8")
1702                                                       : from_ascii(bparams.encoding().latexName());
1703                         os << "\\begin{CJK}{" << cjkenc << "}{"
1704                            << from_ascii(bparams.fonts_cjk) << "}";
1705                         state->open_encoding_ = CJK;
1706                         return make_pair(true, count + 15);
1707                 }
1708         }
1709         // Dead code to avoid a warning:
1710         return make_pair(true, 0);
1711
1712 }
1713
1714 } // namespace lyx