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