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