]> git.lyx.org Git - features.git/blob - src/output_latex.cpp
9629a91ebffc9cb9affa3bf630c6705918d04c70
[features.git] / src / output_latex.cpp
1 /**
2  * \file output_latex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "Encoding.h"
18 #include "Font.h"
19 #include "InsetList.h"
20 #include "Language.h"
21 #include "Layout.h"
22 #include "LyXRC.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "TextClass.h"
27 #include "TexRow.h"
28
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetArgument.h"
31
32 #include "support/lassert.h"
33 #include "support/convert.h"
34 #include "support/debug.h"
35 #include "support/lstrings.h"
36
37 #include <algorithm>
38 #include <boost/next_prior.hpp>
39 #include <list>
40
41 using namespace std;
42 using namespace lyx::support;
43
44
45 namespace lyx {
46
47 namespace {
48
49 enum OpenEncoding {
50         none,
51         inputenc,
52         CJK
53 };
54
55 static int open_encoding_ = none;
56 static int cjk_inherited_ = 0;
57 Language const * prev_env_language_ = 0;
58
59
60 string const getPolyglossiaEnvName(Language const * lang)
61 {
62         string result = lang->polyglossia();
63         if (result == "arabic")
64                 // exceptional spelling; see polyglossia docs.
65                 result = "Arabic";
66         return result;
67 }
68
69
70 struct TeXEnvironmentData
71 {
72         bool cjk_nested;
73         Layout const * style;
74         Language const * par_language;
75         Encoding const * prev_encoding;
76         bool leftindent_open;
77 };
78
79
80 static TeXEnvironmentData prepareEnvironment(Buffer const & buf,
81                                         Text const & text,
82                                         ParagraphList::const_iterator pit,
83                                         otexstream & os,
84                                         OutputParams const & runparams)
85 {
86         TeXEnvironmentData data;
87
88         BufferParams const & bparams = buf.params();
89
90         // FIXME This test should not be necessary.
91         // We should perhaps issue an error if it is.
92         Layout const & style = text.inset().forcePlainLayout() ?
93                 bparams.documentClass().plainLayout() : pit->layout();
94
95         ParagraphList const & paragraphs = text.paragraphs();
96         ParagraphList::const_iterator const priorpit =
97                 pit == paragraphs.begin() ? pit : boost::prior(pit);
98
99         bool const use_prev_env_language = prev_env_language_ != 0
100                         && priorpit->layout().isEnvironment()
101                         && (priorpit->getDepth() > pit->getDepth()
102                             || (priorpit->getDepth() == pit->getDepth()
103                                 && priorpit->layout() != pit->layout()));
104
105         data.prev_encoding = runparams.encoding;
106         data.par_language = pit->getParLanguage(bparams);
107         Language const * const doc_language = bparams.language;
108         Language const * const prev_par_language =
109                 (pit != paragraphs.begin())
110                 ? (use_prev_env_language ? prev_env_language_
111                                          : priorpit->getParLanguage(bparams))
112                 : doc_language;
113
114         bool const use_polyglossia = runparams.use_polyglossia;
115         string const par_lang = use_polyglossia ?
116                 getPolyglossiaEnvName(data.par_language) : data.par_language->babel();
117         string const prev_par_lang = use_polyglossia ?
118                 getPolyglossiaEnvName(prev_par_language) : prev_par_language->babel();
119         string const doc_lang = use_polyglossia ?
120                 getPolyglossiaEnvName(doc_language) : doc_language->babel();
121         string const lang_begin_command = use_polyglossia ?
122                 "\\begin{$$lang}" : lyxrc.language_command_begin;
123         string const lang_end_command = use_polyglossia ?
124                 "\\end{$$lang}" : lyxrc.language_command_end;
125
126         if (par_lang != prev_par_lang) {
127                 if (!lang_end_command.empty() &&
128                     prev_par_lang != doc_lang &&
129                     !prev_par_lang.empty()) {
130                         os << from_ascii(subst(
131                                 lang_end_command,
132                                 "$$lang",
133                                 prev_par_lang))
134                           // the '%' is necessary to prevent unwanted whitespace
135                           << "%\n";
136                 }
137
138                 if ((lang_end_command.empty() ||
139                     par_lang != doc_lang) &&
140                     !par_lang.empty()) {
141                         os << from_ascii(subst(
142                                 lang_begin_command,
143                                 "$$lang",
144                                 par_lang));
145                         if (use_polyglossia
146                             && !data.par_language->polyglossiaOpts().empty())
147                                         os << "["
148                                            << from_ascii(data.par_language->polyglossiaOpts())
149                                            << "]";
150                           // the '%' is necessary to prevent unwanted whitespace
151                         os << "%\n";
152                 }
153         }
154
155         data.leftindent_open = false;
156         if (!pit->params().leftIndent().zero()) {
157                 os << "\\begin{LyXParagraphLeftIndent}{"
158                    << from_ascii(pit->params().leftIndent().asLatexString())
159                    << "}\n";
160                 data.leftindent_open = true;
161         }
162
163         if (style.isEnvironment()) {
164                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
165                 if (!style.latexargs().empty()) {
166                     OutputParams rp = runparams;
167                     rp.local_font = &pit->getFirstFontSettings(bparams);
168                     latexArgInsets(*pit, os, rp, style.latexargs());
169                 }
170                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
171                         os << '{'
172                            << pit->params().labelWidthString()
173                            << "}\n";
174                 } else if (style.labeltype == LABEL_BIBLIO) {
175                         if (pit->params().labelWidthString().empty())
176                                 os << '{' << bibitemWidest(buf, runparams) << "}\n";
177                         else
178                                 os << '{'
179                                   << pit->params().labelWidthString()
180                                   << "}\n";
181                 } else
182                         os << from_ascii(style.latexparam()) << '\n';
183         }
184         data.style = &style;
185
186         // in multilingual environments, the CJK tags have to be nested properly
187         data.cjk_nested = false;
188         if (data.par_language->encoding()->package() == Encoding::CJK &&
189             open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
190                 if (prev_par_language->encoding()->package() == Encoding::CJK)
191                         os << "\\begin{CJK}{" << from_ascii(data.par_language->encoding()->latexName())
192                            << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
193                 open_encoding_ = CJK;
194                 data.cjk_nested = true;
195         }
196         return data;
197 }
198
199
200 static void finishEnvironment(otexstream & os, OutputParams const & runparams,
201                                TeXEnvironmentData const & data)
202 {
203         if (open_encoding_ == CJK && data.cjk_nested) {
204                 // We need to close the encoding even if it does not change
205                 // to do correct environment nesting
206                 os << "\\end{CJK}\n";
207                 open_encoding_ = none;
208         }
209
210         if (data.style->isEnvironment()) {
211                 os << "\\end{" << from_ascii(data.style->latexname()) << "}\n";
212                 prev_env_language_ = data.par_language;
213                 if (runparams.encoding != data.prev_encoding) {
214                         runparams.encoding = data.prev_encoding;
215                         if (!runparams.isFullUnicode())
216                                 os << setEncoding(data.prev_encoding->iconvName());
217                 }
218         }
219
220         if (data.leftindent_open) {
221                 os << "\\end{LyXParagraphLeftIndent}\n";
222                 prev_env_language_ = data.par_language;
223                 if (runparams.encoding != data.prev_encoding) {
224                         runparams.encoding = data.prev_encoding;
225                         if (!runparams.isFullUnicode())
226                                 os << setEncoding(data.prev_encoding->iconvName());
227                 }
228         }
229 }
230
231
232 void TeXEnvironment(Buffer const & buf, Text const & text,
233                     OutputParams const & runparams,
234                     pit_type & pit, otexstream & os)
235 {
236         ParagraphList const & paragraphs = text.paragraphs();
237         ParagraphList::const_iterator par = paragraphs.constIterator(pit);
238         LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << pit);
239
240         Layout const & current_layout = par->layout();
241         depth_type const current_depth = par->params().depth();
242         Length const & current_left_indent = par->params().leftIndent();
243
244         // This is for debugging purpose at the end.
245         pit_type const par_begin = pit;
246         for (; pit < runparams.par_end; ++pit) {
247                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
248
249                 // check first if this is an higher depth paragraph.
250                 bool go_out = (par->params().depth() < current_depth);
251                 if (par->params().depth() == current_depth) {
252                         // This environment is finished.
253                         go_out |= (par->layout() != current_layout);
254                         go_out |= (par->params().leftIndent() != current_left_indent);
255                 }
256                 if (go_out) {
257                         // nothing to do here, restore pit and go out.
258                         pit--;
259                         break;
260                 }
261
262                 if (par->layout() == current_layout
263                         && par->params().depth() == current_depth
264                         && par->params().leftIndent() == current_left_indent) {
265                         // We are still in the same environment so TeXOnePar and continue;
266                         TeXOnePar(buf, text, pit, os, runparams);
267                         continue;
268                 }
269
270                 // We are now in a deeper environment.
271                 // Either par->layout() != current_layout
272                 // Or     par->params().depth() > current_depth
273                 // Or     par->params().leftIndent() != current_left_indent)
274
275                 if (par->layout().isParagraph()) {
276                         // FIXME (Lgb): How to handle this?
277                         //&& !suffixIs(os, "\n\n")
278
279                         // (ARRae) There should be at least one '\n' already but we need there to
280                         // be two for Standard paragraphs that are depth-increment'ed to be
281                         // output correctly. However, tables can also be paragraphs so
282                         // don't adjust them.
283
284                         // FIXME (Lgb): Will it ever harm to have one '\n' too
285                         // many? i.e. that we sometimes will have
286                         // three in a row.
287                         os << '\n';
288                 }
289
290                 // FIXME This test should not be necessary.
291                 // We should perhaps issue an error if it is.
292                 bool const force_plain_layout = text.inset().forcePlainLayout();
293                 Layout const & style = force_plain_layout
294                         ? buf.params().documentClass().plainLayout()
295                         : par->layout();
296
297                 if (!style.isEnvironment()) {
298                         // This is a standard paragraph, no need to call TeXEnvironment.
299                         TeXOnePar(buf, text, pit, os, runparams);
300                         continue;
301                 }
302
303                 // This is a new environment.
304                 TeXEnvironmentData const data =
305                         prepareEnvironment(buf, text, par, os, runparams);
306                 // Recursive call to TeXEnvironment!
307                 TeXEnvironment(buf, text, runparams, pit, os);
308                 finishEnvironment(os, runparams, data);
309         }
310
311         if (pit != runparams.par_end)
312                 LYXERR(Debug::LATEX, "TeXEnvironment for paragraph " << par_begin << " done.");
313 }
314
315 } // namespace anon
316
317
318 void latexArgInsets(Paragraph const & par, otexstream & os,
319         OutputParams const & runparams, Layout::LaTeXArgMap const & latexargs, bool item)
320 {
321         map<int, InsetArgument const *> ilist;
322         vector<string> required;
323
324         InsetList::const_iterator it = par.insetList().begin();
325         InsetList::const_iterator end = par.insetList().end();
326         for (; it != end; ++it) {
327                 if (it->inset->lyxCode() == ARG_CODE) {
328                         InsetArgument const * ins =
329                                 static_cast<InsetArgument const *>(it->inset);
330                         if (ins->name().empty())
331                                 LYXERR0("Error: Unnamed argument inset!");
332                         else {
333                                 string const name = item ? split(ins->name(), ':') : ins->name();
334                                 unsigned int const nr = convert<unsigned int>(name);
335                                 ilist[nr] = ins;
336                                 Layout::LaTeXArgMap::const_iterator const lit =
337                                                 latexargs.find(ins->name());
338                                 if (lit != latexargs.end()) {
339                                         Layout::latexarg const & arg = (*lit).second;
340                                         if (!arg.requires.empty()) {
341                                                 vector<string> req = getVectorFromString(arg.requires);
342                                                 required.insert(required.end(), req.begin(), req.end());
343                                         }
344                                 }
345                         }
346                 }
347         }
348
349         unsigned int const argnr = latexargs.size();
350         if (argnr == 0)
351                 return;
352
353         for (unsigned int i = 1; i <= argnr; ++i) {
354                 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
355                 bool inserted = false;
356                 if (lit != ilist.end()) {
357                         InsetArgument const * ins = (*lit).second;
358                         if (ins) {
359                                 Layout::LaTeXArgMap::const_iterator const lait =
360                                                 latexargs.find(ins->name());
361                                 if (lait != latexargs.end()) {
362                                         Layout::latexarg arg = (*lait).second;
363                                         docstring ldelim = arg.mandatory ?
364                                                         from_ascii("{") : from_ascii("[");
365                                         docstring rdelim = arg.mandatory ?
366                                                         from_ascii("}") : from_ascii("]");
367                                         if (!arg.ldelim.empty())
368                                                 ldelim = arg.ldelim;
369                                         if (!arg.rdelim.empty())
370                                                 rdelim = arg.rdelim;
371                                         ins->latexArgument(os, runparams, ldelim, rdelim, arg.presetarg);
372                                         inserted = true;
373                                 }
374                         }
375                 }
376                 if (!inserted) {
377                         Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
378                         Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
379                         for (; lait != laend; ++lait) {
380                                 string const name = item ? "item:" + convert<string>(i) : convert<string>(i);
381                                 if ((*lait).first == name) {
382                                         Layout::latexarg arg = (*lait).second;
383                                         if (arg.mandatory) {
384                                                 docstring ldelim = arg.ldelim.empty() ?
385                                                                 from_ascii("{") : arg.ldelim;
386                                                 docstring rdelim = arg.rdelim.empty() ?
387                                                                 from_ascii("}") : arg.rdelim;
388                                                 os << ldelim << arg.presetarg << rdelim;
389                                         } else if (!arg.presetarg.empty()) {
390                                                 docstring ldelim = arg.mandatory ?
391                                                                 from_ascii("{") : from_ascii("[");
392                                                 docstring rdelim = arg.mandatory ?
393                                                                 from_ascii("}") : from_ascii("]");
394                                                 if (!arg.ldelim.empty())
395                                                         ldelim = arg.ldelim;
396                                                 if (!arg.rdelim.empty())
397                                                         rdelim = arg.rdelim;
398                                                 os << ldelim << arg.presetarg << rdelim;
399                                         } else if (find(required.begin(), required.end(),
400                                                    (*lait).first) != required.end()) {
401                                                 docstring ldelim = arg.ldelim.empty() ?
402                                                                 from_ascii("[") : arg.ldelim;
403                                                 docstring rdelim = arg.rdelim.empty() ?
404                                                                 from_ascii("]") : arg.rdelim;
405                                                 os << ldelim << rdelim;
406                                         } else
407                                                 break;
408                                 }
409                         }
410                 }
411         }
412 }
413
414 namespace {
415
416 // output the proper paragraph start according to latextype.
417 void parStartCommand(Paragraph const & par, otexstream & os,
418                      OutputParams const & runparams, Layout const & style) 
419 {
420         switch (style.latextype) {
421         case LATEX_COMMAND:
422                 os << '\\' << from_ascii(style.latexname());
423
424                 // Command arguments
425                 if (!style.latexargs().empty())
426                         latexArgInsets(par, os, runparams, style.latexargs());
427                 os << from_ascii(style.latexparam());
428                 break;
429         case LATEX_ITEM_ENVIRONMENT:
430         case LATEX_LIST_ENVIRONMENT:
431                 os << "\\" + style.itemcommand();
432                 // Item arguments
433                 if (!style.itemargs().empty())
434                         latexArgInsets(par, os, runparams, style.itemargs(), true);
435                 os << " ";
436                 break;
437         case LATEX_BIB_ENVIRONMENT:
438                 // ignore this, the inset will write itself
439                 break;
440         default:
441                 break;
442         }
443 }
444
445 } // namespace anon
446
447 // FIXME: this should be anonymous
448 void TeXOnePar(Buffer const & buf,
449                Text const & text,
450                pit_type pit,
451                otexstream & os,
452                OutputParams const & runparams_in,
453                string const & everypar,
454                int start_pos, int end_pos)
455 {
456         BufferParams const & bparams = buf.params();
457         ParagraphList const & paragraphs = text.paragraphs();
458         Paragraph const & par = paragraphs.at(pit);
459         // FIXME This check should not really be needed.
460         // Perhaps we should issue an error if it is.
461         Layout const style = text.inset().forcePlainLayout() ?
462                 bparams.documentClass().plainLayout() : par.layout();
463
464         if (style.inpreamble)
465                 return;
466
467         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
468                 << everypar << "'");
469
470         OutputParams runparams = runparams_in;
471         runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
472         // We reinitialze par begin and end to be on the safe side
473         // with embedded inset as we don't know if they set those
474         // value correctly.
475         runparams.par_begin = 0;
476         runparams.par_end = 0;
477
478         bool const maintext = text.isMainText();
479         // we are at the beginning of an inset and CJK is already open;
480         // we count inheritation levels to get the inset nesting right.
481         if (pit == 0 && !maintext
482             && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
483                 cjk_inherited_ += 1;
484                 open_encoding_ = none;
485         }
486
487         if (text.inset().isPassThru()) {
488                 Font const outerfont = text.outerFont(pit);
489
490                 // No newline before first paragraph in this lyxtext
491                 if (pit > 0) {
492                         os << '\n';
493                         if (!text.inset().getLayout().parbreakIsNewline())
494                                 os << '\n';
495                 }
496
497                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
498                 return;
499         }
500
501         Paragraph const * nextpar = runparams.isLastPar
502                 ? 0 : &paragraphs.at(pit + 1);
503
504         if (style.pass_thru) {
505                 Font const outerfont = text.outerFont(pit);
506                 runparams.local_font = &par.getFirstFontSettings(bparams);
507                 parStartCommand(par, os, runparams, style);
508
509                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
510
511                 // I did not create a parEndCommand for this minuscule
512                 // task because in the other user of parStartCommand
513                 // the code is different (JMarc)
514                 if (style.isCommand())
515                         os << "}\n";
516                 else
517                         os << '\n';
518                 if (!style.parbreak_is_newline) {
519                         os << '\n';
520                 } else if (nextpar) {
521                         Layout const nextstyle = text.inset().forcePlainLayout()
522                                 ? bparams.documentClass().plainLayout()
523                                 : nextpar->layout();
524                         if (nextstyle.name() != style.name())
525                                 os << '\n';
526                 }
527
528                 return;
529         }
530
531         // This paragraph's language
532         Language const * const par_language = par.getParLanguage(bparams);
533         // The document's language
534         Language const * const doc_language = bparams.language;
535         // The language that was in effect when the environment this paragraph is
536         // inside of was opened
537         Language const * const outer_language =
538                 (runparams.local_font != 0) ?
539                         runparams.local_font->language() : doc_language;
540
541         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
542
543         // The previous language that was in effect is the language of the
544         // previous paragraph, unless the previous paragraph is inside an
545         // environment with nesting depth greater than (or equal to, but with
546         // a different layout) the current one. If there is no previous
547         // paragraph, the previous language is the outer language.
548         bool const use_prev_env_language = prev_env_language_ != 0
549                         && priorpar
550                         && priorpar->layout().isEnvironment()
551                         && (priorpar->getDepth() > par.getDepth()
552                             || (priorpar->getDepth() == par.getDepth()
553                                     && priorpar->layout() != par.layout()));
554         Language const * const prev_language =
555                 (pit != 0)
556                 ? (use_prev_env_language ? prev_env_language_
557                                          : priorpar->getParLanguage(bparams))
558                 : outer_language;
559
560
561         bool const use_polyglossia = runparams.use_polyglossia;
562         string const par_lang = use_polyglossia ?
563                 getPolyglossiaEnvName(par_language): par_language->babel();
564         string const prev_lang = use_polyglossia ?
565                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
566         string const doc_lang = use_polyglossia ?
567                 getPolyglossiaEnvName(doc_language) : doc_language->babel();
568         string const outer_lang = use_polyglossia ?
569                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
570         string lang_begin_command = use_polyglossia ?
571                 "\\begin{$$lang}" : lyxrc.language_command_begin;
572         string lang_end_command = use_polyglossia ?
573                 "\\end{$$lang}" : lyxrc.language_command_end;
574         // the '%' is necessary to prevent unwanted whitespace
575         string lang_command_termination = "%\n";
576
577         // In some insets (such as Arguments), we cannot use \selectlanguage
578         bool const localswitch = !use_polyglossia
579                 && text.inset().getLayout().forcelocalfontswitch();
580         if (localswitch) {
581                 lang_begin_command = lyxrc.language_command_local;
582                 lang_end_command = "}";
583                 lang_command_termination.clear();
584         }
585
586         if (par_lang != prev_lang
587                 // check if we already put language command in TeXEnvironment()
588                 && !(style.isEnvironment()
589                      && (pit == 0 || (priorpar->layout() != par.layout()
590                                           && priorpar->getDepth() <= par.getDepth())
591                                   || priorpar->getDepth() < par.getDepth())))
592         {
593                 if (!lang_end_command.empty() &&
594                     prev_lang != outer_lang &&
595                     !prev_lang.empty())
596                 {
597                         os << from_ascii(subst(lang_end_command,
598                                 "$$lang",
599                                 prev_lang))
600                            << lang_command_termination;
601                 }
602
603                 // We need to open a new language if we couldn't close the previous
604                 // one (because there's no language_command_end); and even if we closed
605                 // the previous one, if the current language is different than the
606                 // outer_language (which is currently in effect once the previous one
607                 // is closed).
608                 if ((lang_end_command.empty() || par_lang != outer_lang)
609                         && !par_lang.empty()) {
610                         // If we're inside an inset, and that inset is within an \L or \R
611                         // (or equivalents), then within the inset, too, any opposite
612                         // language paragraph should appear within an \L or \R (in addition
613                         // to, outside of, the normal language switch commands).
614                         // This behavior is not correct for ArabTeX, though.
615                         if (!use_polyglossia
616                             // not for ArabTeX
617                                 && par_language->lang() != "arabic_arabtex"
618                                 && outer_language->lang() != "arabic_arabtex"
619                             // are we in an inset?
620                             && runparams.local_font != 0
621                             // is the inset within an \L or \R?
622                             //
623                             // FIXME: currently, we don't check this; this means that
624                             // we'll have unnnecessary \L and \R commands, but that
625                             // doesn't seem to hurt (though latex will complain)
626                             //
627                             // is this paragraph in the opposite direction?
628                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
629                                 // FIXME: I don't have a working copy of the Arabi package, so
630                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
631                                 // or not...
632                                 if (par_language->lang() == "farsi")
633                                         os << "\\textFR{";
634                                 else if (outer_language->lang() == "farsi")
635                                         os << "\\textLR{";
636                                 else if (par_language->lang() == "arabic_arabi")
637                                         os << "\\textAR{";
638                                 else if (outer_language->lang() == "arabic_arabi")
639                                         os << "\\textLR{";
640                                 // remaining RTL languages currently is hebrew
641                                 else if (par_language->rightToLeft())
642                                         os << "\\R{";
643                                 else
644                                         os << "\\L{";
645                         }
646                         // With CJK, the CJK tag has to be closed first (see below)
647                         if (runparams.encoding->package() != Encoding::CJK
648                             && !par_lang.empty()) {
649                                 os << from_ascii(subst(
650                                         lang_begin_command,
651                                         "$$lang",
652                                         par_lang));
653                                 if (use_polyglossia
654                                     && !par_language->polyglossiaOpts().empty())
655                                                 os << "["
656                                                   << from_ascii(par_language->polyglossiaOpts())
657                                                   << "]";
658                                 os << lang_command_termination;
659                         }
660                 }
661         }
662
663         // Switch file encoding if necessary; no need to do this for "default"
664         // encoding, since this only affects the position of the outputted
665         // \inputencoding command; the encoding switch will occur when necessary
666         if (bparams.inputenc == "auto"
667                 && runparams.encoding->package() != Encoding::none) {
668                 // Look ahead for future encoding changes.
669                 // We try to output them at the beginning of the paragraph,
670                 // since the \inputencoding command is not allowed e.g. in
671                 // sections. For this reason we only set runparams.moving_arg
672                 // after checking for the encoding change, otherwise the
673                 // change would be always avoided by switchEncoding().
674                 for (pos_type i = 0; i < par.size(); ++i) {
675                         char_type const c = par.getChar(i);
676                         Encoding const * const encoding =
677                                 par.getFontSettings(bparams, i).language()->encoding();
678                         if (encoding->package() != Encoding::CJK
679                                 && runparams.encoding->package() == Encoding::inputenc
680                                 && c < 0x80)
681                                 continue;
682                         if (par.isInset(i))
683                                 break;
684                         // All characters before c are in the ASCII range, and
685                         // c is non-ASCII (but no inset), so change the
686                         // encoding to that required by the language of c.
687                         // With CJK, only add switch if we have CJK content at the beginning
688                         // of the paragraph
689                         if (i != 0 && encoding->package() == Encoding::CJK)
690                                 continue;
691
692                         pair<bool, int> enc_switch = switchEncoding(os.os(),
693                                                 bparams, runparams, *encoding);
694                         // the following is necessary after a CJK environment in a multilingual
695                         // context (nesting issue).
696                         if (par_language->encoding()->package() == Encoding::CJK
697                                 && open_encoding_ != CJK && cjk_inherited_ == 0) {
698                                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
699                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
700                                 open_encoding_ = CJK;
701                         }
702                         if (encoding->package() != Encoding::none && enc_switch.first) {
703                                 if (enc_switch.second > 0) {
704                                         // the '%' is necessary to prevent unwanted whitespace
705                                         os << "%\n";
706                                 }
707                                 // With CJK, the CJK tag had to be closed first (see above)
708                                 if (runparams.encoding->package() == Encoding::CJK
709                                     && !par_lang.empty()) {
710                                         os << from_ascii(subst(
711                                                 lang_begin_command,
712                                                 "$$lang",
713                                                 par_lang))
714                                         << lang_command_termination;
715                                 }
716                                 runparams.encoding = encoding;
717                         }
718                         break;
719                 }
720         }
721
722         runparams.moving_arg |= style.needprotect;
723         Encoding const * const prev_encoding = runparams.encoding;
724
725         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
726         if (par.allowParagraphCustomization()) {
727                 if (par.params().startOfAppendix()) {
728                         os << "\\appendix\n";
729                 }
730
731                 if (!par.params().spacing().isDefault()
732                         && (pit == 0 || !priorpar->hasSameLayout(par)))
733                 {
734                         os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
735                             << '\n';
736                 }
737
738                 if (style.isCommand()) {
739                         os << '\n';
740                 }
741         }
742
743         runparams.local_font = &par.getFirstFontSettings(bparams);
744         parStartCommand(par, os, runparams, style);
745         Font const outerfont = text.outerFont(pit);
746
747         // FIXME UNICODE
748         os << from_utf8(everypar);
749         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
750
751         // Make sure that \\par is done with the font of the last
752         // character if this has another size as the default.
753         // This is necessary because LaTeX (and LyX on the screen)
754         // calculates the space between the baselines according
755         // to this font. (Matthias)
756         //
757         // Is this really needed ? (Dekel)
758         // We do not need to use to change the font for the last paragraph
759         // or for a command.
760
761         Font const font = par.empty()
762                  ? par.getLayoutFont(bparams, outerfont)
763                  : par.getFont(bparams, par.size() - 1, outerfont);
764
765         bool const is_command = style.isCommand();
766
767         if (style.resfont.size() != font.fontInfo().size()
768             && nextpar
769             && !is_command) {
770                 os << '{';
771                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
772         } else if (is_command) {
773                 os << '}';
774                 if (runparams.encoding != prev_encoding) {
775                         runparams.encoding = prev_encoding;
776                         if (!runparams.isFullUnicode())
777                                 os << setEncoding(prev_encoding->iconvName());
778                 }
779         }
780
781         bool pending_newline = false;
782         bool unskip_newline = false;
783         switch (style.latextype) {
784         case LATEX_ITEM_ENVIRONMENT:
785         case LATEX_LIST_ENVIRONMENT:
786                 if (nextpar && (par.params().depth() < nextpar->params().depth()))
787                         pending_newline = true;
788                 break;
789         case LATEX_ENVIRONMENT: {
790                 // if its the last paragraph of the current environment
791                 // skip it otherwise fall through
792                 if (nextpar
793                         && (nextpar->layout() != par.layout()
794                         || nextpar->params().depth() != par.params().depth()))
795                         break;
796         }
797
798         // fall through possible
799         default:
800                 // we don't need it for the last paragraph!!!
801                 if (nextpar)
802                         pending_newline = true;
803         }
804
805         if (par.allowParagraphCustomization()) {
806                 if (!par.params().spacing().isDefault()
807                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
808                         if (pending_newline)
809                                 os << '\n';
810                         os << from_ascii(par.params().spacing().writeEnvirEnd(useSetSpace));
811                         pending_newline = true;
812                 }
813         }
814
815         // Closing the language is needed for the last paragraph; it is also
816         // needed if we're within an \L or \R that we may have opened above (not
817         // necessarily in this paragraph) and are about to close.
818         bool closing_rtl_ltr_environment = !use_polyglossia
819                 // not for ArabTeX
820                 && (par_language->lang() != "arabic_arabtex"
821                     && outer_language->lang() != "arabic_arabtex")
822                      // have we opened and \L or \R environment?
823                 && runparams.local_font != 0
824                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
825                 // are we about to close the language?
826                 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
827                    || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
828
829         if (closing_rtl_ltr_environment
830             || (runparams.isLastPar
831                 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
832                     || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
833                 // Since \selectlanguage write the language to the aux file,
834                 // we need to reset the language at the end of footnote or
835                 // float.
836
837                 if (pending_newline)
838                         os << '\n';
839
840                 // when the paragraph uses CJK, the language has to be closed earlier
841                 if (font.language()->encoding()->package() != Encoding::CJK) {
842                         if (lang_end_command.empty()) {
843                                 // If this is a child, we should restore the
844                                 // master language after the last paragraph.
845                                 Language const * const current_language =
846                                         (runparams.isLastPar && runparams.master_language)
847                                                 ? runparams.master_language
848                                                 : outer_language;
849                                 string const current_lang = use_polyglossia
850                                         ? getPolyglossiaEnvName(current_language)
851                                         : current_language->babel();
852                                 if (!current_lang.empty()) {
853                                         os << from_ascii(subst(
854                                                 lang_begin_command,
855                                                 "$$lang",
856                                                 current_lang));
857                                         pending_newline = !localswitch;
858                                         unskip_newline = !localswitch;
859                                 }
860                         } else if (!par_lang.empty()) {
861                                 os << from_ascii(subst(
862                                         lang_end_command,
863                                         "$$lang",
864                                         par_lang));
865                                 pending_newline = !localswitch;
866                                 unskip_newline = !localswitch;
867                         }
868                 }
869         }
870         if (closing_rtl_ltr_environment)
871                 os << "}";
872
873         if (pending_newline) {
874                 if (unskip_newline)
875                         // prevent unwanted whitespace
876                         os << '%';
877                 os << '\n';
878         }
879
880         // if this is a CJK-paragraph and the next isn't, close CJK
881         // also if the next paragraph is a multilingual environment (because of nesting)
882         if (nextpar
883                 && open_encoding_ == CJK
884                 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
885                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
886                 // inbetween environments, CJK has to be closed later (nesting!)
887                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
888                 os << "\\end{CJK}\n";
889                 open_encoding_ = none;
890         }
891
892         // If this is the last paragraph, close the CJK environment
893         // if necessary. If it's an environment, we'll have to \end that first.
894         if (runparams.isLastPar && !style.isEnvironment()) {
895                 switch (open_encoding_) {
896                         case CJK: {
897                                 // do nothing at the end of child documents
898                                 if (maintext && buf.masterBuffer() != &buf)
899                                         break;
900                                 // end of main text
901                                 if (maintext) {
902                                         os << "\n\\end{CJK}\n";
903                                 // end of an inset
904                                 } else
905                                         os << "\\end{CJK}";
906                                 open_encoding_ = none;
907                                 break;
908                         }
909                         case inputenc: {
910                                 os << "\\egroup";
911                                 open_encoding_ = none;
912                                 break;
913                         }
914                         case none:
915                         default:
916                                 // do nothing
917                                 break;
918                 }
919         }
920
921         // If this is the last paragraph, and a local_font was set upon entering
922         // the inset, and we're using "auto" or "default" encoding, the encoding
923         // should be set back to that local_font's encoding.
924         // However, do not change the encoding when a fully unicode aware backend
925         // such as XeTeX is used.
926         if (runparams.isLastPar && runparams_in.local_font != 0
927             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
928             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
929             && (!runparams.isFullUnicode())) {
930                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
931                 os << setEncoding(runparams_in.encoding->iconvName());
932         }
933         // Otherwise, the current encoding should be set for the next paragraph.
934         else
935                 runparams_in.encoding = runparams.encoding;
936
937
938         // we don't need a newline for the last paragraph!!!
939         // Note from JMarc: we will re-add a \n explicitly in
940         // TeXEnvironment, because it is needed in this case
941         if (nextpar) {
942                 Layout const & next_layout = nextpar->layout();
943                 if (style == next_layout
944                     // no blank lines before environments!
945                     || !next_layout.isEnvironment()
946                     // unless there's a depth change
947                     // FIXME What we really want to do here is put every \begin and \end
948                     // tag on a new line (which was not the case with nested environments).
949                     // But in the present state of play, we don't have access to the
950                     // information whether the current TeX row is empty or not.
951                     // For some ideas about how to fix this, see this thread:
952                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
953                     || nextpar->params().depth() != par.params().depth()) {
954                         os << '\n';
955                 }
956         }
957
958         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
959                 << &par << " next " << nextpar);
960
961         return;
962 }
963
964
965 // LaTeX all paragraphs
966 void latexParagraphs(Buffer const & buf,
967                      Text const & text,
968                      otexstream & os,
969                      OutputParams const & runparams,
970                      string const & everypar)
971 {
972         BufferParams const & bparams = buf.params();
973
974         bool const maintext = text.isMainText();
975         bool const is_child = buf.masterBuffer() != &buf;
976
977         // Open a CJK environment at the beginning of the main buffer
978         // if the document's language is a CJK language
979         // (but not in child documents)
980         if (maintext && !is_child
981             && bparams.encoding().package() == Encoding::CJK) {
982                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
983                 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
984                 open_encoding_ = CJK;
985         }
986         // if "auto begin" is switched off, explicitly switch the
987         // language on at start
988         string const mainlang = runparams.use_polyglossia
989                 ? getPolyglossiaEnvName(bparams.language)
990                 : bparams.language->babel();
991         string const lang_begin_command = runparams.use_polyglossia ?
992                 "\\begin{$$lang}" : lyxrc.language_command_begin;
993
994         if (maintext && !lyxrc.language_auto_begin &&
995             !mainlang.empty()) {
996                 // FIXME UNICODE
997                 os << from_utf8(subst(lang_begin_command,
998                                         "$$lang",
999                                         mainlang));
1000                 if (runparams.use_polyglossia
1001                     && !bparams.language->polyglossiaOpts().empty())
1002                         os << "["
1003                             << from_ascii(bparams.language->polyglossiaOpts())
1004                             << "]";
1005                 os << '\n';
1006         }
1007
1008         ParagraphList const & paragraphs = text.paragraphs();
1009         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
1010
1011         if (runparams.par_begin == runparams.par_end) {
1012                 // The full doc will be exported but it is easier to just rely on
1013                 // runparams range parameters that will be passed TeXEnvironment.
1014                 runparams.par_begin = 0;
1015                 runparams.par_end = paragraphs.size();
1016         }
1017
1018         pit_type pit = runparams.par_begin;
1019         // lastpit is for the language check after the loop.
1020         pit_type lastpit = pit;
1021         // variables used in the loop:
1022         bool was_title = false;
1023         bool already_title = false;
1024         DocumentClass const & tclass = bparams.documentClass();
1025
1026         for (; pit < runparams.par_end; ++pit) {
1027                 lastpit = pit;
1028                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1029
1030                 // FIXME This check should not be needed. We should
1031                 // perhaps issue an error if it is.
1032                 Layout const & layout = text.inset().forcePlainLayout() ?
1033                                 tclass.plainLayout() : par->layout();
1034
1035                 if (layout.intitle) {
1036                         if (already_title) {
1037                                 LYXERR0("Error in latexParagraphs: You"
1038                                         " should not mix title layouts"
1039                                         " with normal ones.");
1040                         } else if (!was_title) {
1041                                 was_title = true;
1042                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1043                                         os << "\\begin{"
1044                                                         << from_ascii(tclass.titlename())
1045                                                         << "}\n";
1046                                 }
1047                         }
1048                 } else if (was_title && !already_title) {
1049                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1050                                 os << "\\end{" << from_ascii(tclass.titlename())
1051                                                 << "}\n";
1052                         }
1053                         else {
1054                                 os << "\\" << from_ascii(tclass.titlename())
1055                                                 << "\n";
1056                         }
1057                         already_title = true;
1058                         was_title = false;
1059                 }
1060
1061
1062                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1063                         // This is a standard top level paragraph, TeX it and continue.
1064                         TeXOnePar(buf, text, pit, os, runparams, everypar);
1065                         continue;
1066                 }
1067                 
1068                 TeXEnvironmentData const data =
1069                         prepareEnvironment(buf, text, par, os, runparams);
1070                 // pit can be changed in TeXEnvironment.
1071                 TeXEnvironment(buf, text, runparams, pit, os);
1072                 finishEnvironment(os, runparams, data);
1073         }
1074
1075         if (pit == runparams.par_end) {
1076                         // Make sure that the last paragraph is
1077                         // correctly terminated (because TeXOnePar does
1078                         // not add a \n in this case)
1079                         //os << '\n';
1080         }
1081
1082         // It might be that we only have a title in this document
1083         if (was_title && !already_title) {
1084                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1085                         os << "\\end{" << from_ascii(tclass.titlename())
1086                            << "}\n";
1087                 } else {
1088                         os << "\\" << from_ascii(tclass.titlename())
1089                            << "\n";
1090                 }
1091         }
1092
1093         // if "auto end" is switched off, explicitly close the language at the end
1094         // but only if the last par is in a babel language
1095         string const lang_end_command = runparams.use_polyglossia ?
1096                 "\\end{$$lang}" : lyxrc.language_command_end;
1097         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1098                 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1099                 os << from_utf8(subst(lang_end_command,
1100                                         "$$lang",
1101                                         mainlang))
1102                         << '\n';
1103         }
1104
1105         // If the last paragraph is an environment, we'll have to close
1106         // CJK at the very end to do proper nesting.
1107         if (maintext && !is_child && open_encoding_ == CJK) {
1108                 os << "\\end{CJK}\n";
1109                 open_encoding_ = none;
1110         }
1111
1112         // reset inherited encoding
1113         if (cjk_inherited_ > 0) {
1114                 cjk_inherited_ -= 1;
1115                 if (cjk_inherited_ == 0)
1116                         open_encoding_ = CJK;
1117         }
1118 }
1119
1120
1121 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1122                    OutputParams const & runparams, Encoding const & newEnc,
1123                    bool force)
1124 {
1125         Encoding const & oldEnc = *runparams.encoding;
1126         bool moving_arg = runparams.moving_arg;
1127         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
1128                 || moving_arg))
1129                 return make_pair(false, 0);
1130
1131         // Do nothing if the encoding is unchanged.
1132         if (oldEnc.name() == newEnc.name())
1133                 return make_pair(false, 0);
1134
1135         // FIXME We ignore encoding switches from/to encodings that do
1136         // neither support the inputenc package nor the CJK package here.
1137         // This does of course only work in special cases (e.g. switch from
1138         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1139         // but it is the best we can do
1140         if (oldEnc.package() == Encoding::none
1141                 || newEnc.package() == Encoding::none)
1142                 return make_pair(false, 0);
1143
1144         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1145                 << oldEnc.name() << " to " << newEnc.name());
1146         os << setEncoding(newEnc.iconvName());
1147         if (bparams.inputenc == "default")
1148                 return make_pair(true, 0);
1149
1150         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1151         switch (newEnc.package()) {
1152                 case Encoding::none:
1153                 case Encoding::japanese:
1154                         // shouldn't ever reach here, see above
1155                         return make_pair(true, 0);
1156                 case Encoding::inputenc: {
1157                         int count = inputenc_arg.length();
1158                         if (oldEnc.package() == Encoding::CJK &&
1159                             open_encoding_ == CJK) {
1160                                 os << "\\end{CJK}";
1161                                 open_encoding_ = none;
1162                                 count += 9;
1163                         }
1164                         else if (oldEnc.package() == Encoding::inputenc &&
1165                                  open_encoding_ == inputenc) {
1166                                 os << "\\egroup";
1167                                 open_encoding_ = none;
1168                                 count += 7;
1169                         }
1170                         if (runparams.local_font != 0
1171                             &&  oldEnc.package() == Encoding::CJK) {
1172                                 // within insets, \inputenc switches need
1173                                 // to be embraced within \bgroup...\egroup;
1174                                 // else CJK fails.
1175                                 os << "\\bgroup";
1176                                 count += 7;
1177                                 open_encoding_ = inputenc;
1178                         }
1179                         // with the japanese option, inputenc is omitted.
1180                         if (runparams.use_japanese)
1181                                 return make_pair(true, count);
1182                         os << "\\inputencoding{" << inputenc_arg << '}';
1183                         return make_pair(true, count + 16);
1184                 }
1185                 case Encoding::CJK: {
1186                         int count = inputenc_arg.length();
1187                         if (oldEnc.package() == Encoding::CJK &&
1188                             open_encoding_ == CJK) {
1189                                 os << "\\end{CJK}";
1190                                 count += 9;
1191                         }
1192                         if (oldEnc.package() == Encoding::inputenc &&
1193                             open_encoding_ == inputenc) {
1194                                 os << "\\egroup";
1195                                 count += 7;
1196                         }
1197                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1198                            << from_ascii(bparams.fonts_cjk) << "}";
1199                         open_encoding_ = CJK;
1200                         return make_pair(true, count + 15);
1201                 }
1202         }
1203         // Dead code to avoid a warning:
1204         return make_pair(true, 0);
1205
1206 }
1207
1208 } // namespace lyx