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