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