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