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