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