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