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