]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
#7209 avoid a crash in inMacroMode(): one cannot get the previous atom of an empty...
[lyx.git] / src / output_latex.cpp
1 /**
2  * \file output_latex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "Encoding.h"
18 #include "Font.h"
19 #include "InsetList.h"
20 #include "Language.h"
21 #include "Layout.h"
22 #include "LyXRC.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphParameters.h"
26 #include "TextClass.h"
27 #include "TexRow.h"
28 #include "VSpace.h"
29
30 #include "insets/InsetBibitem.h"
31 #include "insets/InsetArgument.h"
32
33 #include "support/lassert.h"
34 #include "support/debug.h"
35 #include "support/lstrings.h"
36
37 #include <boost/next_prior.hpp>
38 #include <list>
39
40 using namespace std;
41 using namespace lyx::support;
42
43
44 namespace lyx {
45
46 namespace {
47
48 enum OpenEncoding {
49                 none,
50                 inputenc,
51                 CJK
52 };
53
54 static int open_encoding_ = none;
55 static int cjk_inherited_ = 0;
56 Language const * prev_env_language_ = 0;
57
58
59 string const getPolyglossiaEnvName(Language const * lang)
60 {
61         string result = lang->polyglossia();
62         if (result == "arabic")
63                 // exceptional spelling; see polyglossia docs.
64                 result = "Arabic";
65         return result;
66 }
67
68
69 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, pit, 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, pit, 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           pit_type pit,
388           odocstream & os, TexRow & texrow,
389           OutputParams const & runparams_in,
390           string const & everypar,
391           int start_pos, int end_pos)
392 {
393         BufferParams const & bparams = buf.params();
394         ParagraphList const & paragraphs = text.paragraphs();
395         Paragraph const & par = paragraphs.at(pit);
396         // FIXME This check should not really be needed.
397         // Perhaps we should issue an error if it is.
398         Layout const style = text.inset().forcePlainLayout() ?
399                 bparams.documentClass().plainLayout() : par.layout();
400
401         if (style.inpreamble)
402                 return;
403
404         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
405                 << everypar << "'");
406
407         OutputParams runparams = runparams_in;
408         runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
409         // We reinitialze par begin and end to be on the safe side
410         // with embedded inset as we don't know if they set those
411         // value correctly.
412         runparams.par_begin = 0;
413         runparams.par_end = 0;
414
415         bool const maintext = text.isMainText();
416         // we are at the beginning of an inset and CJK is already open;
417         // we count inheritation levels to get the inset nesting right.
418         if (pit == 0 && !maintext
419             && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
420                 cjk_inherited_ += 1;
421                 open_encoding_ = none;
422         }
423
424         if (text.inset().getLayout().isPassThru()) {
425                 Font const outerfont = text.outerFont(pit);
426
427                 // No newline before first paragraph in this lyxtext
428                 if (pit > 0) {
429                         os << '\n';
430                         texrow.newline();
431                         if (!text.inset().getLayout().parbreakIsNewline()) {
432                                 os << '\n';
433                                 texrow.newline();
434                         }
435                 }
436
437                 par.latex(bparams, outerfont, os, texrow, runparams, start_pos,
438                         end_pos);
439                 return;
440         }
441
442         Paragraph const * nextpar = runparams.isLastPar
443                 ? 0 : &paragraphs.at(pit + 1);
444
445         if (style.pass_thru) {
446                 Font const outerfont = text.outerFont(pit);
447                 par.latex(bparams, outerfont, os, texrow, runparams, start_pos,
448                         end_pos);
449                 os << '\n';
450                 texrow.newline();
451                 if (!style.parbreak_is_newline) {
452                         os << '\n';
453                         texrow.newline();
454                 } else if (nextpar) {
455                         Layout const nextstyle = text.inset().forcePlainLayout() ?
456                                 bparams.documentClass().plainLayout() : nextpar->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 = par.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         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
477
478         // The previous language that was in effect is the language of the
479         // previous paragraph, unless the previous paragraph is inside an
480         // environment with nesting depth greater than (or equal to, but with
481         // a different layout) the current one. If there is no previous
482         // paragraph, the previous language is the outer language.
483         bool const use_prev_env_language = prev_env_language_ != 0
484                         && priorpar
485                         && priorpar->layout().isEnvironment()
486                         && (priorpar->getDepth() > par.getDepth()
487                             || (priorpar->getDepth() == par.getDepth()
488                                     && priorpar->layout() != par.layout()));
489         Language const * const prev_language =
490                 (pit != 0)
491                 ? (use_prev_env_language ? prev_env_language_
492                                          : priorpar->getParLanguage(bparams))
493                 : outer_language;
494
495         string par_lang = par_language->babel();
496         string prev_lang = prev_language->babel();
497         string doc_lang = doc_language->babel();
498         string outer_lang = outer_language->babel();
499         string lang_begin_command = lyxrc.language_command_begin;
500         string lang_end_command = lyxrc.language_command_end;
501
502         if (runparams.use_polyglossia) {
503                 par_lang = getPolyglossiaEnvName(par_language);
504                 prev_lang = getPolyglossiaEnvName(prev_language);
505                 doc_lang = getPolyglossiaEnvName(doc_language);
506                 outer_lang = getPolyglossiaEnvName(outer_language);
507                 lang_begin_command = "\\begin{$$lang}";
508                 lang_end_command = "\\end{$$lang}";
509         }
510         if (par_lang != prev_lang
511                 // check if we already put language command in TeXEnvironment()
512                 && !(style.isEnvironment()
513                      && (pit == 0 || (priorpar->layout() != par.layout()
514                                           && priorpar->getDepth() <= par.getDepth())
515                                   || priorpar->getDepth() < par.getDepth())))
516         {
517                 if (!lang_end_command.empty() &&
518                     prev_lang != outer_lang &&
519                     !prev_lang.empty())
520                 {
521                         os << from_ascii(subst(lang_end_command,
522                                 "$$lang",
523                                 prev_lang))
524                            // the '%' is necessary to prevent unwanted whitespace
525                            << "%\n";
526                         texrow.newline();
527                 }
528
529                 // We need to open a new language if we couldn't close the previous
530                 // one (because there's no language_command_end); and even if we closed
531                 // the previous one, if the current language is different than the
532                 // outer_language (which is currently in effect once the previous one
533                 // is closed).
534                 if ((lang_end_command.empty() || par_lang != outer_lang)
535                         && !par_lang.empty()) {
536                         // If we're inside an inset, and that inset is within an \L or \R
537                         // (or equivalents), then within the inset, too, any opposite
538                         // language paragraph should appear within an \L or \R (in addition
539                         // to, outside of, the normal language switch commands).
540                         // This behavior is not correct for ArabTeX, though.
541                         if (!runparams.use_polyglossia
542                             // not for ArabTeX
543                                 && par_language->lang() != "arabic_arabtex"
544                                 && outer_language->lang() != "arabic_arabtex"
545                             // are we in an inset?
546                             && runparams.local_font != 0
547                             // is the inset within an \L or \R?
548                             //
549                             // FIXME: currently, we don't check this; this means that
550                             // we'll have unnnecessary \L and \R commands, but that
551                             // doesn't seem to hurt (though latex will complain)
552                             //
553                             // is this paragraph in the opposite direction?
554                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
555                                 // FIXME: I don't have a working copy of the Arabi package, so
556                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
557                                 // or not...
558                                 if (par_language->lang() == "farsi")
559                                         os << "\\textFR{";
560                                 else if (outer_language->lang() == "farsi")
561                                         os << "\\textLR{";
562                                 else if (par_language->lang() == "arabic_arabi")
563                                         os << "\\textAR{";
564                                 else if (outer_language->lang() == "arabic_arabi")
565                                         os << "\\textLR{";
566                                 // remaining RTL languages currently is hebrew
567                                 else if (par_language->rightToLeft())
568                                         os << "\\R{";
569                                 else
570                                         os << "\\L{";
571                         }
572                         // With CJK, the CJK tag has to be closed first (see below)
573                         if (runparams.encoding->package() != Encoding::CJK) {
574                                 os << from_ascii(subst(
575                                         lang_begin_command,
576                                         "$$lang",
577                                         par_lang));
578                                 if (runparams.use_polyglossia
579                                     && !par_language->polyglossiaOpts().empty())
580                                                 os << "["
581                                                   << from_ascii(par_language->polyglossiaOpts())
582                                                   << "]";
583                                    // the '%' is necessary to prevent unwanted whitespace
584                                 os << "%\n";
585                                 texrow.newline();
586                         }
587                 }
588         }
589
590         // Switch file encoding if necessary; no need to do this for "default"
591         // encoding, since this only affects the position of the outputted
592         // \inputencoding command; the encoding switch will occur when necessary
593         if (bparams.inputenc == "auto"
594                 && runparams.encoding->package() != Encoding::none) {
595                 // Look ahead for future encoding changes.
596                 // We try to output them at the beginning of the paragraph,
597                 // since the \inputencoding command is not allowed e.g. in
598                 // sections. For this reason we only set runparams.moving_arg
599                 // after checking for the encoding change, otherwise the
600                 // change would be always avoided by switchEncoding().
601                 for (pos_type i = 0; i < par.size(); ++i) {
602                         char_type const c = par.getChar(i);
603                         Encoding const * const encoding =
604                                 par.getFontSettings(bparams, i).language()->encoding();
605                         if (encoding->package() != Encoding::CJK
606                                 && runparams.encoding->package() == Encoding::inputenc
607                                 && c < 0x80)
608                                 continue;
609                         if (par.isInset(i))
610                                 break;
611                         // All characters before c are in the ASCII range, and
612                         // c is non-ASCII (but no inset), so change the
613                         // encoding to that required by the language of c.
614                         // With CJK, only add switch if we have CJK content at the beginning
615                         // of the paragraph
616                         if (i != 0 && encoding->package() == Encoding::CJK)
617                                 continue;
618
619                         pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
620                                 *encoding);
621                         // the following is necessary after a CJK environment in a multilingual
622                         // context (nesting issue).
623                         if (par_language->encoding()->package() == Encoding::CJK
624                                 && open_encoding_ != CJK && cjk_inherited_ == 0) {
625                                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
626                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
627                                 open_encoding_ = CJK;
628                                 texrow.newline();
629                         }
630                         if (encoding->package() != Encoding::none && enc_switch.first) {
631                                 if (enc_switch.second > 0) {
632                                         // the '%' is necessary to prevent unwanted whitespace
633                                         os << "%\n";
634                                         texrow.newline();
635                                 }
636                                 // With CJK, the CJK tag had to be closed first (see above)
637                                 if (runparams.encoding->package() == Encoding::CJK) {
638                                         os << from_ascii(subst(
639                                                 lang_begin_command,
640                                                 "$$lang",
641                                                 par_lang))
642                                         // the '%' is necessary to prevent unwanted whitespace
643                                         << "%\n";
644                                         texrow.newline();
645                                 }
646                                 runparams.encoding = encoding;
647                         }
648                         break;
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 (par.allowParagraphCustomization()) {
657                 if (par.params().startOfAppendix()) {
658                         os << "\\appendix\n";
659                         texrow.newline();
660                 }
661
662                 if (!par.params().spacing().isDefault()
663                         && (pit == 0 || !priorpar->hasSameLayout(par)))
664                 {
665                         os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
666                             << '\n';
667                         texrow.newline();
668                 }
669
670                 if (style.isCommand()) {
671                         os << '\n';
672                         texrow.newline();
673                 }
674         }
675
676         switch (style.latextype) {
677         case LATEX_COMMAND:
678                 os << '\\' << from_ascii(style.latexname());
679
680                 // Separate handling of optional argument inset.
681                 if (style.optargs != 0 || style.reqargs != 0) {
682                         int ret = latexArgInsets(par, os, runparams, style.reqargs, style.optargs);
683                         while (ret > 0) {
684                                 texrow.newline();
685                                 --ret;
686                         }
687                 }
688                 else
689                         os << from_ascii(style.latexparam());
690                 break;
691         case LATEX_ITEM_ENVIRONMENT:
692         case LATEX_LIST_ENVIRONMENT:
693                 os << "\\item ";
694                 break;
695         case LATEX_BIB_ENVIRONMENT:
696                 // ignore this, the inset will write itself
697                 break;
698         default:
699                 break;
700         }
701
702         Font const outerfont = text.outerFont(pit);
703
704         // FIXME UNICODE
705         os << from_utf8(everypar);
706         par.latex(bparams, outerfont, os, texrow, runparams, start_pos, end_pos);
707
708         // Make sure that \\par is done with the font of the last
709         // character if this has another size as the default.
710         // This is necessary because LaTeX (and LyX on the screen)
711         // calculates the space between the baselines according
712         // to this font. (Matthias)
713         //
714         // Is this really needed ? (Dekel)
715         // We do not need to use to change the font for the last paragraph
716         // or for a command.
717
718         Font const font = par.empty()
719                  ? par.getLayoutFont(bparams, outerfont)
720                  : par.getFont(bparams, par.size() - 1, outerfont);
721
722         bool const is_command = style.isCommand();
723
724         if (style.resfont.size() != font.fontInfo().size()
725             && nextpar
726             && !is_command) {
727                 os << '{';
728                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
729         } else if (is_command) {
730                 os << '}';
731                 if (runparams.encoding != prev_encoding) {
732                         runparams.encoding = prev_encoding;
733                         if (!runparams.isFullUnicode())
734                                 os << setEncoding(prev_encoding->iconvName());
735                 }
736         }
737
738         bool pending_newline = false;
739         switch (style.latextype) {
740         case LATEX_ITEM_ENVIRONMENT:
741         case LATEX_LIST_ENVIRONMENT:
742                 if (nextpar && (par.params().depth() < nextpar->params().depth()))
743                         pending_newline = true;
744                 break;
745         case LATEX_ENVIRONMENT: {
746                 // if its the last paragraph of the current environment
747                 // skip it otherwise fall through
748                 if (nextpar
749                         && (nextpar->layout() != par.layout()
750                         || nextpar->params().depth() != par.params().depth()))
751                         break;
752         }
753
754         // fall through possible
755         default:
756                 // we don't need it for the last paragraph!!!
757                 if (nextpar)
758                         pending_newline = true;
759         }
760
761         if (par.allowParagraphCustomization()) {
762                 if (!par.params().spacing().isDefault()
763                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
764                         if (pending_newline) {
765                                 os << '\n';
766                                 texrow.newline();
767                         }
768                         os << from_ascii(par.params().spacing().writeEnvirEnd(useSetSpace));
769                         pending_newline = true;
770                 }
771         }
772
773         // Closing the language is needed for the last paragraph; it is also
774         // needed if we're within an \L or \R that we may have opened above (not
775         // necessarily in this paragraph) and are about to close.
776         bool closing_rtl_ltr_environment = !runparams.use_polyglossia
777                 // not for ArabTeX
778                 && (par_language->lang() != "arabic_arabtex"
779                     && outer_language->lang() != "arabic_arabtex")
780                      // have we opened and \L or \R environment?
781                 && runparams.local_font != 0
782                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
783                 // are we about to close the language?
784                 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
785                    || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
786
787         if (closing_rtl_ltr_environment
788                 || (runparams.isLastPar && par_language->babel() != outer_language->babel())) {
789                 // Since \selectlanguage write the language to the aux file,
790                 // we need to reset the language at the end of footnote or
791                 // float.
792
793                 if (pending_newline) {
794                         os << '\n';
795                         texrow.newline();
796                 }
797                 // when the paragraph uses CJK, the language has to be closed earlier
798                 if (font.language()->encoding()->package() != Encoding::CJK) {
799                         if (lang_end_command.empty()) {
800                                 // If this is a child, we should restore the
801                                 // master language after the last paragraph.
802                                 Language const * const current_language =
803                                         (runparams.isLastPar && runparams.master_language)
804                                                 ? runparams.master_language
805                                                 : outer_language;
806                                 string const current_lang = runparams.use_polyglossia ?
807                                         getPolyglossiaEnvName(current_language)
808                                         : current_language->babel();
809                                 if (!current_lang.empty()) {
810                                         os << from_ascii(subst(
811                                                 lang_begin_command,
812                                                 "$$lang",
813                                                 current_lang));
814                                         pending_newline = true;
815                                 }
816                         } else if (!par_lang.empty()) {
817                                 os << from_ascii(subst(
818                                         lang_end_command,
819                                         "$$lang",
820                                         par_lang));
821                                 pending_newline = true;
822                         }
823                 }
824         }
825         if (closing_rtl_ltr_environment)
826                 os << "}";
827
828         if (pending_newline) {
829                 os << '\n';
830                 texrow.newline();
831         }
832
833         // if this is a CJK-paragraph and the next isn't, close CJK
834         // also if the next paragraph is a multilingual environment (because of nesting)
835         if (nextpar
836                 && open_encoding_ == CJK
837                 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
838                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
839                 // inbetween environments, CJK has to be closed later (nesting!)
840                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
841                 os << "\\end{CJK}\n";
842                 open_encoding_ = none;
843         }
844
845         // If this is the last paragraph, close the CJK environment
846         // if necessary. If it's an environment, we'll have to \end that first.
847         if (runparams.isLastPar && !style.isEnvironment()) {
848                 switch (open_encoding_) {
849                         case CJK: {
850                                 // do nothing at the end of child documents
851                                 if (maintext && buf.masterBuffer() != &buf)
852                                         break;
853                                 // end of main text
854                                 if (maintext) {
855                                         os << '\n';
856                                         texrow.newline();
857                                         os << "\\end{CJK}\n";
858                                         texrow.newline();
859                                 // end of an inset
860                                 } else
861                                         os << "\\end{CJK}";
862                                 open_encoding_ = none;
863                                 break;
864                         }
865                         case inputenc: {
866                                 os << "\\egroup";
867                                 open_encoding_ = none;
868                                 break;
869                         }
870                         case none:
871                         default:
872                                 // do nothing
873                                 break;
874                 }
875         }
876
877         // If this is the last paragraph, and a local_font was set upon entering
878         // the inset, and we're using "auto" or "default" encoding, the encoding
879         // should be set back to that local_font's encoding.
880         // However, do not change the encoding when a fully unicode aware backend
881         // such as XeTeX is used.
882         if (runparams.isLastPar && runparams_in.local_font != 0
883             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
884             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
885             && (!runparams.isFullUnicode())) {
886                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
887                 os << setEncoding(runparams_in.encoding->iconvName());
888         }
889         // Otherwise, the current encoding should be set for the next paragraph.
890         else
891                 runparams_in.encoding = runparams.encoding;
892
893
894         // we don't need a newline for the last paragraph!!!
895         // Note from JMarc: we will re-add a \n explicitly in
896         // TeXEnvironment, because it is needed in this case
897         if (nextpar) {
898                 Layout const & next_layout = nextpar->layout();
899                 if (style == next_layout
900                     // no blank lines before environments!
901                     || !next_layout.isEnvironment()
902                     // unless there's a depth change
903                     // FIXME What we really want to do here is put every \begin and \end
904                     // tag on a new line (which was not the case with nested environments).
905                     // But in the present state of play, we don't have access to the
906                     // information whether the current TeX row is empty or not.
907                     // For some ideas about how to fix this, see this thread:
908                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
909                     || nextpar->params().depth() != par.params().depth()) {
910                         os << '\n';
911                         texrow.newline();
912                 }
913         }
914
915         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
916                 << &par << " next " << nextpar);
917
918         return;
919 }
920
921
922 // LaTeX all paragraphs
923 void latexParagraphs(Buffer const & buf,
924                      Text const & text,
925                      odocstream & os,
926                      TexRow & texrow,
927                      OutputParams const & runparams,
928                      string const & everypar)
929 {
930         BufferParams const & bparams = buf.params();
931
932         bool const maintext = text.isMainText();
933         bool const is_child = buf.masterBuffer() != &buf;
934
935         // Open a CJK environment at the beginning of the main buffer
936         // if the document's language is a CJK language
937         // (but not in child documents)
938         if (maintext && !is_child
939             && bparams.encoding().package() == Encoding::CJK) {
940                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
941                 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
942                 texrow.newline();
943                 open_encoding_ = CJK;
944         }
945         // if "auto begin" is switched off, explicitly switch the
946         // language on at start
947         string const mainlang = runparams.use_polyglossia ?
948                 getPolyglossiaEnvName(bparams.language)
949                 : bparams.language->babel();
950         string const lang_begin_command = runparams.use_polyglossia ?
951                 "\\begin{$$lang}" : lyxrc.language_command_begin;
952
953         if (maintext && !lyxrc.language_auto_begin &&
954             !mainlang.empty()) {
955                 // FIXME UNICODE
956                 os << from_utf8(subst(lang_begin_command,
957                                         "$$lang",
958                                         mainlang));
959                 if (runparams.use_polyglossia
960                     && !bparams.language->polyglossiaOpts().empty())
961                         os << "["
962                             << from_ascii(bparams.language->polyglossiaOpts())
963                             << "]";
964                 os << '\n';
965                 texrow.newline();
966         }
967
968         ParagraphList const & paragraphs = text.paragraphs();
969         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
970
971         if (runparams.par_begin == runparams.par_end) {
972                 // The full doc will be exported but it is easier to just rely on
973                 // runparams range parameters that will be passed TeXEnvironment.
974                 runparams.par_begin = 0;
975                 runparams.par_end = paragraphs.size();
976         }
977
978         pit_type pit = runparams.par_begin;
979         // lastpit is for the language check after the loop.
980         pit_type lastpit = pit;
981         // variables used in the loop:
982         bool was_title = false;
983         bool already_title = false;
984         DocumentClass const & tclass = bparams.documentClass();
985
986         for (; pit < runparams.par_end; ++pit) {
987                 lastpit = pit;
988                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
989
990                 // FIXME This check should not be needed. We should
991                 // perhaps issue an error if it is.
992                 Layout const & layout = text.inset().forcePlainLayout() ?
993                                 tclass.plainLayout() : par->layout();
994
995                 if (layout.intitle) {
996                         if (already_title) {
997                                 LYXERR0("Error in latexParagraphs: You"
998                                         " should not mix title layouts"
999                                         " with normal ones.");
1000                         } else if (!was_title) {
1001                                 was_title = true;
1002                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1003                                         os << "\\begin{"
1004                                                         << from_ascii(tclass.titlename())
1005                                                         << "}\n";
1006                                         texrow.newline();
1007                                 }
1008                         }
1009                 } else if (was_title && !already_title) {
1010                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1011                                 os << "\\end{" << from_ascii(tclass.titlename())
1012                                                 << "}\n";
1013                         }
1014                         else {
1015                                 os << "\\" << from_ascii(tclass.titlename())
1016                                                 << "\n";
1017                         }
1018                         texrow.newline();
1019                         already_title = true;
1020                         was_title = false;
1021                 }
1022
1023
1024                 if (!layout.isEnvironment() && par->params().leftIndent().zero()) {
1025                         // This is a standard top level paragraph, TeX it and continue.
1026                         TeXOnePar(buf, text, pit, os, texrow, runparams, everypar);
1027                         continue;
1028                 }
1029                 
1030                 TeXEnvironementData const data = prepareEnvironement(buf, text, par,
1031                         os, texrow, runparams);
1032                 // pit can be changed in TeXEnvironment.
1033                 TeXEnvironment(buf, text, runparams, pit, os, texrow);
1034                 finishEnvironement(os, texrow, runparams, data);
1035         }
1036
1037         if (pit == runparams.par_end) {
1038                         // Make sure that the last paragraph is
1039                         // correctly terminated (because TeXOnePar does
1040                         // not add a \n in this case)
1041                         //os << '\n';
1042                         //texrow.newline();
1043         }
1044
1045         // It might be that we only have a title in this document
1046         if (was_title && !already_title) {
1047                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1048                         os << "\\end{" << from_ascii(tclass.titlename())
1049                             << "}\n";
1050                 }
1051                 else {
1052                         os << "\\" << from_ascii(tclass.titlename())
1053                             << "\n";
1054                                 }
1055                 texrow.newline();
1056         }
1057
1058         // if "auto end" is switched off, explicitly close the language at the end
1059         // but only if the last par is in a babel language
1060         string const lang_end_command = runparams.use_polyglossia ?
1061                 "\\end{$$lang}" : lyxrc.language_command_end;
1062         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1063                 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1064                 os << from_utf8(subst(lang_end_command,
1065                                         "$$lang",
1066                                         mainlang))
1067                         << '\n';
1068                 texrow.newline();
1069         }
1070
1071         // If the last paragraph is an environment, we'll have to close
1072         // CJK at the very end to do proper nesting.
1073         if (maintext && !is_child && open_encoding_ == CJK) {
1074                 os << "\\end{CJK}\n";
1075                 texrow.newline();
1076                 open_encoding_ = none;
1077         }
1078
1079         // reset inherited encoding
1080         if (cjk_inherited_ > 0) {
1081                 cjk_inherited_ -= 1;
1082                 if (cjk_inherited_ == 0)
1083                         open_encoding_ = CJK;
1084         }
1085 }
1086
1087
1088 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1089                    OutputParams const & runparams, Encoding const & newEnc,
1090                    bool force)
1091 {
1092         Encoding const & oldEnc = *runparams.encoding;
1093         bool moving_arg = runparams.moving_arg;
1094         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
1095                 || moving_arg))
1096                 return make_pair(false, 0);
1097
1098         // Do nothing if the encoding is unchanged.
1099         if (oldEnc.name() == newEnc.name())
1100                 return make_pair(false, 0);
1101
1102         // FIXME We ignore encoding switches from/to encodings that do
1103         // neither support the inputenc package nor the CJK package here.
1104         // This does of course only work in special cases (e.g. switch from
1105         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1106         // but it is the best we can do
1107         if (oldEnc.package() == Encoding::none
1108                 || newEnc.package() == Encoding::none)
1109                 return make_pair(false, 0);
1110
1111         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1112                 << oldEnc.name() << " to " << newEnc.name());
1113         os << setEncoding(newEnc.iconvName());
1114         if (bparams.inputenc == "default")
1115                 return make_pair(true, 0);
1116
1117         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1118         switch (newEnc.package()) {
1119                 case Encoding::none:
1120                 case Encoding::japanese:
1121                         // shouldn't ever reach here, see above
1122                         return make_pair(true, 0);
1123                 case Encoding::inputenc: {
1124                         int count = inputenc_arg.length();
1125                         if (oldEnc.package() == Encoding::CJK &&
1126                             open_encoding_ == CJK) {
1127                                 os << "\\end{CJK}";
1128                                 open_encoding_ = none;
1129                                 count += 9;
1130                         }
1131                         else if (oldEnc.package() == Encoding::inputenc &&
1132                                  open_encoding_ == inputenc) {
1133                                 os << "\\egroup";
1134                                 open_encoding_ = none;
1135                                 count += 7;
1136                         }
1137                         if (runparams.local_font != 0
1138                             &&  oldEnc.package() == Encoding::CJK) {
1139                                 // within insets, \inputenc switches need
1140                                 // to be embraced within \bgroup...\egroup;
1141                                 // else CJK fails.
1142                                 os << "\\bgroup";
1143                                 count += 7;
1144                                 open_encoding_ = inputenc;
1145                         }
1146                         // with the japanese option, inputenc is omitted.
1147                         if (runparams.use_japanese)
1148                                 return make_pair(true, count);
1149                         os << "\\inputencoding{" << inputenc_arg << '}';
1150                         return make_pair(true, count + 16);
1151                 }
1152                 case Encoding::CJK: {
1153                         int count = inputenc_arg.length();
1154                         if (oldEnc.package() == Encoding::CJK &&
1155                             open_encoding_ == CJK) {
1156                                 os << "\\end{CJK}";
1157                                 count += 9;
1158                         }
1159                         if (oldEnc.package() == Encoding::inputenc &&
1160                             open_encoding_ == inputenc) {
1161                                 os << "\\egroup";
1162                                 count += 7;
1163                         }
1164                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1165                            << from_ascii(bparams.fonts_cjk) << "}";
1166                         open_encoding_ = CJK;
1167                         return make_pair(true, count + 15);
1168                 }
1169         }
1170         // Dead code to avoid a warning:
1171         return make_pair(true, 0);
1172
1173 }
1174
1175 } // namespace lyx