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