]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
4736530e8322d8e806d1663d67833a0d97940321
[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
65 ParagraphList::const_iterator
66 TeXDeeper(Buffer const & buf,
67           Text const & text,
68           ParagraphList::const_iterator pit,
69           odocstream & os, TexRow & texrow,
70           OutputParams const & runparams)
71 {
72         LYXERR(Debug::LATEX, "TeXDeeper...     " << &*pit);
73         ParagraphList::const_iterator par = pit;
74
75         ParagraphList const & paragraphs = text.paragraphs();
76
77         while (par != paragraphs.end() &&
78                                         par->params().depth() == pit->params().depth()) {
79                 // FIXME This test should not be necessary.
80                 // We should perhaps issue an error if it is.
81                 Layout const & style = par->forcePlainLayout() ?
82                         buf.params().documentClass().plainLayout() : par->layout();
83                 if (style.isEnvironment()) {
84                         par = TeXEnvironment(buf, text, par,
85                                              os, texrow, runparams);
86                 } else {
87                         par = TeXOnePar(buf, text, par,
88                                              os, texrow, runparams);
89                 }
90         }
91         LYXERR(Debug::LATEX, "TeXDeeper...done ");
92
93         return par;
94 }
95
96
97 ParagraphList::const_iterator
98 TeXEnvironment(Buffer const & buf,
99                Text const & text,
100                ParagraphList::const_iterator pit,
101                odocstream & os, TexRow & texrow,
102                OutputParams const & runparams)
103 {
104         LYXERR(Debug::LATEX, "TeXEnvironment...     " << &*pit);
105
106         BufferParams const & bparams = buf.params();
107
108         // FIXME This test should not be necessary.
109         // We should perhaps issue an error if it is.
110         Layout const & style = pit->forcePlainLayout() ?
111                 bparams.documentClass().plainLayout() : 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(*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                         if (pit->params().labelWidthString().empty())
173                                 os << '{' << bibitemWidest(buf) << "}\n";
174                         else
175                                 os << '{'
176                                   << pit->params().labelWidthString()
177                                   << "}\n";
178                 } else
179                         os << from_ascii(style.latexparam()) << '\n';
180                 texrow.newline();
181         }
182
183         // in multilingual environments, the CJK tags have to be nested properly
184         bool cjk_nested = false;
185         if (par_language->encoding()->package() == Encoding::CJK &&
186             open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
187                 if (prev_par_language->encoding()->package() == Encoding::CJK)
188                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
189                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
190                 open_encoding_ = CJK;
191                 cjk_nested = true;
192                 texrow.newline();
193         }
194
195         ParagraphList::const_iterator par = pit;
196         do {
197                 par = TeXOnePar(buf, text, par, os, texrow, runparams);
198
199                 if (par == paragraphs.end()) {
200                         // Make sure that the last paragraph is
201                         // correctly terminated (because TeXOnePar does
202                         // not add a \n in this case)
203                         os << '\n';
204                         texrow.newline();
205                 } else if (par->params().depth() > pit->params().depth()) {
206                         if (par->layout().isParagraph()) {
207                           // Thinko!
208                           // How to handle this? (Lgb)
209                           //&& !suffixIs(os, "\n\n")
210
211                                 // There should be at least one '\n' already
212                                 // but we need there to be two for Standard
213                                 // paragraphs that are depth-increment'ed to be
214                                 // output correctly.  However, tables can
215                                 // also be paragraphs so don't adjust them.
216                                 // ARRae
217                                 // Thinkee:
218                                 // Will it ever harm to have one '\n' too
219                                 // many? i.e. that we sometimes will have
220                                 // three in a row. (Lgb)
221                                 os << '\n';
222                                 texrow.newline();
223                         }
224                         par = TeXDeeper(buf, text, par, os, texrow,
225                                         runparams);
226                 }
227         } while (par != paragraphs.end()
228                  && par->layout() == pit->layout()
229                  && par->params().depth() == pit->params().depth()
230                  && par->params().leftIndent() == pit->params().leftIndent());
231
232         if (open_encoding_ == CJK && cjk_nested) {
233                 // We need to close the encoding even if it does not change
234                 // to do correct environment nesting
235                 os << "\\end{CJK}\n";
236                 texrow.newline();
237                 open_encoding_ = none;
238         }
239
240         if (style.isEnvironment()) {
241                 os << "\\end{" << from_ascii(style.latexname()) << "}\n";
242                 texrow.newline();
243         }
244
245         if (leftindent_open) {
246                 os << "\\end{LyXParagraphLeftIndent}\n";
247                 texrow.newline();
248         }
249
250         if (par != paragraphs.end())
251                 LYXERR(Debug::LATEX, "TeXEnvironment...done " << &*par);
252
253         return par;
254 }
255
256 } // namespace anon
257
258
259 int latexOptArgInsets(Paragraph const & par, odocstream & os,
260         OutputParams const & runparams, int number)
261 {
262         int lines = 0;
263
264         InsetList::const_iterator it = par.insetList().begin();
265         InsetList::const_iterator end = par.insetList().end();
266         for (; it != end && number > 0 ; ++it) {
267                 if (it->inset->lyxCode() == OPTARG_CODE) {
268                         InsetOptArg * ins =
269                                 static_cast<InsetOptArg *>(it->inset);
270                         lines += ins->latexOptional(os, runparams);
271                         --number;
272                 }
273         }
274         return lines;
275 }
276
277 // FIXME: this should be anonymous
278 ParagraphList::const_iterator 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           int start_pos, int end_pos)
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 const priorpit = 
292                 pit == paragraphs.begin() ? pit : boost::prior(pit);
293         ParagraphList::const_iterator const nextpit = 
294                 pit == paragraphs.end() ? pit : boost::next(pit);
295
296         OutputParams runparams = runparams_in;
297         runparams.isLastPar = nextpit == paragraphs.end();
298
299         if (runparams.verbatim) {
300                 int const dist = distance(paragraphs.begin(), pit);
301                 Font const outerfont = outerFont(dist, paragraphs);
302
303                 // No newline if only one paragraph in this lyxtext
304                 if (dist > 0) {
305                         os << '\n';
306                         texrow.newline();
307                 }
308
309                 /*bool need_par = */ pit->latex(bparams, outerfont,
310                         os, texrow, runparams, start_pos, end_pos);
311                 return nextpit;
312         }
313
314         // FIXME This check should not really be needed.
315         // Perhaps we should issue an error if it is.
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                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
450                                         *encoding);
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                                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\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, start_pos, end_pos);
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 const 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                 if (nextpit != paragraphs.end() && 
579                     (nextpit->layout() != pit->layout()
580                      || nextpit->params().depth() != pit->params().depth()))
581                         break;
582         }
583
584         // fall through possible
585         default:
586                 // we don't need it for the last paragraph!!!
587                 if (nextpit != paragraphs.end())
588                         pending_newline = true;
589         }
590
591         if (pit->allowParagraphCustomization()) {
592                 if (!pit->params().spacing().isDefault()
593                         && (nextpit == paragraphs.end() || !nextpit->hasSameLayout(*pit)))
594                 {
595                         if (pending_newline) {
596                                 os << '\n';
597                                 texrow.newline();
598                         }
599                         os << from_ascii(pit->params().spacing().writeEnvirEnd(useSetSpace));
600                         pending_newline = true;
601                 }
602         }
603
604         // Closing the language is needed for the last paragraph; it is also
605         // needed if we're within an \L or \R that we may have opened above (not
606         // necessarily in this paragraph) and are about to close.
607         bool closing_rtl_ltr_environment =
608                 // not for ArabTeX
609                 (par_language->lang() != "arabic_arabtex" &&
610                  outer_language->lang() != "arabic_arabtex") &&
611                 // have we opened and \L or \R environment?
612                 runparams.local_font != 0 &&
613                 runparams.local_font->isRightToLeft() != par_language->rightToLeft() &&
614                 // are we about to close the language?
615                 ((nextpit != paragraphs.end() &&
616                   par_language->babel() !=
617                     (nextpit->getParLanguage(bparams))->babel()) ||
618                   (nextpit == paragraphs.end() &&
619                     par_language->babel() != outer_language->babel()));
620
621         if (closing_rtl_ltr_environment || (nextpit == paragraphs.end()
622             && par_language->babel() != outer_language->babel())) {
623                 // Since \selectlanguage write the language to the aux file,
624                 // we need to reset the language at the end of footnote or
625                 // float.
626
627                 if (pending_newline) {
628                         os << '\n';
629                         texrow.newline();
630                 }
631                 // when the paragraph uses CJK, the language has to be closed earlier
632                 if (font.language()->encoding()->package() != Encoding::CJK) {
633                         if (lyxrc.language_command_end.empty()) {
634                                 if (!prev_language->babel().empty()) {
635                                         os << from_ascii(subst(
636                                                 lyxrc.language_command_begin,
637                                                 "$$lang",
638                                                 prev_language->babel()));
639                                         pending_newline = true;
640                                 }
641                         } else if (!par_language->babel().empty()) {
642                                 os << from_ascii(subst(
643                                         lyxrc.language_command_end,
644                                         "$$lang",
645                                         par_language->babel()));
646                                 pending_newline = true;
647                         }
648                 }
649         }
650         if (closing_rtl_ltr_environment)
651                 os << "}";
652
653         if (pending_newline) {
654                 os << '\n';
655                 texrow.newline();
656         }
657
658         // if this is a CJK-paragraph and the next isn't, close CJK
659         // also if the next paragraph is a multilingual environment (because of nesting)
660         if (nextpit != paragraphs.end() && open_encoding_ == CJK &&
661             (nextpit->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
662              (nextpit->layout().isEnvironment() && nextpit->isMultiLingual(bparams)))
663              // inbetween environments, CJK has to be closed later (nesting!)
664              && (!style.isEnvironment() || !nextpit->layout().isEnvironment())) {
665                 os << "\\end{CJK}\n";
666                 open_encoding_ = none;
667         }
668
669         // If this is the last paragraph, close the CJK environment
670         // if necessary. If it's an environment, we'll have to \end that first.
671         if (nextpit == paragraphs.end() && !style.isEnvironment()) {
672                 switch (open_encoding_) {
673                         case CJK: {
674                                 // do nothing at the end of child documents
675                                 if (maintext && buf.masterBuffer() != &buf)
676                                         break;
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, and we're using "auto" or "default" encoding, the encoding
703         // should be set back to that local_font's encoding.
704         // However, do not change the encoding when XeTeX is used.
705         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
706             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
707             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
708             && (!bparams.useXetex)) {
709                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
710                 os << setEncoding(runparams_in.encoding->iconvName());
711         }
712         // Otherwise, the current encoding should be set for the next paragraph.
713         else
714                 runparams_in.encoding = runparams.encoding;
715
716
717         // we don't need a newline for the last paragraph!!!
718         // Note from JMarc: we will re-add a \n explicitly in
719         // TeXEnvironment, because it is needed in this case
720         if (nextpit != paragraphs.end()) {
721                 Layout const & next_layout = nextpit->layout();
722                 if (style == next_layout
723                     // no blank lines before environments!
724                     || !next_layout.isEnvironment()
725                     // unless there's a depth change
726                     // FIXME What we really want to do here is put every \begin and \end
727                     // tag on a new line (which was not the case with nested environments).
728                     // But in the present state of play, we don't have access to the
729                     // information whether the current TeX row is empty or not.
730                     // For some ideas about how to fix this, see this thread:
731                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
732                     || nextpit->params().depth() != pit->params().depth()) {
733                         os << '\n';
734                         texrow.newline();
735                 }
736         }
737
738         if (nextpit != paragraphs.end())
739                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
740
741         return nextpit;
742 }
743
744
745 // LaTeX all paragraphs
746 void latexParagraphs(Buffer const & buf,
747                      Text const & text,
748                      odocstream & os,
749                      TexRow & texrow,
750                      OutputParams const & runparams,
751                      string const & everypar)
752 {
753         bool was_title = false;
754         bool already_title = false;
755         BufferParams const & bparams = buf.params();
756         DocumentClass const & tclass = bparams.documentClass();
757         ParagraphList const & paragraphs = text.paragraphs();
758         ParagraphList::const_iterator par = paragraphs.begin();
759         ParagraphList::const_iterator endpar = paragraphs.end();
760
761         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
762         // if only part of the paragraphs will be outputed
763         if (runparams.par_begin !=  runparams.par_end) {
764                 par = boost::next(paragraphs.begin(), runparams.par_begin);
765                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
766                 // runparams will be passed to nested paragraphs, so
767                 // we have to reset the range parameters.
768                 const_cast<OutputParams&>(runparams).par_begin = 0;
769                 const_cast<OutputParams&>(runparams).par_end = 0;
770         }
771
772         bool const maintext = text.isMainText(buf);
773         bool const is_child = buf.masterBuffer() != &buf;
774
775         // Open a CJK environment at the beginning of the main buffer
776         // if the document's language is a CJK language
777         // (but not in child documents)
778         if (maintext && !is_child
779             && bparams.encoding().package() == Encoding::CJK) {
780                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
781                 << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
782                 texrow.newline();
783                 open_encoding_ = CJK;
784         }
785         // if "auto begin" is switched off, explicitely switch the
786         // language on at start
787         if (maintext && !lyxrc.language_auto_begin &&
788             !bparams.language->babel().empty()) {
789                 // FIXME UNICODE
790                 os << from_utf8(subst(lyxrc.language_command_begin,
791                                         "$$lang",
792                                         bparams.language->babel()))
793                         << '\n';
794         texrow.newline();
795         }
796
797         ParagraphList::const_iterator lastpar;
798         // if only_body
799         while (par != endpar) {
800                 lastpar = par;
801                 // FIXME This check should not be needed. We should
802                 // perhaps issue an error if it is.
803                 Layout const & layout = par->forcePlainLayout() ?
804                                 tclass.plainLayout() : par->layout();
805
806                 if (layout.intitle) {
807                         if (already_title) {
808                                 lyxerr << "Error in latexParagraphs: You"
809                                         " should not mix title layouts"
810                                         " with normal ones." << endl;
811                         } else if (!was_title) {
812                                 was_title = true;
813                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
814                                         os << "\\begin{"
815                                                         << from_ascii(tclass.titlename())
816                                                         << "}\n";
817                                         texrow.newline();
818                                 }
819                         }
820                 } else if (was_title && !already_title) {
821                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
822                                 os << "\\end{" << from_ascii(tclass.titlename())
823                                                 << "}\n";
824                         }
825                         else {
826                                 os << "\\" << from_ascii(tclass.titlename())
827                                                 << "\n";
828                         }
829                         texrow.newline();
830                         already_title = true;
831                         was_title = false;
832                 }
833
834                 if (layout.isEnvironment() ||
835                                         !par->params().leftIndent().zero()) {
836                         par = TeXEnvironment(buf, text, par, os,
837                                                                 texrow, runparams);
838                 } else {
839                         par = TeXOnePar(buf, text, par, os, texrow,
840                                         runparams, everypar);
841                 }
842                 if (distance(lastpar, par) >= distance(lastpar, endpar))
843                         break;
844         }
845
846         // It might be that we only have a title in this document
847         if (was_title && !already_title) {
848                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
849                         os << "\\end{" << from_ascii(tclass.titlename())
850                             << "}\n";
851                 }
852                 else {
853                         os << "\\" << from_ascii(tclass.titlename())
854                             << "\n";
855                                 }
856                 texrow.newline();
857         }
858
859         // if "auto end" is switched off, explicitely close the language at the end
860         // but only if the last par is in a babel language
861         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
862                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
863                 os << from_utf8(subst(lyxrc.language_command_end,
864                                         "$$lang",
865                                         bparams.language->babel()))
866                         << '\n';
867                 texrow.newline();
868         }
869
870         // If the last paragraph is an environment, we'll have to close
871         // CJK at the very end to do proper nesting.
872         if (maintext && !is_child && open_encoding_ == CJK) {
873                 os << "\\end{CJK}\n";
874                 texrow.newline();
875                 open_encoding_ = none;
876         }
877
878         // reset inherited encoding
879         if (cjk_inherited_ > 0) {
880                 cjk_inherited_ -= 1;
881                 if (cjk_inherited_ == 0)
882                         open_encoding_ = CJK;
883         }
884 }
885
886
887 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
888                    OutputParams const & runparams, Encoding const & newEnc,
889                    bool force)
890 {
891         Encoding const & oldEnc = *runparams.encoding;
892         bool moving_arg = runparams.moving_arg;
893         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
894                 || moving_arg))
895                 return make_pair(false, 0);
896
897         // Do nothing if the encoding is unchanged.
898         if (oldEnc.name() == newEnc.name())
899                 return make_pair(false, 0);
900
901         // FIXME We ignore encoding switches from/to encodings that do
902         // neither support the inputenc package nor the CJK package here.
903         // This does of course only work in special cases (e.g. switch from
904         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
905         // but it is the best we can do
906         if (oldEnc.package() == Encoding::none
907                 || newEnc.package() == Encoding::none)
908                 return make_pair(false, 0);
909
910         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
911                 << oldEnc.name() << " to " << newEnc.name());
912         os << setEncoding(newEnc.iconvName());
913         if (bparams.inputenc == "default")
914                 return make_pair(true, 0);
915
916         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
917         switch (newEnc.package()) {
918                 case Encoding::none:
919                 case Encoding::japanese:
920                         // shouldn't ever reach here, see above
921                         return make_pair(true, 0);
922                 case Encoding::inputenc: {
923                         int count = inputenc_arg.length();
924                         if (oldEnc.package() == Encoding::CJK &&
925                             open_encoding_ == CJK) {
926                                 os << "\\end{CJK}";
927                                 open_encoding_ = none;
928                                 count += 9;
929                         }
930                         else if (oldEnc.package() == Encoding::inputenc &&
931                                  open_encoding_ == inputenc) {
932                                 os << "\\egroup";
933                                 open_encoding_ = none;
934                                 count += 7;
935                         }
936                         if (runparams.local_font != 0
937                             &&  oldEnc.package() == Encoding::CJK) {
938                                 // within insets, \inputenc switches need
939                                 // to be embraced within \bgroup...\egroup;
940                                 // else CJK fails.
941                                 os << "\\bgroup";
942                                 count += 7;
943                                 open_encoding_ = inputenc;
944                         }
945                         // with the japanese option, inputenc is omitted.
946                         if (runparams.use_japanese)
947                                 return make_pair(true, count);
948                         os << "\\inputencoding{" << inputenc_arg << '}';
949                         return make_pair(true, count + 16);
950                 }
951                 case Encoding::CJK: {
952                         int count = inputenc_arg.length();
953                         if (oldEnc.package() == Encoding::CJK &&
954                             open_encoding_ == CJK) {
955                                 os << "\\end{CJK}";
956                                 count += 9;
957                         }
958                         if (oldEnc.package() == Encoding::inputenc &&
959                             open_encoding_ == inputenc) {
960                                 os << "\\egroup";
961                                 count += 7;
962                         }
963                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
964                            << from_ascii(bparams.fontsCJK) << "}";
965                         open_encoding_ = CJK;
966                         return make_pair(true, count + 15);
967                 }
968         }
969         // Dead code to avoid a warning:
970         return make_pair(true, 0);
971
972 }
973
974 } // namespace lyx