]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
Smash another case of missing language switch and also avoid redundant switches.
[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 * prev_language =
343                 (pit != paragraphs.begin()) ?
344                         priorpit->getParLanguage(bparams) : outer_language;
345
346         // When the language is changed at the very start of a LyX environment,
347         // the language switch in the LaTeX code occurs just before switching to
348         // the corresponding LaTeX environment. So, when the environment ends,
349         // we have to properly restore the language that was in effect.
350         bool env_lang_switch = false;
351         if (!priorpit->hasSameLayout(*pit)) {
352                 ParagraphList::const_iterator outpit = priorpit;
353                 while (outpit != paragraphs.begin()
354                        && (outpit->hasSameLayout(*priorpit)
355                            || outpit->getDepth() > pit->getDepth())
356                            || outpit->getAlign() != outpit->layout().align)
357                         outpit = boost::prior(outpit);
358                 ParagraphList::const_iterator inpit = boost::next(outpit);
359                 bool topped = outpit == paragraphs.begin()
360                               && (outpit->hasSameLayout(*priorpit)
361                                   || outpit->getDepth() > pit->getDepth()
362                                   || outpit->getAlign() != outpit->layout().align);
363                 Language const * const outenv_language = topped ?
364                                         outer_language
365                                         : outpit->getParLanguage(bparams);
366                 Language const * const inenv_language = topped ?
367                                         outpit->getParLanguage(bparams)
368                                         : inpit->getParLanguage(bparams);
369                 if (outenv_language->babel() != inenv_language->babel()) {
370                         if (inenv_language->babel() != par_language->babel())
371                                 env_lang_switch = true;
372                         prev_language = inenv_language;
373                 } else
374                         prev_language = outenv_language;
375         }
376
377         if ((par_language->babel() != prev_language->babel() || env_lang_switch)
378             // check if we already put language command in TeXEnvironment()
379             && !(style.isEnvironment()
380                  && (pit == paragraphs.begin() ||
381                      (priorpit->layout() != pit->layout() &&
382                       priorpit->getDepth() <= pit->getDepth())
383                      || priorpit->getDepth() < pit->getDepth())))
384         {
385                 if (!lyxrc.language_command_end.empty() &&
386                     prev_language->babel() != outer_language->babel() &&
387                     !prev_language->babel().empty())
388                 {
389                         os << from_ascii(subst(lyxrc.language_command_end,
390                                 "$$lang",
391                                 prev_language->babel()))
392                            // the '%' is necessary to prevent unwanted whitespace
393                            << "%\n";
394                         texrow.newline();
395                 }
396
397                 // We need to open a new language if we couldn't close the previous
398                 // one (because there's no language_command_end); and even if we closed
399                 // the previous one, if the current language is different than the
400                 // outer_language (which is currently in effect once the previous one
401                 // is closed).
402                 if ((lyxrc.language_command_end.empty() ||
403                      par_language->babel() != outer_language->babel()) &&
404                     !par_language->babel().empty()) {
405                         // If we're inside an inset, and that inset is within an \L or \R
406                         // (or equivalents), then within the inset, too, any opposite
407                         // language paragraph should appear within an \L or \R (in addition
408                         // to, outside of, the normal language switch commands).
409                         // This behavior is not correct for ArabTeX, though.
410                         if (    // not for ArabTeX
411                                         (par_language->lang() != "arabic_arabtex" &&
412                                          outer_language->lang() != "arabic_arabtex") &&
413                                         // are we in an inset?
414                                         runparams.local_font != 0 &&
415                                         // is the inset within an \L or \R?
416                                         //
417                                         // FIXME: currently, we don't check this; this means that
418                                         // we'll have unnnecessary \L and \R commands, but that
419                                         // doesn't seem to hurt (though latex will complain)
420                                         //
421                                         // is this paragraph in the opposite direction?
422                                         runparams.local_font->isRightToLeft() !=
423                                                 par_language->rightToLeft()
424                                 ) {
425                                 // FIXME: I don't have a working copy of the Arabi package, so
426                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
427                                 // or not...
428                                 if (par_language->lang() == "farsi")
429                                         os << "\\textFR{";
430                                 else if (outer_language->lang() == "farsi")
431                                         os << "\\textLR{";
432                                 else if (par_language->lang() == "arabic_arabi")
433                                         os << "\\textAR{";
434                                 else if (outer_language->lang() == "arabic_arabi")
435                                         os << "\\textLR{";
436                                 // remaining RTL languages currently is hebrew
437                                 else if (par_language->rightToLeft())
438                                         os << "\\R{";
439                                 else
440                                         os << "\\L{";
441                         }
442                         // With CJK, the CJK tag has to be closed first (see below)
443                         if (runparams.encoding->package() != Encoding::CJK) {
444                                 os << from_ascii(subst(
445                                         lyxrc.language_command_begin,
446                                         "$$lang",
447                                         par_language->babel()))
448                                    // the '%' is necessary to prevent unwanted whitespace
449                                    << "%\n";
450                                 texrow.newline();
451                         }
452                 }
453         }
454
455         // Switch file encoding if necessary; no need to do this for "default"
456         // encoding, since this only affects the position of the outputted
457         // \inputencoding command; the encoding switch will occur when necessary
458         if (bparams.inputenc == "auto" &&
459             runparams.encoding->package() != Encoding::none) {
460                 // Look ahead for future encoding changes.
461                 // We try to output them at the beginning of the paragraph,
462                 // since the \inputencoding command is not allowed e.g. in
463                 // sections.
464                 for (pos_type i = 0; i < pit->size(); ++i) {
465                         char_type const c = pit->getChar(i);
466                         Encoding const * const encoding =
467                                 pit->getFontSettings(bparams, i).language()->encoding();
468                         if (encoding->package() != Encoding::CJK &&
469                             runparams.encoding->package() == Encoding::inputenc &&
470                             c < 0x80)
471                                 continue;
472                         if (pit->isInset(i))
473                                 break;
474                         // All characters before c are in the ASCII range, and
475                         // c is non-ASCII (but no inset), so change the
476                         // encoding to that required by the language of c.
477                         // With CJK, only add switch if we have CJK content at the beginning
478                         // of the paragraph
479                         if (encoding->package() != Encoding::CJK || i == 0) {
480                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
481                                         *encoding);
482                                 // the following is necessary after a CJK environment in a multilingual
483                                 // context (nesting issue).
484                                 if (par_language->encoding()->package() == Encoding::CJK &&
485                                     open_encoding_ != CJK && cjk_inherited_ == 0) {
486                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
487                                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
488                                         open_encoding_ = CJK;
489                                         texrow.newline();
490                                 }
491                                 if (encoding->package() != Encoding::none && enc_switch.first) {
492                                         if (enc_switch.second > 0) {
493                                                 // the '%' is necessary to prevent unwanted whitespace
494                                                 os << "%\n";
495                                                 texrow.newline();
496                                         }
497                                         // With CJK, the CJK tag had to be closed first (see above)
498                                         if (runparams.encoding->package() == Encoding::CJK) {
499                                                 os << from_ascii(subst(
500                                                         lyxrc.language_command_begin,
501                                                         "$$lang",
502                                                         par_language->babel()))
503                                                 // the '%' is necessary to prevent unwanted whitespace
504                                                 << "%\n";
505                                                 texrow.newline();
506                                         }
507                                         runparams.encoding = encoding;
508                                 }
509                                 break;
510                         }
511                 }
512         }
513
514         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
515         if (pit->allowParagraphCustomization()) {
516                 if (pit->params().startOfAppendix()) {
517                         os << "\\appendix\n";
518                         texrow.newline();
519                 }
520
521                 if (!pit->params().spacing().isDefault()
522                         && (pit == paragraphs.begin()
523                             || !priorpit->hasSameLayout(*pit)))
524                 {
525                         os << from_ascii(pit->params().spacing().writeEnvirBegin(useSetSpace))
526                             << '\n';
527                         texrow.newline();
528                 }
529
530                 if (style.isCommand()) {
531                         os << '\n';
532                         texrow.newline();
533                 }
534         }
535
536         switch (style.latextype) {
537         case LATEX_COMMAND:
538                 os << '\\' << from_ascii(style.latexname());
539
540                 // Separate handling of optional argument inset.
541                 if (style.optionalargs > 0) {
542                         int ret = latexOptArgInsets(*pit, os, runparams,
543                                                     style.optionalargs);
544                         while (ret > 0) {
545                                 texrow.newline();
546                                 --ret;
547                         }
548                 }
549                 else
550                         os << from_ascii(style.latexparam());
551                 break;
552         case LATEX_ITEM_ENVIRONMENT:
553         case LATEX_LIST_ENVIRONMENT:
554                 os << "\\item ";
555                 break;
556         case LATEX_BIB_ENVIRONMENT:
557                 // ignore this, the inset will write itself
558                 break;
559         default:
560                 break;
561         }
562
563         Font const outerfont = outerFont(distance(paragraphs.begin(), pit),
564                           paragraphs);
565
566         // FIXME UNICODE
567         os << from_utf8(everypar);
568         bool need_par = pit->latex(bparams, outerfont,
569                                              os, texrow, runparams, start_pos, end_pos);
570
571         // Make sure that \\par is done with the font of the last
572         // character if this has another size as the default.
573         // This is necessary because LaTeX (and LyX on the screen)
574         // calculates the space between the baselines according
575         // to this font. (Matthias)
576         //
577         // Is this really needed ? (Dekel)
578         // We do not need to use to change the font for the last paragraph
579         // or for a command.
580
581         Font const font = pit->empty()
582                  ? pit->getLayoutFont(bparams, outerfont)
583                  : pit->getFont(bparams, pit->size() - 1, outerfont);
584
585         bool const is_command = style.isCommand();
586
587         if (style.resfont.size() != font.fontInfo().size()
588             && nextpit != paragraphs.end()
589             && !is_command) {
590                 if (!need_par)
591                         os << '{';
592                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
593         } else if (need_par) {
594                 os << "\\par}";
595         } else if (is_command)
596                 os << '}';
597
598         bool pending_newline = false;
599         switch (style.latextype) {
600         case LATEX_ITEM_ENVIRONMENT:
601         case LATEX_LIST_ENVIRONMENT:
602                 if (nextpit != paragraphs.end()
603                     && (pit->params().depth() < nextpit->params().depth()))
604                         pending_newline = true;
605                 break;
606         case LATEX_ENVIRONMENT: {
607                 // if its the last paragraph of the current environment
608                 // skip it otherwise fall through
609                 if (nextpit != paragraphs.end() && 
610                     (nextpit->layout() != pit->layout()
611                      || nextpit->params().depth() != pit->params().depth()))
612                         break;
613         }
614
615         // fall through possible
616         default:
617                 // we don't need it for the last paragraph!!!
618                 if (nextpit != paragraphs.end())
619                         pending_newline = true;
620         }
621
622         if (pit->allowParagraphCustomization()) {
623                 if (!pit->params().spacing().isDefault()
624                         && (nextpit == paragraphs.end() || !nextpit->hasSameLayout(*pit)))
625                 {
626                         if (pending_newline) {
627                                 os << '\n';
628                                 texrow.newline();
629                         }
630                         os << from_ascii(pit->params().spacing().writeEnvirEnd(useSetSpace));
631                         pending_newline = true;
632                 }
633         }
634
635         // Closing the language is needed for the last paragraph; it is also
636         // needed if we're within an \L or \R that we may have opened above (not
637         // necessarily in this paragraph) and are about to close.
638         bool closing_rtl_ltr_environment =
639                 // not for ArabTeX
640                 (par_language->lang() != "arabic_arabtex" &&
641                  outer_language->lang() != "arabic_arabtex") &&
642                 // have we opened and \L or \R environment?
643                 runparams.local_font != 0 &&
644                 runparams.local_font->isRightToLeft() != par_language->rightToLeft() &&
645                 // are we about to close the language?
646                 ((nextpit != paragraphs.end() &&
647                   par_language->babel() !=
648                     (nextpit->getParLanguage(bparams))->babel()) ||
649                   (nextpit == paragraphs.end() &&
650                     par_language->babel() != outer_language->babel()));
651
652         if (closing_rtl_ltr_environment || (nextpit == paragraphs.end()
653             && par_language->babel() != outer_language->babel())) {
654                 // Since \selectlanguage write the language to the aux file,
655                 // we need to reset the language at the end of footnote or
656                 // float.
657
658                 if (pending_newline) {
659                         os << '\n';
660                         texrow.newline();
661                 }
662                 // when the paragraph uses CJK, the language has to be closed earlier
663                 if (font.language()->encoding()->package() != Encoding::CJK) {
664                         if (lyxrc.language_command_end.empty()) {
665                                 if (!prev_language->babel().empty()) {
666                                         os << from_ascii(subst(
667                                                 lyxrc.language_command_begin,
668                                                 "$$lang",
669                                                 prev_language->babel()));
670                                         pending_newline = true;
671                                 }
672                         } else if (!par_language->babel().empty()) {
673                                 os << from_ascii(subst(
674                                         lyxrc.language_command_end,
675                                         "$$lang",
676                                         par_language->babel()));
677                                 pending_newline = true;
678                         }
679                 }
680         }
681         if (closing_rtl_ltr_environment)
682                 os << "}";
683
684         if (pending_newline) {
685                 os << '\n';
686                 texrow.newline();
687         }
688
689         // if this is a CJK-paragraph and the next isn't, close CJK
690         // also if the next paragraph is a multilingual environment (because of nesting)
691         if (nextpit != paragraphs.end() && open_encoding_ == CJK &&
692             (nextpit->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
693              (nextpit->layout().isEnvironment() && nextpit->isMultiLingual(bparams)))
694              // inbetween environments, CJK has to be closed later (nesting!)
695              && (!style.isEnvironment() || !nextpit->layout().isEnvironment())) {
696                 os << "\\end{CJK}\n";
697                 open_encoding_ = none;
698         }
699
700         // If this is the last paragraph, close the CJK environment
701         // if necessary. If it's an environment, we'll have to \end that first.
702         if (nextpit == paragraphs.end() && !style.isEnvironment()) {
703                 switch (open_encoding_) {
704                         case CJK: {
705                                 // do nothing at the end of child documents
706                                 if (maintext && buf.masterBuffer() != &buf)
707                                         break;
708                                 // end of main text
709                                 if (maintext) {
710                                         os << '\n';
711                                         texrow.newline();
712                                         os << "\\end{CJK}\n";
713                                         texrow.newline();
714                                 // end of an inset
715                                 } else
716                                         os << "\\end{CJK}";
717                                 open_encoding_ = none;
718                                 break;
719                         }
720                         case inputenc: {
721                                 os << "\\egroup";
722                                 open_encoding_ = none;
723                                 break;
724                         }
725                         case none:
726                         default:
727                                 // do nothing
728                                 break;
729                 }
730         }
731
732         // If this is the last paragraph, and a local_font was set upon entering
733         // the inset, and we're using "auto" or "default" encoding, the encoding
734         // should be set back to that local_font's encoding.
735         // However, do not change the encoding when XeTeX is used.
736         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
737             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
738             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
739             && (!bparams.useXetex)) {
740                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
741                 os << setEncoding(runparams_in.encoding->iconvName());
742         }
743         // Otherwise, the current encoding should be set for the next paragraph.
744         else
745                 runparams_in.encoding = runparams.encoding;
746
747
748         // we don't need a newline for the last paragraph!!!
749         // Note from JMarc: we will re-add a \n explicitly in
750         // TeXEnvironment, because it is needed in this case
751         if (nextpit != paragraphs.end()) {
752                 Layout const & next_layout = nextpit->layout();
753                 if (style == next_layout
754                     // no blank lines before environments!
755                     || !next_layout.isEnvironment()
756                     // unless there's a depth change
757                     // FIXME What we really want to do here is put every \begin and \end
758                     // tag on a new line (which was not the case with nested environments).
759                     // But in the present state of play, we don't have access to the
760                     // information whether the current TeX row is empty or not.
761                     // For some ideas about how to fix this, see this thread:
762                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
763                     || nextpit->params().depth() != pit->params().depth()) {
764                         os << '\n';
765                         texrow.newline();
766                 }
767         }
768
769         if (nextpit != paragraphs.end())
770                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
771
772         return nextpit;
773 }
774
775
776 // LaTeX all paragraphs
777 void latexParagraphs(Buffer const & buf,
778                      Text const & text,
779                      odocstream & os,
780                      TexRow & texrow,
781                      OutputParams const & runparams,
782                      string const & everypar)
783 {
784         bool was_title = false;
785         bool already_title = false;
786         BufferParams const & bparams = buf.params();
787         DocumentClass const & tclass = bparams.documentClass();
788         ParagraphList const & paragraphs = text.paragraphs();
789         ParagraphList::const_iterator par = paragraphs.begin();
790         ParagraphList::const_iterator endpar = paragraphs.end();
791
792         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
793         // if only part of the paragraphs will be outputed
794         if (runparams.par_begin !=  runparams.par_end) {
795                 par = boost::next(paragraphs.begin(), runparams.par_begin);
796                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
797                 // runparams will be passed to nested paragraphs, so
798                 // we have to reset the range parameters.
799                 const_cast<OutputParams&>(runparams).par_begin = 0;
800                 const_cast<OutputParams&>(runparams).par_end = 0;
801         }
802
803         bool const maintext = text.isMainText(buf);
804         bool const is_child = buf.masterBuffer() != &buf;
805
806         // Open a CJK environment at the beginning of the main buffer
807         // if the document's language is a CJK language
808         // (but not in child documents)
809         if (maintext && !is_child
810             && bparams.encoding().package() == Encoding::CJK) {
811                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
812                 << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
813                 texrow.newline();
814                 open_encoding_ = CJK;
815         }
816         // if "auto begin" is switched off, explicitely switch the
817         // language on at start
818         if (maintext && !lyxrc.language_auto_begin &&
819             !bparams.language->babel().empty()) {
820                 // FIXME UNICODE
821                 os << from_utf8(subst(lyxrc.language_command_begin,
822                                         "$$lang",
823                                         bparams.language->babel()))
824                         << '\n';
825         texrow.newline();
826         }
827
828         ParagraphList::const_iterator lastpar;
829         // if only_body
830         while (par != endpar) {
831                 lastpar = par;
832                 // FIXME This check should not be needed. We should
833                 // perhaps issue an error if it is.
834                 Layout const & layout = par->forcePlainLayout() ?
835                                 tclass.plainLayout() : par->layout();
836
837                 if (layout.intitle) {
838                         if (already_title) {
839                                 lyxerr << "Error in latexParagraphs: You"
840                                         " should not mix title layouts"
841                                         " with normal ones." << endl;
842                         } else if (!was_title) {
843                                 was_title = true;
844                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
845                                         os << "\\begin{"
846                                                         << from_ascii(tclass.titlename())
847                                                         << "}\n";
848                                         texrow.newline();
849                                 }
850                         }
851                 } else if (was_title && !already_title) {
852                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
853                                 os << "\\end{" << from_ascii(tclass.titlename())
854                                                 << "}\n";
855                         }
856                         else {
857                                 os << "\\" << from_ascii(tclass.titlename())
858                                                 << "\n";
859                         }
860                         texrow.newline();
861                         already_title = true;
862                         was_title = false;
863                 }
864
865                 if (layout.isEnvironment() ||
866                                         !par->params().leftIndent().zero()) {
867                         par = TeXEnvironment(buf, text, par, os,
868                                                                 texrow, runparams);
869                 } else {
870                         par = TeXOnePar(buf, text, par, os, texrow,
871                                         runparams, everypar);
872                 }
873                 if (distance(lastpar, par) >= distance(lastpar, endpar))
874                         break;
875         }
876
877         // It might be that we only have a title in this document
878         if (was_title && !already_title) {
879                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
880                         os << "\\end{" << from_ascii(tclass.titlename())
881                             << "}\n";
882                 }
883                 else {
884                         os << "\\" << from_ascii(tclass.titlename())
885                             << "\n";
886                                 }
887                 texrow.newline();
888         }
889
890         // if "auto end" is switched off, explicitely close the language at the end
891         // but only if the last par is in a babel language
892         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
893                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
894                 os << from_utf8(subst(lyxrc.language_command_end,
895                                         "$$lang",
896                                         bparams.language->babel()))
897                         << '\n';
898                 texrow.newline();
899         }
900
901         // If the last paragraph is an environment, we'll have to close
902         // CJK at the very end to do proper nesting.
903         if (maintext && !is_child && open_encoding_ == CJK) {
904                 os << "\\end{CJK}\n";
905                 texrow.newline();
906                 open_encoding_ = none;
907         }
908
909         // reset inherited encoding
910         if (cjk_inherited_ > 0) {
911                 cjk_inherited_ -= 1;
912                 if (cjk_inherited_ == 0)
913                         open_encoding_ = CJK;
914         }
915 }
916
917
918 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
919                    OutputParams const & runparams, Encoding const & newEnc,
920                    bool force)
921 {
922         Encoding const & oldEnc = *runparams.encoding;
923         bool moving_arg = runparams.moving_arg;
924         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
925                 || moving_arg))
926                 return make_pair(false, 0);
927
928         // Do nothing if the encoding is unchanged.
929         if (oldEnc.name() == newEnc.name())
930                 return make_pair(false, 0);
931
932         // FIXME We ignore encoding switches from/to encodings that do
933         // neither support the inputenc package nor the CJK package here.
934         // This does of course only work in special cases (e.g. switch from
935         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
936         // but it is the best we can do
937         if (oldEnc.package() == Encoding::none
938                 || newEnc.package() == Encoding::none)
939                 return make_pair(false, 0);
940
941         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
942                 << oldEnc.name() << " to " << newEnc.name());
943         os << setEncoding(newEnc.iconvName());
944         if (bparams.inputenc == "default")
945                 return make_pair(true, 0);
946
947         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
948         switch (newEnc.package()) {
949                 case Encoding::none:
950                 case Encoding::japanese:
951                         // shouldn't ever reach here, see above
952                         return make_pair(true, 0);
953                 case Encoding::inputenc: {
954                         int count = inputenc_arg.length();
955                         if (oldEnc.package() == Encoding::CJK &&
956                             open_encoding_ == CJK) {
957                                 os << "\\end{CJK}";
958                                 open_encoding_ = none;
959                                 count += 9;
960                         }
961                         else if (oldEnc.package() == Encoding::inputenc &&
962                                  open_encoding_ == inputenc) {
963                                 os << "\\egroup";
964                                 open_encoding_ = none;
965                                 count += 7;
966                         }
967                         if (runparams.local_font != 0
968                             &&  oldEnc.package() == Encoding::CJK) {
969                                 // within insets, \inputenc switches need
970                                 // to be embraced within \bgroup...\egroup;
971                                 // else CJK fails.
972                                 os << "\\bgroup";
973                                 count += 7;
974                                 open_encoding_ = inputenc;
975                         }
976                         // with the japanese option, inputenc is omitted.
977                         if (runparams.use_japanese)
978                                 return make_pair(true, count);
979                         os << "\\inputencoding{" << inputenc_arg << '}';
980                         return make_pair(true, count + 16);
981                 }
982                 case Encoding::CJK: {
983                         int count = inputenc_arg.length();
984                         if (oldEnc.package() == Encoding::CJK &&
985                             open_encoding_ == CJK) {
986                                 os << "\\end{CJK}";
987                                 count += 9;
988                         }
989                         if (oldEnc.package() == Encoding::inputenc &&
990                             open_encoding_ == inputenc) {
991                                 os << "\\egroup";
992                                 count += 7;
993                         }
994                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
995                            << from_ascii(bparams.fontsCJK) << "}";
996                         open_encoding_ = CJK;
997                         return make_pair(true, count + 15);
998                 }
999         }
1000         // Dead code to avoid a warning:
1001         return make_pair(true, 0);
1002
1003 }
1004
1005 } // namespace lyx