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