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