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