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