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