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