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