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