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