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