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