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