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