]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
* Doxy
[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         bool const useSetSpace = bparams.getTextClass().provides("SetSpace");
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(useSetSpace))
506                             << '\n';
507                         texrow.newline();
508                 }
509
510                 if (style->isCommand()) {
511                         os << '\n';
512                         texrow.newline();
513                 }
514         }
515
516         switch (style->latextype) {
517         case LATEX_COMMAND:
518                 os << '\\' << from_ascii(style->latexname());
519
520                 // Separate handling of optional argument inset.
521                 if (style->optionalargs > 0) {
522                         int ret = latexOptArgInsets(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(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(useSetSpace));
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 (distance(lastpar, par) >= 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 & newEnc)
870 {
871         Encoding const oldEnc = *runparams.encoding;
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