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