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