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