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