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