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