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