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