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