]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
Kornel's gcc compile fix.
[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 "ParagraphParameters.h"
25 #include "TextClass.h"
26 #include "TexRow.h"
27 #include "VSpace.h"
28
29 #include "insets/InsetBibitem.h"
30 #include "insets/InsetOptArg.h"
31
32 #include "support/lassert.h"
33 #include "support/debug.h"
34 #include "support/lstrings.h"
35
36 #include <boost/next_prior.hpp>
37
38 using namespace std;
39 using namespace lyx::support;
40
41
42 namespace lyx {
43
44 namespace {
45
46 enum OpenEncoding {
47                 none,
48                 inputenc,
49                 CJK
50 };
51
52 static int open_encoding_ = none;
53 static int cjk_inherited_ = 0;
54 Language const * prev_env_language_ = 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         bool const force_plain_layout = text.inset().forcePlainLayout();
78         while (par != paragraphs.end() &&
79                                         par->params().depth() == pit->params().depth()) {
80                 // FIXME This test should not be necessary.
81                 // We should perhaps issue an error if it is.
82                 Layout const & style = force_plain_layout
83                         ? buf.params().documentClass().plainLayout() : par->layout();
84                 if (style.isEnvironment()) {
85                         par = TeXEnvironment(buf, text, par,
86                                              os, texrow, runparams);
87                 } else {
88                         par = TeXOnePar(buf, text, par,
89                                              os, texrow, runparams);
90                 }
91         }
92         LYXERR(Debug::LATEX, "TeXDeeper...done ");
93
94         return par;
95 }
96
97
98 ParagraphList::const_iterator
99 TeXEnvironment(Buffer const & buf,
100                Text const & text,
101                ParagraphList::const_iterator pit,
102                odocstream & os, TexRow & texrow,
103                OutputParams const & runparams)
104 {
105         LYXERR(Debug::LATEX, "TeXEnvironment...     " << &*pit);
106
107         BufferParams const & bparams = buf.params();
108
109         // FIXME This test should not be necessary.
110         // We should perhaps issue an error if it is.
111         Layout const & style = text.inset().forcePlainLayout() ?
112                 bparams.documentClass().plainLayout() : pit->layout();
113
114         ParagraphList const & paragraphs = text.paragraphs();
115         ParagraphList::const_iterator const priorpit =
116                 pit == paragraphs.begin() ? pit : boost::prior(pit);
117
118         bool const use_prev_env_language = prev_env_language_ != 0
119                         && priorpit->layout().isEnvironment()
120                         && (priorpit->getDepth() > pit->getDepth()
121                             || (priorpit->getDepth() == pit->getDepth()
122                                 && priorpit->layout() != pit->layout()));
123
124         Encoding const * const prev_encoding = runparams.encoding;
125         Language const * const par_language = pit->getParLanguage(bparams);
126         Language const * const doc_language = bparams.language;
127         Language const * const prev_par_language =
128                 (pit != paragraphs.begin())
129                 ? (use_prev_env_language ? prev_env_language_
130                                          : priorpit->getParLanguage(bparams))
131                 : doc_language;
132         if (par_language->babel() != prev_par_language->babel()) {
133
134                 if (!lyxrc.language_command_end.empty() &&
135                     prev_par_language->babel() != doc_language->babel() &&
136                     !prev_par_language->babel().empty()) {
137                         os << from_ascii(subst(
138                                 lyxrc.language_command_end,
139                                 "$$lang",
140                                 prev_par_language->babel()))
141                            // the '%' is necessary to prevent unwanted whitespace
142                            << "%\n";
143                         texrow.newline();
144                 }
145
146                 if ((lyxrc.language_command_end.empty() ||
147                      par_language->babel() != doc_language->babel()) &&
148                     !par_language->babel().empty()) {
149                         os << from_ascii(subst(
150                                 lyxrc.language_command_begin,
151                                 "$$lang",
152                                 par_language->babel()))
153                            // the '%' is necessary to prevent unwanted whitespace
154                            << "%\n";
155                         texrow.newline();
156                 }
157         }
158
159         bool leftindent_open = false;
160         if (!pit->params().leftIndent().zero()) {
161                 os << "\\begin{LyXParagraphLeftIndent}{"
162                    << from_ascii(pit->params().leftIndent().asLatexString())
163                    << "}\n";
164                 texrow.newline();
165                 leftindent_open = true;
166         }
167
168         if (style.isEnvironment()) {
169                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
170                 if (style.optionalargs > 0) {
171                         int ret = latexOptArgInsets(*pit, os, runparams,
172                                                     style.optionalargs);
173                         while (ret > 0) {
174                                 texrow.newline();
175                                 --ret;
176                         }
177                 }
178                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
179                         os << '{'
180                            << pit->params().labelWidthString()
181                            << "}\n";
182                 } else if (style.labeltype == LABEL_BIBLIO) {
183                         if (pit->params().labelWidthString().empty())
184                                 os << '{' << bibitemWidest(buf) << "}\n";
185                         else
186                                 os << '{'
187                                   << pit->params().labelWidthString()
188                                   << "}\n";
189                 } else
190                         os << from_ascii(style.latexparam()) << '\n';
191                 texrow.newline();
192         }
193
194         // in multilingual environments, the CJK tags have to be nested properly
195         bool cjk_nested = false;
196         if (par_language->encoding()->package() == Encoding::CJK &&
197             open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
198                 if (prev_par_language->encoding()->package() == Encoding::CJK)
199                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
200                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
201                 open_encoding_ = CJK;
202                 cjk_nested = true;
203                 texrow.newline();
204         }
205
206         ParagraphList::const_iterator par = pit;
207         do {
208                 par = TeXOnePar(buf, text, par, os, texrow, runparams);
209
210                 if (par == paragraphs.end()) {
211                         // Make sure that the last paragraph is
212                         // correctly terminated (because TeXOnePar does
213                         // not add a \n in this case)
214                         os << '\n';
215                         texrow.newline();
216                 } else if (par->params().depth() > pit->params().depth()) {
217                         if (par->layout().isParagraph()) {
218                           // Thinko!
219                           // How to handle this? (Lgb)
220                           //&& !suffixIs(os, "\n\n")
221
222                                 // There should be at least one '\n' already
223                                 // but we need there to be two for Standard
224                                 // paragraphs that are depth-increment'ed to be
225                                 // output correctly.  However, tables can
226                                 // also be paragraphs so don't adjust them.
227                                 // ARRae
228                                 // Thinkee:
229                                 // Will it ever harm to have one '\n' too
230                                 // many? i.e. that we sometimes will have
231                                 // three in a row. (Lgb)
232                                 os << '\n';
233                                 texrow.newline();
234                         }
235                         par = TeXDeeper(buf, text, par, os, texrow,
236                                         runparams);
237                 }
238         } while (par != paragraphs.end()
239                  && par->layout() == pit->layout()
240                  && par->params().depth() == pit->params().depth()
241                  && par->params().leftIndent() == pit->params().leftIndent());
242
243         if (open_encoding_ == CJK && cjk_nested) {
244                 // We need to close the encoding even if it does not change
245                 // to do correct environment nesting
246                 os << "\\end{CJK}\n";
247                 texrow.newline();
248                 open_encoding_ = none;
249         }
250
251         if (style.isEnvironment()) {
252                 os << "\\end{" << from_ascii(style.latexname()) << "}\n";
253                 texrow.newline();
254                 prev_env_language_ = par_language;
255                 if (runparams.encoding != prev_encoding) {
256                         runparams.encoding = prev_encoding;
257                         if (!bparams.useXetex)
258                                 os << setEncoding(prev_encoding->iconvName());
259                 }
260         }
261
262         if (leftindent_open) {
263                 os << "\\end{LyXParagraphLeftIndent}\n";
264                 texrow.newline();
265                 prev_env_language_ = par_language;
266                 if (runparams.encoding != prev_encoding) {
267                         runparams.encoding = prev_encoding;
268                         if (!bparams.useXetex)
269                                 os << setEncoding(prev_encoding->iconvName());
270                 }
271         }
272
273         if (par != paragraphs.end())
274                 LYXERR(Debug::LATEX, "TeXEnvironment...done " << &*par);
275
276         return par;
277 }
278
279 } // namespace anon
280
281
282 int latexOptArgInsets(Paragraph const & par, odocstream & os,
283         OutputParams const & runparams, int number)
284 {
285         int lines = 0;
286
287         InsetList::const_iterator it = par.insetList().begin();
288         InsetList::const_iterator end = par.insetList().end();
289         for (; it != end && number > 0 ; ++it) {
290                 if (it->inset->lyxCode() == OPTARG_CODE) {
291                         InsetOptArg * ins =
292                                 static_cast<InsetOptArg *>(it->inset);
293                         lines += ins->latexOptional(os, runparams);
294                         --number;
295                 }
296         }
297         return lines;
298 }
299
300 // FIXME: this should be anonymous
301 ParagraphList::const_iterator TeXOnePar(Buffer const & buf,
302           Text const & text,
303           ParagraphList::const_iterator const pit,
304           odocstream & os, TexRow & texrow,
305           OutputParams const & runparams_in,
306           string const & everypar,
307           int start_pos, int end_pos)
308 {
309         LYXERR(Debug::LATEX, "TeXOnePar...     " << &*pit << " '"
310                 << everypar << "'");
311         BufferParams const & bparams = buf.params();
312         ParagraphList const & paragraphs = text.paragraphs();
313
314         ParagraphList::const_iterator const priorpit = 
315                 pit == paragraphs.begin() ? pit : boost::prior(pit);
316         ParagraphList::const_iterator const nextpit = 
317                 pit == paragraphs.end() ? pit : boost::next(pit);
318
319         OutputParams runparams = runparams_in;
320         runparams.isLastPar = nextpit == paragraphs.end();
321
322         if (runparams.verbatim) {
323                 int const dist = distance(paragraphs.begin(), pit);
324                 Font const outerfont = text.outerFont(dist);
325
326                 // No newline if only one paragraph in this lyxtext
327                 if (dist > 0) {
328                         os << '\n';
329                         texrow.newline();
330                 }
331
332                 /*bool need_par = */ pit->latex(bparams, outerfont,
333                         os, texrow, runparams, start_pos, end_pos);
334                 return nextpit;
335         }
336
337         // FIXME This check should not really be needed.
338         // Perhaps we should issue an error if it is.
339         Layout const style = text.inset().forcePlainLayout() ?
340                 bparams.documentClass().plainLayout() : pit->layout();
341
342         runparams.moving_arg |= style.needprotect;
343
344         bool const maintext = text.isMainText();
345         // we are at the beginning of an inset and CJK is already open;
346         // we count inheritation levels to get the inset nesting right.
347         if (pit == paragraphs.begin() && !maintext
348             && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
349                 cjk_inherited_ += 1;
350                 open_encoding_ = none;
351         }
352
353         // This paragraph's language
354         Language const * const par_language = pit->getParLanguage(bparams);
355         // The document's language
356         Language const * const doc_language = bparams.language;
357         // The language that was in effect when the environment this paragraph is
358         // inside of was opened
359         Language const * const outer_language =
360                 (runparams.local_font != 0) ?
361                         runparams.local_font->language() : doc_language;
362
363         // The previous language that was in effect is the language of the
364         // previous paragraph, unless the previous paragraph is inside an
365         // environment with nesting depth greater than (or equal to, but with
366         // a different layout) the current one. If there is no previous
367         // paragraph, the previous language is the outer language.
368         bool const use_prev_env_language = prev_env_language_ != 0
369                         && priorpit->layout().isEnvironment()
370                         && (priorpit->getDepth() > pit->getDepth()
371                             || (priorpit->getDepth() == pit->getDepth()
372                                 && priorpit->layout() != pit->layout()));
373         Language const * const prev_language =
374                 (pit != paragraphs.begin())
375                 ? (use_prev_env_language ? prev_env_language_
376                                          : priorpit->getParLanguage(bparams))
377                 : outer_language;
378
379         if (par_language->babel() != prev_language->babel()
380             // check if we already put language command in TeXEnvironment()
381             && !(style.isEnvironment()
382                  && (pit == paragraphs.begin() ||
383                      (priorpit->layout() != pit->layout() &&
384                       priorpit->getDepth() <= pit->getDepth())
385                      || priorpit->getDepth() < pit->getDepth())))
386         {
387                 if (!lyxrc.language_command_end.empty() &&
388                     prev_language->babel() != outer_language->babel() &&
389                     !prev_language->babel().empty())
390                 {
391                         os << from_ascii(subst(lyxrc.language_command_end,
392                                 "$$lang",
393                                 prev_language->babel()))
394                            // the '%' is necessary to prevent unwanted whitespace
395                            << "%\n";
396                         texrow.newline();
397                 }
398
399                 // We need to open a new language if we couldn't close the previous
400                 // one (because there's no language_command_end); and even if we closed
401                 // the previous one, if the current language is different than the
402                 // outer_language (which is currently in effect once the previous one
403                 // is closed).
404                 if ((lyxrc.language_command_end.empty() ||
405                      par_language->babel() != outer_language->babel()) &&
406                     !par_language->babel().empty()) {
407                         // If we're inside an inset, and that inset is within an \L or \R
408                         // (or equivalents), then within the inset, too, any opposite
409                         // language paragraph should appear within an \L or \R (in addition
410                         // to, outside of, the normal language switch commands).
411                         // This behavior is not correct for ArabTeX, though.
412                         if (    // not for ArabTeX
413                                         (par_language->lang() != "arabic_arabtex" &&
414                                          outer_language->lang() != "arabic_arabtex") &&
415                                         // are we in an inset?
416                                         runparams.local_font != 0 &&
417                                         // is the inset within an \L or \R?
418                                         //
419                                         // FIXME: currently, we don't check this; this means that
420                                         // we'll have unnnecessary \L and \R commands, but that
421                                         // doesn't seem to hurt (though latex will complain)
422                                         //
423                                         // is this paragraph in the opposite direction?
424                                         runparams.local_font->isRightToLeft() !=
425                                                 par_language->rightToLeft()
426                                 ) {
427                                 // FIXME: I don't have a working copy of the Arabi package, so
428                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
429                                 // or not...
430                                 if (par_language->lang() == "farsi")
431                                         os << "\\textFR{";
432                                 else if (outer_language->lang() == "farsi")
433                                         os << "\\textLR{";
434                                 else if (par_language->lang() == "arabic_arabi")
435                                         os << "\\textAR{";
436                                 else if (outer_language->lang() == "arabic_arabi")
437                                         os << "\\textLR{";
438                                 // remaining RTL languages currently is hebrew
439                                 else if (par_language->rightToLeft())
440                                         os << "\\R{";
441                                 else
442                                         os << "\\L{";
443                         }
444                         // With CJK, the CJK tag has to be closed first (see below)
445                         if (runparams.encoding->package() != Encoding::CJK) {
446                                 os << from_ascii(subst(
447                                         lyxrc.language_command_begin,
448                                         "$$lang",
449                                         par_language->babel()))
450                                    // the '%' is necessary to prevent unwanted whitespace
451                                    << "%\n";
452                                 texrow.newline();
453                         }
454                 }
455         }
456
457         // Switch file encoding if necessary; no need to do this for "default"
458         // encoding, since this only affects the position of the outputted
459         // \inputencoding command; the encoding switch will occur when necessary
460         if (bparams.inputenc == "auto" &&
461             runparams.encoding->package() != Encoding::none) {
462                 // Look ahead for future encoding changes.
463                 // We try to output them at the beginning of the paragraph,
464                 // since the \inputencoding command is not allowed e.g. in
465                 // sections.
466                 for (pos_type i = 0; i < pit->size(); ++i) {
467                         char_type const c = pit->getChar(i);
468                         Encoding const * const encoding =
469                                 pit->getFontSettings(bparams, i).language()->encoding();
470                         if (encoding->package() != Encoding::CJK &&
471                             runparams.encoding->package() == Encoding::inputenc &&
472                             c < 0x80)
473                                 continue;
474                         if (pit->isInset(i))
475                                 break;
476                         // All characters before c are in the ASCII range, and
477                         // c is non-ASCII (but no inset), so change the
478                         // encoding to that required by the language of c.
479                         // With CJK, only add switch if we have CJK content at the beginning
480                         // of the paragraph
481                         if (encoding->package() != Encoding::CJK || i == 0) {
482                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
483                                         *encoding);
484                                 // the following is necessary after a CJK environment in a multilingual
485                                 // context (nesting issue).
486                                 if (par_language->encoding()->package() == Encoding::CJK &&
487                                     open_encoding_ != CJK && cjk_inherited_ == 0) {
488                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
489                                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
490                                         open_encoding_ = CJK;
491                                         texrow.newline();
492                                 }
493                                 if (encoding->package() != Encoding::none && enc_switch.first) {
494                                         if (enc_switch.second > 0) {
495                                                 // the '%' is necessary to prevent unwanted whitespace
496                                                 os << "%\n";
497                                                 texrow.newline();
498                                         }
499                                         // With CJK, the CJK tag had to be closed first (see above)
500                                         if (runparams.encoding->package() == Encoding::CJK) {
501                                                 os << from_ascii(subst(
502                                                         lyxrc.language_command_begin,
503                                                         "$$lang",
504                                                         par_language->babel()))
505                                                 // the '%' is necessary to prevent unwanted whitespace
506                                                 << "%\n";
507                                                 texrow.newline();
508                                         }
509                                         runparams.encoding = encoding;
510                                 }
511                                 break;
512                         }
513                 }
514         }
515
516         Encoding const * const prev_encoding = runparams.encoding;
517
518         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
519         if (pit->allowParagraphCustomization()) {
520                 if (pit->params().startOfAppendix()) {
521                         os << "\\appendix\n";
522                         texrow.newline();
523                 }
524
525                 if (!pit->params().spacing().isDefault()
526                         && (pit == paragraphs.begin()
527                             || !priorpit->hasSameLayout(*pit)))
528                 {
529                         os << from_ascii(pit->params().spacing().writeEnvirBegin(useSetSpace))
530                             << '\n';
531                         texrow.newline();
532                 }
533
534                 if (style.isCommand()) {
535                         os << '\n';
536                         texrow.newline();
537                 }
538         }
539
540         switch (style.latextype) {
541         case LATEX_COMMAND:
542                 os << '\\' << from_ascii(style.latexname());
543
544                 // Separate handling of optional argument inset.
545                 if (style.optionalargs > 0) {
546                         int ret = latexOptArgInsets(*pit, os, runparams,
547                                                     style.optionalargs);
548                         while (ret > 0) {
549                                 texrow.newline();
550                                 --ret;
551                         }
552                 }
553                 else
554                         os << from_ascii(style.latexparam());
555                 break;
556         case LATEX_ITEM_ENVIRONMENT:
557         case LATEX_LIST_ENVIRONMENT:
558                 os << "\\item ";
559                 break;
560         case LATEX_BIB_ENVIRONMENT:
561                 // ignore this, the inset will write itself
562                 break;
563         default:
564                 break;
565         }
566
567         Font const outerfont = text.outerFont(distance(paragraphs.begin(), pit));
568
569         // FIXME UNICODE
570         os << from_utf8(everypar);
571         bool need_par = pit->latex(bparams, outerfont,
572                                              os, texrow, runparams, start_pos, end_pos);
573
574         // Make sure that \\par is done with the font of the last
575         // character if this has another size as the default.
576         // This is necessary because LaTeX (and LyX on the screen)
577         // calculates the space between the baselines according
578         // to this font. (Matthias)
579         //
580         // Is this really needed ? (Dekel)
581         // We do not need to use to change the font for the last paragraph
582         // or for a command.
583
584         Font const font = pit->empty()
585                  ? pit->getLayoutFont(bparams, outerfont)
586                  : pit->getFont(bparams, pit->size() - 1, outerfont);
587
588         bool const is_command = style.isCommand();
589
590         if (style.resfont.size() != font.fontInfo().size()
591             && nextpit != paragraphs.end()
592             && !is_command) {
593                 if (!need_par)
594                         os << '{';
595                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
596         } else if (need_par) {
597                 os << "\\par}";
598         } else if (is_command) {
599                 os << '}';
600                 if (runparams.encoding != prev_encoding) {
601                         runparams.encoding = prev_encoding;
602                         if (!bparams.useXetex)
603                                 os << setEncoding(prev_encoding->iconvName());
604                 }
605         }
606
607         bool pending_newline = false;
608         switch (style.latextype) {
609         case LATEX_ITEM_ENVIRONMENT:
610         case LATEX_LIST_ENVIRONMENT:
611                 if (nextpit != paragraphs.end()
612                     && (pit->params().depth() < nextpit->params().depth()))
613                         pending_newline = true;
614                 break;
615         case LATEX_ENVIRONMENT: {
616                 // if its the last paragraph of the current environment
617                 // skip it otherwise fall through
618                 if (nextpit != paragraphs.end() && 
619                     (nextpit->layout() != pit->layout()
620                      || nextpit->params().depth() != pit->params().depth()))
621                         break;
622         }
623
624         // fall through possible
625         default:
626                 // we don't need it for the last paragraph!!!
627                 if (nextpit != paragraphs.end())
628                         pending_newline = true;
629         }
630
631         if (pit->allowParagraphCustomization()) {
632                 if (!pit->params().spacing().isDefault()
633                         && (nextpit == paragraphs.end() || !nextpit->hasSameLayout(*pit)))
634                 {
635                         if (pending_newline) {
636                                 os << '\n';
637                                 texrow.newline();
638                         }
639                         os << from_ascii(pit->params().spacing().writeEnvirEnd(useSetSpace));
640                         pending_newline = true;
641                 }
642         }
643
644         // Closing the language is needed for the last paragraph; it is also
645         // needed if we're within an \L or \R that we may have opened above (not
646         // necessarily in this paragraph) and are about to close.
647         bool closing_rtl_ltr_environment =
648                 // not for ArabTeX
649                 (par_language->lang() != "arabic_arabtex" &&
650                  outer_language->lang() != "arabic_arabtex") &&
651                 // have we opened and \L or \R environment?
652                 runparams.local_font != 0 &&
653                 runparams.local_font->isRightToLeft() != par_language->rightToLeft() &&
654                 // are we about to close the language?
655                 ((nextpit != paragraphs.end() &&
656                   par_language->babel() !=
657                     (nextpit->getParLanguage(bparams))->babel()) ||
658                   (nextpit == paragraphs.end() &&
659                     par_language->babel() != outer_language->babel()));
660
661         if (closing_rtl_ltr_environment || (nextpit == paragraphs.end()
662             && par_language->babel() != outer_language->babel())) {
663                 // Since \selectlanguage write the language to the aux file,
664                 // we need to reset the language at the end of footnote or
665                 // float.
666
667                 if (pending_newline) {
668                         os << '\n';
669                         texrow.newline();
670                 }
671                 // when the paragraph uses CJK, the language has to be closed earlier
672                 if (font.language()->encoding()->package() != Encoding::CJK) {
673                         if (lyxrc.language_command_end.empty()) {
674                                 if (!prev_language->babel().empty()) {
675                                         os << from_ascii(subst(
676                                                 lyxrc.language_command_begin,
677                                                 "$$lang",
678                                                 prev_language->babel()));
679                                         pending_newline = true;
680                                 }
681                         } else if (!par_language->babel().empty()) {
682                                 os << from_ascii(subst(
683                                         lyxrc.language_command_end,
684                                         "$$lang",
685                                         par_language->babel()));
686                                 pending_newline = true;
687                         }
688                 }
689         }
690         if (closing_rtl_ltr_environment)
691                 os << "}";
692
693         if (pending_newline) {
694                 os << '\n';
695                 texrow.newline();
696         }
697
698         // if this is a CJK-paragraph and the next isn't, close CJK
699         // also if the next paragraph is a multilingual environment (because of nesting)
700         if (nextpit != paragraphs.end() && open_encoding_ == CJK &&
701             (nextpit->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
702              (nextpit->layout().isEnvironment() && nextpit->isMultiLingual(bparams)))
703              // inbetween environments, CJK has to be closed later (nesting!)
704              && (!style.isEnvironment() || !nextpit->layout().isEnvironment())) {
705                 os << "\\end{CJK}\n";
706                 open_encoding_ = none;
707         }
708
709         // If this is the last paragraph, close the CJK environment
710         // if necessary. If it's an environment, we'll have to \end that first.
711         if (nextpit == paragraphs.end() && !style.isEnvironment()) {
712                 switch (open_encoding_) {
713                         case CJK: {
714                                 // do nothing at the end of child documents
715                                 if (maintext && buf.masterBuffer() != &buf)
716                                         break;
717                                 // end of main text
718                                 if (maintext) {
719                                         os << '\n';
720                                         texrow.newline();
721                                         os << "\\end{CJK}\n";
722                                         texrow.newline();
723                                 // end of an inset
724                                 } else
725                                         os << "\\end{CJK}";
726                                 open_encoding_ = none;
727                                 break;
728                         }
729                         case inputenc: {
730                                 os << "\\egroup";
731                                 open_encoding_ = none;
732                                 break;
733                         }
734                         case none:
735                         default:
736                                 // do nothing
737                                 break;
738                 }
739         }
740
741         // If this is the last paragraph, and a local_font was set upon entering
742         // the inset, and we're using "auto" or "default" encoding, the encoding
743         // should be set back to that local_font's encoding.
744         // However, do not change the encoding when XeTeX is used.
745         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
746             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
747             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
748             && (!bparams.useXetex)) {
749                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
750                 os << setEncoding(runparams_in.encoding->iconvName());
751         }
752         // Otherwise, the current encoding should be set for the next paragraph.
753         else
754                 runparams_in.encoding = runparams.encoding;
755
756
757         // we don't need a newline for the last paragraph!!!
758         // Note from JMarc: we will re-add a \n explicitly in
759         // TeXEnvironment, because it is needed in this case
760         if (nextpit != paragraphs.end()) {
761                 Layout const & next_layout = nextpit->layout();
762                 if (style == next_layout
763                     // no blank lines before environments!
764                     || !next_layout.isEnvironment()
765                     // unless there's a depth change
766                     // FIXME What we really want to do here is put every \begin and \end
767                     // tag on a new line (which was not the case with nested environments).
768                     // But in the present state of play, we don't have access to the
769                     // information whether the current TeX row is empty or not.
770                     // For some ideas about how to fix this, see this thread:
771                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
772                     || nextpit->params().depth() != pit->params().depth()) {
773                         os << '\n';
774                         texrow.newline();
775                 }
776         }
777
778         if (nextpit != paragraphs.end())
779                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
780
781         return nextpit;
782 }
783
784
785 // LaTeX all paragraphs
786 void latexParagraphs(Buffer const & buf,
787                      Text const & text,
788                      odocstream & os,
789                      TexRow & texrow,
790                      OutputParams const & runparams,
791                      string const & everypar)
792 {
793         bool was_title = false;
794         bool already_title = false;
795         BufferParams const & bparams = buf.params();
796         DocumentClass const & tclass = bparams.documentClass();
797         ParagraphList const & paragraphs = text.paragraphs();
798         ParagraphList::const_iterator par = paragraphs.begin();
799         ParagraphList::const_iterator endpar = paragraphs.end();
800
801         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
802         // if only part of the paragraphs will be outputed
803         if (runparams.par_begin !=  runparams.par_end) {
804                 par = boost::next(paragraphs.begin(), runparams.par_begin);
805                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
806                 // runparams will be passed to nested paragraphs, so
807                 // we have to reset the range parameters.
808                 const_cast<OutputParams&>(runparams).par_begin = 0;
809                 const_cast<OutputParams&>(runparams).par_end = 0;
810         }
811
812         bool const maintext = text.isMainText();
813         bool const is_child = buf.masterBuffer() != &buf;
814
815         // Open a CJK environment at the beginning of the main buffer
816         // if the document's language is a CJK language
817         // (but not in child documents)
818         if (maintext && !is_child
819             && bparams.encoding().package() == Encoding::CJK) {
820                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
821                 << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
822                 texrow.newline();
823                 open_encoding_ = CJK;
824         }
825         // if "auto begin" is switched off, explicitely switch the
826         // language on at start
827         if (maintext && !lyxrc.language_auto_begin &&
828             !bparams.language->babel().empty()) {
829                 // FIXME UNICODE
830                 os << from_utf8(subst(lyxrc.language_command_begin,
831                                         "$$lang",
832                                         bparams.language->babel()))
833                         << '\n';
834         texrow.newline();
835         }
836
837         ParagraphList::const_iterator lastpar;
838         // if only_body
839         while (par != endpar) {
840                 lastpar = par;
841                 // FIXME This check should not be needed. We should
842                 // perhaps issue an error if it is.
843                 Layout const & layout = text.inset().forcePlainLayout() ?
844                                 tclass.plainLayout() : par->layout();
845
846                 if (layout.intitle) {
847                         if (already_title) {
848                                 lyxerr << "Error in latexParagraphs: You"
849                                         " should not mix title layouts"
850                                         " with normal ones." << endl;
851                         } else if (!was_title) {
852                                 was_title = true;
853                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
854                                         os << "\\begin{"
855                                                         << from_ascii(tclass.titlename())
856                                                         << "}\n";
857                                         texrow.newline();
858                                 }
859                         }
860                 } else if (was_title && !already_title) {
861                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
862                                 os << "\\end{" << from_ascii(tclass.titlename())
863                                                 << "}\n";
864                         }
865                         else {
866                                 os << "\\" << from_ascii(tclass.titlename())
867                                                 << "\n";
868                         }
869                         texrow.newline();
870                         already_title = true;
871                         was_title = false;
872                 }
873
874                 if (layout.isEnvironment() ||
875                                         !par->params().leftIndent().zero()) {
876                         par = TeXEnvironment(buf, text, par, os,
877                                                                 texrow, runparams);
878                 } else {
879                         par = TeXOnePar(buf, text, par, os, texrow,
880                                         runparams, everypar);
881                 }
882                 if (distance(lastpar, par) >= distance(lastpar, endpar))
883                         break;
884         }
885
886         // It might be that we only have a title in this document
887         if (was_title && !already_title) {
888                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
889                         os << "\\end{" << from_ascii(tclass.titlename())
890                             << "}\n";
891                 }
892                 else {
893                         os << "\\" << from_ascii(tclass.titlename())
894                             << "\n";
895                                 }
896                 texrow.newline();
897         }
898
899         // if "auto end" is switched off, explicitely close the language at the end
900         // but only if the last par is in a babel language
901         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
902                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
903                 os << from_utf8(subst(lyxrc.language_command_end,
904                                         "$$lang",
905                                         bparams.language->babel()))
906                         << '\n';
907                 texrow.newline();
908         }
909
910         // If the last paragraph is an environment, we'll have to close
911         // CJK at the very end to do proper nesting.
912         if (maintext && !is_child && open_encoding_ == CJK) {
913                 os << "\\end{CJK}\n";
914                 texrow.newline();
915                 open_encoding_ = none;
916         }
917
918         // reset inherited encoding
919         if (cjk_inherited_ > 0) {
920                 cjk_inherited_ -= 1;
921                 if (cjk_inherited_ == 0)
922                         open_encoding_ = CJK;
923         }
924 }
925
926
927 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
928                    OutputParams const & runparams, Encoding const & newEnc,
929                    bool force)
930 {
931         Encoding const & oldEnc = *runparams.encoding;
932         bool moving_arg = runparams.moving_arg;
933         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
934                 || moving_arg))
935                 return make_pair(false, 0);
936
937         // Do nothing if the encoding is unchanged.
938         if (oldEnc.name() == newEnc.name())
939                 return make_pair(false, 0);
940
941         // FIXME We ignore encoding switches from/to encodings that do
942         // neither support the inputenc package nor the CJK package here.
943         // This does of course only work in special cases (e.g. switch from
944         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
945         // but it is the best we can do
946         if (oldEnc.package() == Encoding::none
947                 || newEnc.package() == Encoding::none)
948                 return make_pair(false, 0);
949
950         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
951                 << oldEnc.name() << " to " << newEnc.name());
952         os << setEncoding(newEnc.iconvName());
953         if (bparams.inputenc == "default")
954                 return make_pair(true, 0);
955
956         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
957         switch (newEnc.package()) {
958                 case Encoding::none:
959                 case Encoding::japanese:
960                         // shouldn't ever reach here, see above
961                         return make_pair(true, 0);
962                 case Encoding::inputenc: {
963                         int count = inputenc_arg.length();
964                         if (oldEnc.package() == Encoding::CJK &&
965                             open_encoding_ == CJK) {
966                                 os << "\\end{CJK}";
967                                 open_encoding_ = none;
968                                 count += 9;
969                         }
970                         else if (oldEnc.package() == Encoding::inputenc &&
971                                  open_encoding_ == inputenc) {
972                                 os << "\\egroup";
973                                 open_encoding_ = none;
974                                 count += 7;
975                         }
976                         if (runparams.local_font != 0
977                             &&  oldEnc.package() == Encoding::CJK) {
978                                 // within insets, \inputenc switches need
979                                 // to be embraced within \bgroup...\egroup;
980                                 // else CJK fails.
981                                 os << "\\bgroup";
982                                 count += 7;
983                                 open_encoding_ = inputenc;
984                         }
985                         // with the japanese option, inputenc is omitted.
986                         if (runparams.use_japanese)
987                                 return make_pair(true, count);
988                         os << "\\inputencoding{" << inputenc_arg << '}';
989                         return make_pair(true, count + 16);
990                 }
991                 case Encoding::CJK: {
992                         int count = inputenc_arg.length();
993                         if (oldEnc.package() == Encoding::CJK &&
994                             open_encoding_ == CJK) {
995                                 os << "\\end{CJK}";
996                                 count += 9;
997                         }
998                         if (oldEnc.package() == Encoding::inputenc &&
999                             open_encoding_ == inputenc) {
1000                                 os << "\\egroup";
1001                                 count += 7;
1002                         }
1003                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1004                            << from_ascii(bparams.fontsCJK) << "}";
1005                         open_encoding_ = CJK;
1006                         return make_pair(true, count + 15);
1007                 }
1008         }
1009         // Dead code to avoid a warning:
1010         return make_pair(true, 0);
1011
1012 }
1013
1014 } // namespace lyx