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