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