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