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