]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
ce5be3911d37c4b37c6452ec37297e015ea38eca
[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->forcePlainLayout() ?
113                 bparams.documentClass().plainLayout() : 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                 // \begin must start on a new line
161                 os << "\n\\begin{" << from_ascii(style.latexname()) << '}';
162                 if (style.optionalargs > 0) {
163                         int ret = latexOptArgInsets(*pit, os, runparams,
164                                                     style.optionalargs);
165                         while (ret > 0) {
166                                 texrow.newline();
167                                 --ret;
168                         }
169                 }
170                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
171                         os << '{'
172                            << pit->params().labelWidthString()
173                            << "}\n";
174                 } else if (style.labeltype == LABEL_BIBLIO) {
175                         // ale970405
176                         os << '{' << bibitemWidest(buf) << "}\n";
177                 } else
178                         os << from_ascii(style.latexparam()) << '\n';
179                 texrow.newline();
180         }
181
182         // in multilingual environments, the CJK tags have to be nested properly
183         bool cjk_nested = false;
184         if (par_language->encoding()->package() == Encoding::CJK &&
185             open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
186                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
187                    << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
188                 open_encoding_ = CJK;
189                 cjk_nested = true;
190                 texrow.newline();
191         }
192
193         ParagraphList::const_iterator par = pit;
194         do {
195                 par = TeXOnePar(buf, text, par, os, texrow, runparams);
196
197                 if (par == paragraphs.end()) {
198                         // Make sure that the last paragraph is
199                         // correctly terminated (because TeXOnePar does
200                         // not add a \n in this case)
201                         os << '\n';
202                         texrow.newline();
203                 } else if (par->params().depth() > pit->params().depth()) {
204                         if (par->layout().isParagraph()) {
205                           // Thinko!
206                           // How to handle this? (Lgb)
207                           //&& !suffixIs(os, "\n\n")
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 } // namespace anon
255
256
257 int latexOptArgInsets(Paragraph const & par, odocstream & os,
258         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(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 const 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         ParagraphList::const_iterator priorpit = pit;
292         if (priorpit != paragraphs.begin())
293                 --priorpit;
294         ParagraphList::const_iterator nextpit = pit;
295         if (nextpit != paragraphs.end())
296                 ++nextpit;
297
298         OutputParams runparams = runparams_in;
299         runparams.isLastPar = nextpit == paragraphs.end();
300
301         if (runparams.verbatim) {
302                 int const dist = distance(paragraphs.begin(), pit);
303                 Font const outerfont = outerFont(dist, paragraphs);
304
305                 // No newline if only one paragraph in this lyxtext
306                 if (dist > 0) {
307                         os << '\n';
308                         texrow.newline();
309                 }
310
311                 /*bool need_par = */ pit->latex(bparams, outerfont,
312                         os, texrow, runparams);
313                 return nextpit;
314         }
315
316         Layout const style = pit->forcePlainLayout() ?
317                 bparams.documentClass().plainLayout() : pit->layout();
318
319         runparams.moving_arg |= style.needprotect;
320
321         bool const maintext = text.isMainText(buf);
322         // we are at the beginning of an inset and CJK is already open;
323         // we count inheritation levels to get the inset nesting right.
324         if (pit == paragraphs.begin() && !maintext
325             && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
326                 cjk_inherited_ += 1;
327                 open_encoding_ = none;
328         }
329
330         // This paragraph's language
331         Language const * const par_language = pit->getParLanguage(bparams);
332         // The document's language
333         Language const * const doc_language = bparams.language;
334         // The language that was in effect when the environment this paragraph is
335         // inside of was opened
336         Language const * const outer_language =
337                 (runparams.local_font != 0) ?
338                         runparams.local_font->language() : doc_language;
339         // The previous language that was in effect is either the language of
340         // the previous paragraph, if there is one, or else the outer language
341         // if there is no previous paragraph
342         Language const * const prev_language =
343                 (pit != paragraphs.begin()) ?
344                         priorpit->getParLanguage(bparams) : outer_language;
345
346         if (par_language->babel() != prev_language->babel()
347             // check if we already put language command in TeXEnvironment()
348             && !(style.isEnvironment()
349                  && (pit == paragraphs.begin() ||
350                      (priorpit->layout() != pit->layout() &&
351                       priorpit->getDepth() <= pit->getDepth())
352                      || priorpit->getDepth() < pit->getDepth())))
353         {
354                 if (!lyxrc.language_command_end.empty() &&
355                     prev_language->babel() != outer_language->babel() &&
356                     !prev_language->babel().empty())
357                 {
358                         os << from_ascii(subst(lyxrc.language_command_end,
359                                 "$$lang",
360                                 prev_language->babel()))
361                            // the '%' is necessary to prevent unwanted whitespace
362                            << "%\n";
363                         texrow.newline();
364                 }
365
366                 // We need to open a new language if we couldn't close the previous
367                 // one (because there's no language_command_end); and even if we closed
368                 // the previous one, if the current language is different than the
369                 // outer_language (which is currently in effect once the previous one
370                 // is closed).
371                 if ((lyxrc.language_command_end.empty() ||
372                      par_language->babel() != outer_language->babel()) &&
373                     !par_language->babel().empty()) {
374                         // If we're inside an inset, and that inset is within an \L or \R
375                         // (or equivalents), then within the inset, too, any opposite
376                         // language paragraph should appear within an \L or \R (in addition
377                         // to, outside of, the normal language switch commands).
378                         // This behavior is not correct for ArabTeX, though.
379                         if (    // not for ArabTeX
380                                         (par_language->lang() != "arabic_arabtex" &&
381                                          outer_language->lang() != "arabic_arabtex") &&
382                                         // are we in an inset?
383                                         runparams.local_font != 0 &&
384                                         // is the inset within an \L or \R?
385                                         //
386                                         // FIXME: currently, we don't check this; this means that
387                                         // we'll have unnnecessary \L and \R commands, but that
388                                         // doesn't seem to hurt (though latex will complain)
389                                         //
390                                         // is this paragraph in the opposite direction?
391                                         runparams.local_font->isRightToLeft() !=
392                                                 par_language->rightToLeft()
393                                 ) {
394                                 // FIXME: I don't have a working copy of the Arabi package, so
395                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
396                                 // or not...
397                                 if (par_language->lang() == "farsi")
398                                         os << "\\textFR{";
399                                 else if (outer_language->lang() == "farsi")
400                                         os << "\\textLR{";
401                                 else if (par_language->lang() == "arabic_arabi")
402                                         os << "\\textAR{";
403                                 else if (outer_language->lang() == "arabic_arabi")
404                                         os << "\\textLR{";
405                                 // remaining RTL languages currently is hebrew
406                                 else if (par_language->rightToLeft())
407                                         os << "\\R{";
408                                 else
409                                         os << "\\L{";
410                         }
411                         // With CJK, the CJK tag has to be closed first (see below)
412                         if (runparams.encoding->package() != Encoding::CJK) {
413                                 os << from_ascii(subst(
414                                         lyxrc.language_command_begin,
415                                         "$$lang",
416                                         par_language->babel()))
417                                    // the '%' is necessary to prevent unwanted whitespace
418                                    << "%\n";
419                                 texrow.newline();
420                         }
421                 }
422         }
423
424         // Switch file encoding if necessary; no need to do this for "default"
425         // encoding, since this only affects the position of the outputted
426         // \inputencoding command; the encoding switch will occur when necessary
427         if (bparams.inputenc == "auto" &&
428             runparams.encoding->package() != Encoding::none) {
429                 // Look ahead for future encoding changes.
430                 // We try to output them at the beginning of the paragraph,
431                 // since the \inputencoding command is not allowed e.g. in
432                 // sections.
433                 for (pos_type i = 0; i < pit->size(); ++i) {
434                         char_type const c = pit->getChar(i);
435                         Encoding const * const encoding =
436                                 pit->getFontSettings(bparams, i).language()->encoding();
437                         if (encoding->package() != Encoding::CJK &&
438                             runparams.encoding->package() == Encoding::inputenc &&
439                             c < 0x80)
440                                 continue;
441                         if (pit->isInset(i))
442                                 break;
443                         // All characters before c are in the ASCII range, and
444                         // c is non-ASCII (but no inset), so change the
445                         // encoding to that required by the language of c.
446                         // With CJK, only add switch if we have CJK content at the beginning
447                         // of the paragraph
448                         if (encoding->package() != Encoding::CJK || i == 0) {
449                                 OutputParams tmp_rp = runparams;
450                                 runparams.moving_arg = false;
451                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
452                                         *encoding);
453                                 runparams = tmp_rp;
454                                 // the following is necessary after a CJK environment in a multilingual
455                                 // context (nesting issue).
456                                 if (par_language->encoding()->package() == Encoding::CJK &&
457                                     open_encoding_ != CJK && cjk_inherited_ == 0) {
458                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
459                                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
460                                         open_encoding_ = CJK;
461                                         texrow.newline();
462                                 }
463                                 if (encoding->package() != Encoding::none && enc_switch.first) {
464                                         if (enc_switch.second > 0) {
465                                                 // the '%' is necessary to prevent unwanted whitespace
466                                                 os << "%\n";
467                                                 texrow.newline();
468                                         }
469                                         // With CJK, the CJK tag had to be closed first (see above)
470                                         if (runparams.encoding->package() == Encoding::CJK) {
471                                                 os << from_ascii(subst(
472                                                         lyxrc.language_command_begin,
473                                                         "$$lang",
474                                                         par_language->babel()))
475                                                 // the '%' is necessary to prevent unwanted whitespace
476                                                 << "%\n";
477                                                 texrow.newline();
478                                         }
479                                         runparams.encoding = encoding;
480                                 }
481                                 break;
482                         }
483                 }
484         }
485
486         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
487         if (pit->allowParagraphCustomization()) {
488                 if (pit->params().startOfAppendix()) {
489                         os << "\\appendix\n";
490                         texrow.newline();
491                 }
492
493                 if (!pit->params().spacing().isDefault()
494                         && (pit == paragraphs.begin()
495                             || !priorpit->hasSameLayout(*pit)))
496                 {
497                         os << from_ascii(pit->params().spacing().writeEnvirBegin(useSetSpace))
498                             << '\n';
499                         texrow.newline();
500                 }
501
502                 if (style.isCommand()) {
503                         os << '\n';
504                         texrow.newline();
505                 }
506         }
507
508         switch (style.latextype) {
509         case LATEX_COMMAND:
510                 os << '\\' << from_ascii(style.latexname());
511
512                 // Separate handling of optional argument inset.
513                 if (style.optionalargs > 0) {
514                         int ret = latexOptArgInsets(*pit, os, runparams,
515                                                     style.optionalargs);
516                         while (ret > 0) {
517                                 texrow.newline();
518                                 --ret;
519                         }
520                 }
521                 else
522                         os << from_ascii(style.latexparam());
523                 break;
524         case LATEX_ITEM_ENVIRONMENT:
525         case LATEX_LIST_ENVIRONMENT:
526                 os << "\\item ";
527                 break;
528         case LATEX_BIB_ENVIRONMENT:
529                 // ignore this, the inset will write itself
530                 break;
531         default:
532                 break;
533         }
534
535         Font const outerfont = outerFont(distance(paragraphs.begin(), pit),
536                           paragraphs);
537
538         // FIXME UNICODE
539         os << from_utf8(everypar);
540         bool need_par = pit->latex(bparams, outerfont,
541                                              os, texrow, runparams);
542
543         // Make sure that \\par is done with the font of the last
544         // character if this has another size as the default.
545         // This is necessary because LaTeX (and LyX on the screen)
546         // calculates the space between the baselines according
547         // to this font. (Matthias)
548         //
549         // Is this really needed ? (Dekel)
550         // We do not need to use to change the font for the last paragraph
551         // or for a command.
552
553         Font const font = pit->empty()
554                  ? pit->getLayoutFont(bparams, outerfont)
555                  : pit->getFont(bparams, pit->size() - 1, outerfont);
556
557         bool is_command = style.isCommand();
558
559         if (style.resfont.size() != font.fontInfo().size()
560             && nextpit != paragraphs.end()
561             && !is_command) {
562                 if (!need_par)
563                         os << '{';
564                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
565         } else if (need_par) {
566                 os << "\\par}";
567         } else if (is_command)
568                 os << '}';
569
570         bool pending_newline = false;
571         switch (style.latextype) {
572         case LATEX_ITEM_ENVIRONMENT:
573         case LATEX_LIST_ENVIRONMENT:
574                 if (nextpit != paragraphs.end()
575                     && (pit->params().depth() < nextpit->params().depth()))
576                         pending_newline = true;
577                 break;
578         case LATEX_ENVIRONMENT: {
579                 // if its the last paragraph of the current environment
580                 // skip it otherwise fall through
581                 ParagraphList::const_iterator next = nextpit;
582
583                 if (next != paragraphs.end() && (next->layout() != pit->layout()
584                         || next->params().depth() != pit->params().depth()))
585                         break;
586         }
587
588                 // fall through possible
589         default:
590                 // we don't need it for the last paragraph!!!
591                 if (nextpit != paragraphs.end())
592                         pending_newline = true;
593         }
594
595         if (pit->allowParagraphCustomization()) {
596                 if (!pit->params().spacing().isDefault()
597                         && (nextpit == paragraphs.end() || !nextpit->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                 ((nextpit != paragraphs.end() &&
620                   par_language->babel() !=
621                         (nextpit->getParLanguage(bparams))->babel()) ||
622                  (nextpit == paragraphs.end() &&
623                   par_language->babel() != outer_language->babel()));
624
625         if (closing_rtl_ltr_environment || (nextpit == 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 (nextpit != paragraphs.end() && open_encoding_ == CJK &&
665             (nextpit->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
666              nextpit->layout().isEnvironment() && nextpit->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 (nextpit == paragraphs.end() && !style.isEnvironment()) {
676                 switch (open_encoding_) {
677                         case CJK: {
678                                 // do nothing at the end of child documents
679                                 if (maintext && buf.masterBuffer() != &buf)
680                                         break;
681                                 // end of main text
682                                 if (maintext) {
683                                         os << '\n';
684                                         texrow.newline();
685                                         os << "\\end{CJK}\n";
686                                         texrow.newline();
687                                 // end of an inset
688                                 } else
689                                         os << "\\end{CJK}";
690                                 open_encoding_ = none;
691                                 break;
692                         }
693                         case inputenc: {
694                                 os << "\\egroup";
695                                 open_encoding_ = none;
696                                 break;
697                         }
698                         case none:
699                         default:
700                                 // do nothing
701                                 break;
702                 }
703         }
704
705         // If this is the last paragraph, and a local_font was set upon entering
706         // the inset, and we're using "auto" or "default" encoding, the encoding
707         // should be set back to that local_font's encoding.
708         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
709             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
710             && (bparams.inputenc == "auto" || bparams.inputenc == "default")) {
711                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
712                 os << setEncoding(runparams_in.encoding->iconvName());
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 (nextpit != paragraphs.end()) {
723                 Layout const & next_layout = nextpit->layout();
724                 // no blank lines before environments!
725                 if (!next_layout.isEnvironment() || style == next_layout) {
726                         os << '\n';
727                         texrow.newline();
728                 }
729         }
730
731         if (nextpit != paragraphs.end())
732                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
733
734         return nextpit;
735 }
736
737 } // anon namespace
738
739
740 // LaTeX all paragraphs
741 void latexParagraphs(Buffer const & buf,
742                      Text const & text,
743                      odocstream & os,
744                      TexRow & texrow,
745                      OutputParams const & runparams,
746                      string const & everypar)
747 {
748         bool was_title = false;
749         bool already_title = false;
750         BufferParams const & bparams = buf.params();
751         DocumentClass const & tclass = bparams.documentClass();
752         ParagraphList const & paragraphs = text.paragraphs();
753         ParagraphList::const_iterator par = paragraphs.begin();
754         ParagraphList::const_iterator endpar = paragraphs.end();
755
756         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
757         // if only part of the paragraphs will be outputed
758         if (runparams.par_begin !=  runparams.par_end) {
759                 par = boost::next(paragraphs.begin(), runparams.par_begin);
760                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
761                 // runparams will be passed to nested paragraphs, so
762                 // we have to reset the range parameters.
763                 const_cast<OutputParams&>(runparams).par_begin = 0;
764                 const_cast<OutputParams&>(runparams).par_end = 0;
765         }
766
767         bool const maintext = text.isMainText(buf);
768         bool const is_child = buf.masterBuffer() != &buf;
769
770         // Open a CJK environment at the beginning of the main buffer
771         // if the document's language is a CJK language
772         // (but not in child documents)
773         if (maintext && !is_child
774             && bparams.encoding().package() == Encoding::CJK) {
775                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
776                 << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
777                 texrow.newline();
778                 open_encoding_ = CJK;
779         }
780         // if "auto begin" is switched off, explicitely switch the
781         // language on at start
782         if (maintext && !lyxrc.language_auto_begin &&
783             !bparams.language->babel().empty()) {
784                 // FIXME UNICODE
785                 os << from_utf8(subst(lyxrc.language_command_begin,
786                                         "$$lang",
787                                         bparams.language->babel()))
788                         << '\n';
789         texrow.newline();
790         }
791
792         ParagraphList::const_iterator lastpar;
793         // if only_body
794         while (par != endpar) {
795                 lastpar = par;
796                 Layout const & layout = par->forcePlainLayout() ?
797                                 tclass.plainLayout() :
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.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                 if (distance(lastpar, par) >= distance(lastpar, endpar))
837                         break;
838         }
839
840         // It might be that we only have a title in this document
841         if (was_title && !already_title) {
842                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
843                         os << "\\end{" << from_ascii(tclass.titlename())
844                             << "}\n";
845                 }
846                 else {
847                         os << "\\" << from_ascii(tclass.titlename())
848                             << "\n";
849                                 }
850                 texrow.newline();
851         }
852
853         // if "auto end" is switched off, explicitely close the language at the end
854         // but only if the last par is in a babel language
855         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
856                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
857                 os << from_utf8(subst(lyxrc.language_command_end,
858                                         "$$lang",
859                                         bparams.language->babel()))
860                         << '\n';
861                 texrow.newline();
862         }
863
864         // If the last paragraph is an environment, we'll have to close
865         // CJK at the very end to do proper nesting.
866         if (maintext && !is_child && open_encoding_ == CJK) {
867                 os << "\\end{CJK}\n";
868                 texrow.newline();
869                 open_encoding_ = none;
870         }
871
872         // reset inherited encoding
873         if (cjk_inherited_ > 0) {
874                 cjk_inherited_ -= 1;
875                 if (cjk_inherited_ == 0)
876                         open_encoding_ = CJK;
877         }
878 }
879
880
881 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
882                    OutputParams const & runparams, Encoding const & newEnc,
883                    bool force)
884 {
885         Encoding const & oldEnc = *runparams.encoding;
886         bool moving_arg = runparams.moving_arg;
887         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
888                 || moving_arg))
889                 return make_pair(false, 0);
890
891         // Do nothing if the encoding is unchanged.
892         if (oldEnc.name() == newEnc.name())
893                 return make_pair(false, 0);
894
895         // FIXME We ignore encoding switches from/to encodings that do
896         // neither support the inputenc package nor the CJK package here.
897         // This does of course only work in special cases (e.g. switch from
898         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
899         // but it is the best we can do
900         if (oldEnc.package() == Encoding::none
901                 || newEnc.package() == Encoding::none)
902                 return make_pair(false, 0);
903
904         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
905                 << oldEnc.name() << " to " << newEnc.name());
906         os << setEncoding(newEnc.iconvName());
907         if (bparams.inputenc == "default")
908                 return make_pair(true, 0);
909
910         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
911         switch (newEnc.package()) {
912                 case Encoding::none:
913                 case Encoding::japanese:
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
931                             && oldEnc.package() == Encoding::CJK) {
932                                 // within insets, \inputenc switches need
933                                 // to be embraced within \bgroup...\egroup;
934                                 // else CJK fails.
935                                 os << "\\bgroup";
936                                 count += 7;
937                                 open_encoding_ = inputenc;
938                         }
939                         // with the japanese option, inputenc is omitted.
940                         if (runparams.use_japanese)
941                                 return make_pair(true, count);
942                         os << "\\inputencoding{" << inputenc_arg << '}';
943                         return make_pair(true, count + 16);
944                 }
945                 case Encoding::CJK: {
946                         int count = inputenc_arg.length();
947                         if (oldEnc.package() == Encoding::CJK &&
948                             open_encoding_ == CJK) {
949                                 os << "\\end{CJK}";
950                                 count += 9;
951                         }
952                         if (oldEnc.package() == Encoding::inputenc &&
953                             open_encoding_ == inputenc) {
954                                 os << "\\egroup";
955                                 count += 7;
956                         }
957                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
958                            << from_ascii(bparams.fontsCJK) << "}";
959                         open_encoding_ = CJK;
960                         return make_pair(true, count + 15);
961                 }
962         }
963         // Dead code to avoid a warning:
964         return make_pair(true, 0);
965
966 }
967
968 } // namespace lyx