]> git.lyx.org Git - features.git/blob - src/output_latex.cpp
Pass local font to arguments and assure pass_thru is inherited
[features.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)
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                                 unsigned int const nr = convert<unsigned int>(ins->name());
334                                 ilist[nr] = ins;
335                                 Layout::LaTeXArgMap::const_iterator const lit =
336                                                 latexargs.find(nr);
337                                 if (lit != latexargs.end()) {
338                                         Layout::latexarg const & arg = (*lit).second;
339                                         if (!arg.requires.empty()) {
340                                                 vector<string> req = getVectorFromString(arg.requires);
341                                                 required.insert(required.end(), req.begin(), req.end());
342                                         }
343                                 }
344                         }
345                 }
346         }
347
348         unsigned int const argnr = latexargs.size();
349         if (argnr == 0)
350                 return;
351
352         for (unsigned int i = 1; i <= argnr; ++i) {
353                 map<int, InsetArgument const *>::const_iterator lit = ilist.find(i);
354                 bool inserted = false;
355                 if (lit != ilist.end()) {
356                         InsetArgument const * ins = (*lit).second;
357                         if (ins) {
358                                 Layout::LaTeXArgMap::const_iterator const lait =
359                                                 latexargs.find(convert<unsigned int>(ins->name()));
360                                 if (lait != latexargs.end()) {
361                                         Layout::latexarg arg = (*lait).second;
362                                         docstring ldelim = arg.mandatory ?
363                                                         from_ascii("{") : from_ascii("[");
364                                         docstring rdelim = arg.mandatory ?
365                                                         from_ascii("}") : from_ascii("]");
366                                         if (!arg.ldelim.empty())
367                                                 ldelim = arg.ldelim;
368                                         if (!arg.rdelim.empty())
369                                                 rdelim = arg.rdelim;
370                                         ins->latexArgument(os, runparams, ldelim, rdelim);
371                                         inserted = true;
372                                 }
373                         }
374                 }
375                 if (!inserted) {
376                         Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
377                         Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
378                         for (; lait != laend; ++lait) {
379                                 if ((*lait).first == i) {
380                                         Layout::latexarg arg = (*lait).second;
381                                         if (arg.mandatory) {
382                                                 docstring ldelim = arg.ldelim.empty() ?
383                                                                 from_ascii("{") : arg.ldelim;
384                                                 docstring rdelim = arg.rdelim.empty() ?
385                                                                 from_ascii("}") : arg.rdelim;
386                                                 os << ldelim << rdelim;
387                                         } else if (find(required.begin(), required.end(),
388                                                    convert<string>((*lait).first)) != required.end()) {
389                                                 docstring ldelim = arg.ldelim.empty() ?
390                                                                 from_ascii("[") : arg.ldelim;
391                                                 docstring rdelim = arg.rdelim.empty() ?
392                                                                 from_ascii("]") : arg.rdelim;
393                                                 os << ldelim << rdelim;
394                                         } else
395                                                 break;
396                                 }
397                         }
398                 }
399         }
400 }
401
402 namespace {
403
404 // output the proper paragraph start according to latextype.
405 void parStartCommand(Paragraph const & par, otexstream & os,
406                      OutputParams const & runparams, Layout const & style) 
407 {
408         switch (style.latextype) {
409         case LATEX_COMMAND:
410                 os << '\\' << from_ascii(style.latexname());
411
412                 // Separate handling of optional argument inset.
413                 if (!style.latexargs().empty())
414                         latexArgInsets(par, os, runparams, style.latexargs());
415                 os << from_ascii(style.latexparam());
416                 break;
417         case LATEX_ITEM_ENVIRONMENT:
418         case LATEX_LIST_ENVIRONMENT:
419                 os << "\\item ";
420                 break;
421         case LATEX_BIB_ENVIRONMENT:
422                 // ignore this, the inset will write itself
423                 break;
424         default:
425                 break;
426         }
427 }
428
429 } // namespace anon
430
431 // FIXME: this should be anonymous
432 void TeXOnePar(Buffer const & buf,
433                Text const & text,
434                pit_type pit,
435                otexstream & os,
436                OutputParams const & runparams_in,
437                string const & everypar,
438                int start_pos, int end_pos)
439 {
440         BufferParams const & bparams = buf.params();
441         ParagraphList const & paragraphs = text.paragraphs();
442         Paragraph const & par = paragraphs.at(pit);
443         // FIXME This check should not really be needed.
444         // Perhaps we should issue an error if it is.
445         Layout const style = text.inset().forcePlainLayout() ?
446                 bparams.documentClass().plainLayout() : par.layout();
447
448         if (style.inpreamble)
449                 return;
450
451         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " ptr " << &par << " '"
452                 << everypar << "'");
453
454         OutputParams runparams = runparams_in;
455         runparams.isLastPar = (pit == pit_type(paragraphs.size() - 1));
456         // We reinitialze par begin and end to be on the safe side
457         // with embedded inset as we don't know if they set those
458         // value correctly.
459         runparams.par_begin = 0;
460         runparams.par_end = 0;
461
462         bool const maintext = text.isMainText();
463         // we are at the beginning of an inset and CJK is already open;
464         // we count inheritation levels to get the inset nesting right.
465         if (pit == 0 && !maintext
466             && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
467                 cjk_inherited_ += 1;
468                 open_encoding_ = none;
469         }
470
471         if (text.inset().isPassThru()) {
472                 Font const outerfont = text.outerFont(pit);
473
474                 // No newline before first paragraph in this lyxtext
475                 if (pit > 0) {
476                         os << '\n';
477                         if (!text.inset().getLayout().parbreakIsNewline())
478                                 os << '\n';
479                 }
480
481                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
482                 return;
483         }
484
485         Paragraph const * nextpar = runparams.isLastPar
486                 ? 0 : &paragraphs.at(pit + 1);
487
488         if (style.pass_thru) {
489                 Font const outerfont = text.outerFont(pit);
490                 runparams.local_font = &par.getFirstFontSettings(bparams);
491                 parStartCommand(par, os, runparams, style);
492
493                 par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
494
495                 // I did not create a parEndCommand for this minuscule
496                 // task because in the other user of parStartCommand
497                 // the code is different (JMarc)
498                 if (style.isCommand())
499                         os << "}\n";
500                 else
501                         os << '\n';
502                 if (!style.parbreak_is_newline) {
503                         os << '\n';
504                 } else if (nextpar) {
505                         Layout const nextstyle = text.inset().forcePlainLayout()
506                                 ? bparams.documentClass().plainLayout()
507                                 : nextpar->layout();
508                         if (nextstyle.name() != style.name())
509                                 os << '\n';
510                 }
511
512                 return;
513         }
514
515         // This paragraph's language
516         Language const * const par_language = par.getParLanguage(bparams);
517         // The document's language
518         Language const * const doc_language = bparams.language;
519         // The language that was in effect when the environment this paragraph is
520         // inside of was opened
521         Language const * const outer_language =
522                 (runparams.local_font != 0) ?
523                         runparams.local_font->language() : doc_language;
524
525         Paragraph const * priorpar = (pit == 0) ? 0 : &paragraphs.at(pit - 1);
526
527         // The previous language that was in effect is the language of the
528         // previous paragraph, unless the previous paragraph is inside an
529         // environment with nesting depth greater than (or equal to, but with
530         // a different layout) the current one. If there is no previous
531         // paragraph, the previous language is the outer language.
532         bool const use_prev_env_language = prev_env_language_ != 0
533                         && priorpar
534                         && priorpar->layout().isEnvironment()
535                         && (priorpar->getDepth() > par.getDepth()
536                             || (priorpar->getDepth() == par.getDepth()
537                                     && priorpar->layout() != par.layout()));
538         Language const * const prev_language =
539                 (pit != 0)
540                 ? (use_prev_env_language ? prev_env_language_
541                                          : priorpar->getParLanguage(bparams))
542                 : outer_language;
543
544
545         bool const use_polyglossia = runparams.use_polyglossia;
546         string const par_lang = use_polyglossia ?
547                 getPolyglossiaEnvName(par_language): par_language->babel();
548         string const prev_lang = use_polyglossia ?
549                 getPolyglossiaEnvName(prev_language) : prev_language->babel();
550         string const doc_lang = use_polyglossia ?
551                 getPolyglossiaEnvName(doc_language) : doc_language->babel();
552         string const outer_lang = use_polyglossia ?
553                 getPolyglossiaEnvName(outer_language) : outer_language->babel();
554         string const lang_begin_command = use_polyglossia ?
555                 "\\begin{$$lang}" : lyxrc.language_command_begin;
556         string const lang_end_command = use_polyglossia ?
557                 "\\end{$$lang}" : lyxrc.language_command_end;
558
559         if (par_lang != prev_lang
560                 // check if we already put language command in TeXEnvironment()
561                 && !(style.isEnvironment()
562                      && (pit == 0 || (priorpar->layout() != par.layout()
563                                           && priorpar->getDepth() <= par.getDepth())
564                                   || priorpar->getDepth() < par.getDepth())))
565         {
566                 if (!lang_end_command.empty() &&
567                     prev_lang != outer_lang &&
568                     !prev_lang.empty())
569                 {
570                         os << from_ascii(subst(lang_end_command,
571                                 "$$lang",
572                                 prev_lang))
573                            // the '%' is necessary to prevent unwanted whitespace
574                            << "%\n";
575                 }
576
577                 // We need to open a new language if we couldn't close the previous
578                 // one (because there's no language_command_end); and even if we closed
579                 // the previous one, if the current language is different than the
580                 // outer_language (which is currently in effect once the previous one
581                 // is closed).
582                 if ((lang_end_command.empty() || par_lang != outer_lang)
583                         && !par_lang.empty()) {
584                         // If we're inside an inset, and that inset is within an \L or \R
585                         // (or equivalents), then within the inset, too, any opposite
586                         // language paragraph should appear within an \L or \R (in addition
587                         // to, outside of, the normal language switch commands).
588                         // This behavior is not correct for ArabTeX, though.
589                         if (!use_polyglossia
590                             // not for ArabTeX
591                                 && par_language->lang() != "arabic_arabtex"
592                                 && outer_language->lang() != "arabic_arabtex"
593                             // are we in an inset?
594                             && runparams.local_font != 0
595                             // is the inset within an \L or \R?
596                             //
597                             // FIXME: currently, we don't check this; this means that
598                             // we'll have unnnecessary \L and \R commands, but that
599                             // doesn't seem to hurt (though latex will complain)
600                             //
601                             // is this paragraph in the opposite direction?
602                             && runparams.local_font->isRightToLeft() != par_language->rightToLeft()) {
603                                 // FIXME: I don't have a working copy of the Arabi package, so
604                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
605                                 // or not...
606                                 if (par_language->lang() == "farsi")
607                                         os << "\\textFR{";
608                                 else if (outer_language->lang() == "farsi")
609                                         os << "\\textLR{";
610                                 else if (par_language->lang() == "arabic_arabi")
611                                         os << "\\textAR{";
612                                 else if (outer_language->lang() == "arabic_arabi")
613                                         os << "\\textLR{";
614                                 // remaining RTL languages currently is hebrew
615                                 else if (par_language->rightToLeft())
616                                         os << "\\R{";
617                                 else
618                                         os << "\\L{";
619                         }
620                         // With CJK, the CJK tag has to be closed first (see below)
621                         if (runparams.encoding->package() != Encoding::CJK
622                             && !par_lang.empty()) {
623                                 os << from_ascii(subst(
624                                         lang_begin_command,
625                                         "$$lang",
626                                         par_lang));
627                                 if (use_polyglossia
628                                     && !par_language->polyglossiaOpts().empty())
629                                                 os << "["
630                                                   << from_ascii(par_language->polyglossiaOpts())
631                                                   << "]";
632                                    // the '%' is necessary to prevent unwanted whitespace
633                                 os << "%\n";
634                         }
635                 }
636         }
637
638         // Switch file encoding if necessary; no need to do this for "default"
639         // encoding, since this only affects the position of the outputted
640         // \inputencoding command; the encoding switch will occur when necessary
641         if (bparams.inputenc == "auto"
642                 && runparams.encoding->package() != Encoding::none) {
643                 // Look ahead for future encoding changes.
644                 // We try to output them at the beginning of the paragraph,
645                 // since the \inputencoding command is not allowed e.g. in
646                 // sections. For this reason we only set runparams.moving_arg
647                 // after checking for the encoding change, otherwise the
648                 // change would be always avoided by switchEncoding().
649                 for (pos_type i = 0; i < par.size(); ++i) {
650                         char_type const c = par.getChar(i);
651                         Encoding const * const encoding =
652                                 par.getFontSettings(bparams, i).language()->encoding();
653                         if (encoding->package() != Encoding::CJK
654                                 && runparams.encoding->package() == Encoding::inputenc
655                                 && c < 0x80)
656                                 continue;
657                         if (par.isInset(i))
658                                 break;
659                         // All characters before c are in the ASCII range, and
660                         // c is non-ASCII (but no inset), so change the
661                         // encoding to that required by the language of c.
662                         // With CJK, only add switch if we have CJK content at the beginning
663                         // of the paragraph
664                         if (i != 0 && encoding->package() == Encoding::CJK)
665                                 continue;
666
667                         pair<bool, int> enc_switch = switchEncoding(os.os(),
668                                                 bparams, runparams, *encoding);
669                         // the following is necessary after a CJK environment in a multilingual
670                         // context (nesting issue).
671                         if (par_language->encoding()->package() == Encoding::CJK
672                                 && open_encoding_ != CJK && cjk_inherited_ == 0) {
673                                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
674                                    << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
675                                 open_encoding_ = CJK;
676                         }
677                         if (encoding->package() != Encoding::none && enc_switch.first) {
678                                 if (enc_switch.second > 0) {
679                                         // the '%' is necessary to prevent unwanted whitespace
680                                         os << "%\n";
681                                 }
682                                 // With CJK, the CJK tag had to be closed first (see above)
683                                 if (runparams.encoding->package() == Encoding::CJK
684                                     && !par_lang.empty()) {
685                                         os << from_ascii(subst(
686                                                 lang_begin_command,
687                                                 "$$lang",
688                                                 par_lang))
689                                         // the '%' is necessary to prevent unwanted whitespace
690                                         << "%\n";
691                                 }
692                                 runparams.encoding = encoding;
693                         }
694                         break;
695                 }
696         }
697
698         runparams.moving_arg |= style.needprotect;
699         Encoding const * const prev_encoding = runparams.encoding;
700
701         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
702         if (par.allowParagraphCustomization()) {
703                 if (par.params().startOfAppendix()) {
704                         os << "\\appendix\n";
705                 }
706
707                 if (!par.params().spacing().isDefault()
708                         && (pit == 0 || !priorpar->hasSameLayout(par)))
709                 {
710                         os << from_ascii(par.params().spacing().writeEnvirBegin(useSetSpace))
711                             << '\n';
712                 }
713
714                 if (style.isCommand()) {
715                         os << '\n';
716                 }
717         }
718
719         runparams.local_font = &par.getFirstFontSettings(bparams);
720         parStartCommand(par, os, runparams, style);
721         Font const outerfont = text.outerFont(pit);
722
723         // FIXME UNICODE
724         os << from_utf8(everypar);
725         par.latex(bparams, outerfont, os, runparams, start_pos, end_pos);
726
727         // Make sure that \\par is done with the font of the last
728         // character if this has another size as the default.
729         // This is necessary because LaTeX (and LyX on the screen)
730         // calculates the space between the baselines according
731         // to this font. (Matthias)
732         //
733         // Is this really needed ? (Dekel)
734         // We do not need to use to change the font for the last paragraph
735         // or for a command.
736
737         Font const font = par.empty()
738                  ? par.getLayoutFont(bparams, outerfont)
739                  : par.getFont(bparams, par.size() - 1, outerfont);
740
741         bool const is_command = style.isCommand();
742
743         if (style.resfont.size() != font.fontInfo().size()
744             && nextpar
745             && !is_command) {
746                 os << '{';
747                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
748         } else if (is_command) {
749                 os << '}';
750                 if (runparams.encoding != prev_encoding) {
751                         runparams.encoding = prev_encoding;
752                         if (!runparams.isFullUnicode())
753                                 os << setEncoding(prev_encoding->iconvName());
754                 }
755         }
756
757         bool pending_newline = false;
758         bool unskip_newline = false;
759         switch (style.latextype) {
760         case LATEX_ITEM_ENVIRONMENT:
761         case LATEX_LIST_ENVIRONMENT:
762                 if (nextpar && (par.params().depth() < nextpar->params().depth()))
763                         pending_newline = true;
764                 break;
765         case LATEX_ENVIRONMENT: {
766                 // if its the last paragraph of the current environment
767                 // skip it otherwise fall through
768                 if (nextpar
769                         && (nextpar->layout() != par.layout()
770                         || nextpar->params().depth() != par.params().depth()))
771                         break;
772         }
773
774         // fall through possible
775         default:
776                 // we don't need it for the last paragraph!!!
777                 if (nextpar)
778                         pending_newline = true;
779         }
780
781         if (par.allowParagraphCustomization()) {
782                 if (!par.params().spacing().isDefault()
783                         && (runparams.isLastPar || !nextpar->hasSameLayout(par))) {
784                         if (pending_newline)
785                                 os << '\n';
786                         os << from_ascii(par.params().spacing().writeEnvirEnd(useSetSpace));
787                         pending_newline = true;
788                 }
789         }
790
791         // Closing the language is needed for the last paragraph; it is also
792         // needed if we're within an \L or \R that we may have opened above (not
793         // necessarily in this paragraph) and are about to close.
794         bool closing_rtl_ltr_environment = !use_polyglossia
795                 // not for ArabTeX
796                 && (par_language->lang() != "arabic_arabtex"
797                     && outer_language->lang() != "arabic_arabtex")
798                      // have we opened and \L or \R environment?
799                 && runparams.local_font != 0
800                 && runparams.local_font->isRightToLeft() != par_language->rightToLeft()
801                 // are we about to close the language?
802                 &&((nextpar && par_language->babel() != (nextpar->getParLanguage(bparams))->babel())
803                    || (runparams.isLastPar && par_language->babel() != outer_language->babel()));
804
805         if (closing_rtl_ltr_environment
806             || (runparams.isLastPar
807                 && ((!use_polyglossia && par_language->babel() != outer_language->babel())
808                     || (use_polyglossia && par_language->polyglossia() != outer_language->polyglossia())))) {
809                 // Since \selectlanguage write the language to the aux file,
810                 // we need to reset the language at the end of footnote or
811                 // float.
812
813                 if (pending_newline)
814                         os << '\n';
815
816                 // when the paragraph uses CJK, the language has to be closed earlier
817                 if (font.language()->encoding()->package() != Encoding::CJK) {
818                         if (lang_end_command.empty()) {
819                                 // If this is a child, we should restore the
820                                 // master language after the last paragraph.
821                                 Language const * const current_language =
822                                         (runparams.isLastPar && runparams.master_language)
823                                                 ? runparams.master_language
824                                                 : outer_language;
825                                 string const current_lang = use_polyglossia
826                                         ? getPolyglossiaEnvName(current_language)
827                                         : current_language->babel();
828                                 if (!current_lang.empty()) {
829                                         os << from_ascii(subst(
830                                                 lang_begin_command,
831                                                 "$$lang",
832                                                 current_lang));
833                                         pending_newline = true;
834                                         unskip_newline = true;
835                                 }
836                         } else if (!par_lang.empty()) {
837                                 os << from_ascii(subst(
838                                         lang_end_command,
839                                         "$$lang",
840                                         par_lang));
841                                 pending_newline = true;
842                                 unskip_newline = true;
843                         }
844                 }
845         }
846         if (closing_rtl_ltr_environment)
847                 os << "}";
848
849         if (pending_newline) {
850                 if (unskip_newline)
851                         // prevent unwanted whitespace
852                         os << '%';
853                 os << '\n';
854         }
855
856         // if this is a CJK-paragraph and the next isn't, close CJK
857         // also if the next paragraph is a multilingual environment (because of nesting)
858         if (nextpar
859                 && open_encoding_ == CJK
860                 && (nextpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK
861                    || (nextpar->layout().isEnvironment() && nextpar->isMultiLingual(bparams)))
862                 // inbetween environments, CJK has to be closed later (nesting!)
863                 && (!style.isEnvironment() || !nextpar->layout().isEnvironment())) {
864                 os << "\\end{CJK}\n";
865                 open_encoding_ = none;
866         }
867
868         // If this is the last paragraph, close the CJK environment
869         // if necessary. If it's an environment, we'll have to \end that first.
870         if (runparams.isLastPar && !style.isEnvironment()) {
871                 switch (open_encoding_) {
872                         case CJK: {
873                                 // do nothing at the end of child documents
874                                 if (maintext && buf.masterBuffer() != &buf)
875                                         break;
876                                 // end of main text
877                                 if (maintext) {
878                                         os << "\n\\end{CJK}\n";
879                                 // end of an inset
880                                 } else
881                                         os << "\\end{CJK}";
882                                 open_encoding_ = none;
883                                 break;
884                         }
885                         case inputenc: {
886                                 os << "\\egroup";
887                                 open_encoding_ = none;
888                                 break;
889                         }
890                         case none:
891                         default:
892                                 // do nothing
893                                 break;
894                 }
895         }
896
897         // If this is the last paragraph, and a local_font was set upon entering
898         // the inset, and we're using "auto" or "default" encoding, the encoding
899         // should be set back to that local_font's encoding.
900         // However, do not change the encoding when a fully unicode aware backend
901         // such as XeTeX is used.
902         if (runparams.isLastPar && runparams_in.local_font != 0
903             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
904             && (bparams.inputenc == "auto" || bparams.inputenc == "default")
905             && (!runparams.isFullUnicode())) {
906                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
907                 os << setEncoding(runparams_in.encoding->iconvName());
908         }
909         // Otherwise, the current encoding should be set for the next paragraph.
910         else
911                 runparams_in.encoding = runparams.encoding;
912
913
914         // we don't need a newline for the last paragraph!!!
915         // Note from JMarc: we will re-add a \n explicitly in
916         // TeXEnvironment, because it is needed in this case
917         if (nextpar) {
918                 Layout const & next_layout = nextpar->layout();
919                 if (style == next_layout
920                     // no blank lines before environments!
921                     || !next_layout.isEnvironment()
922                     // unless there's a depth change
923                     // FIXME What we really want to do here is put every \begin and \end
924                     // tag on a new line (which was not the case with nested environments).
925                     // But in the present state of play, we don't have access to the
926                     // information whether the current TeX row is empty or not.
927                     // For some ideas about how to fix this, see this thread:
928                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
929                     || nextpar->params().depth() != par.params().depth()) {
930                         os << '\n';
931                 }
932         }
933
934         LYXERR(Debug::LATEX, "TeXOnePar for paragraph " << pit << " done; ptr "
935                 << &par << " next " << nextpar);
936
937         return;
938 }
939
940
941 // LaTeX all paragraphs
942 void latexParagraphs(Buffer const & buf,
943                      Text const & text,
944                      otexstream & os,
945                      OutputParams const & runparams,
946                      string const & everypar)
947 {
948         BufferParams const & bparams = buf.params();
949
950         bool const maintext = text.isMainText();
951         bool const is_child = buf.masterBuffer() != &buf;
952
953         // Open a CJK environment at the beginning of the main buffer
954         // if the document's language is a CJK language
955         // (but not in child documents)
956         if (maintext && !is_child
957             && bparams.encoding().package() == Encoding::CJK) {
958                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
959                 << "}{" << from_ascii(bparams.fonts_cjk) << "}%\n";
960                 open_encoding_ = CJK;
961         }
962         // if "auto begin" is switched off, explicitly switch the
963         // language on at start
964         string const mainlang = runparams.use_polyglossia
965                 ? getPolyglossiaEnvName(bparams.language)
966                 : bparams.language->babel();
967         string const lang_begin_command = runparams.use_polyglossia ?
968                 "\\begin{$$lang}" : lyxrc.language_command_begin;
969
970         if (maintext && !lyxrc.language_auto_begin &&
971             !mainlang.empty()) {
972                 // FIXME UNICODE
973                 os << from_utf8(subst(lang_begin_command,
974                                         "$$lang",
975                                         mainlang));
976                 if (runparams.use_polyglossia
977                     && !bparams.language->polyglossiaOpts().empty())
978                         os << "["
979                             << from_ascii(bparams.language->polyglossiaOpts())
980                             << "]";
981                 os << '\n';
982         }
983
984         ParagraphList const & paragraphs = text.paragraphs();
985         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
986
987         if (runparams.par_begin == runparams.par_end) {
988                 // The full doc will be exported but it is easier to just rely on
989                 // runparams range parameters that will be passed TeXEnvironment.
990                 runparams.par_begin = 0;
991                 runparams.par_end = paragraphs.size();
992         }
993
994         pit_type pit = runparams.par_begin;
995         // lastpit is for the language check after the loop.
996         pit_type lastpit = pit;
997         // variables used in the loop:
998         bool was_title = false;
999         bool already_title = false;
1000         DocumentClass const & tclass = bparams.documentClass();
1001
1002         for (; pit < runparams.par_end; ++pit) {
1003                 lastpit = pit;
1004                 ParagraphList::const_iterator par = paragraphs.constIterator(pit);
1005
1006                 // FIXME This check should not be needed. We should
1007                 // perhaps issue an error if it is.
1008                 Layout const & layout = text.inset().forcePlainLayout() ?
1009                                 tclass.plainLayout() : par->layout();
1010
1011                 if (layout.intitle) {
1012                         if (already_title) {
1013                                 LYXERR0("Error in latexParagraphs: You"
1014                                         " should not mix title layouts"
1015                                         " with normal ones.");
1016                         } else if (!was_title) {
1017                                 was_title = true;
1018                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1019                                         os << "\\begin{"
1020                                                         << from_ascii(tclass.titlename())
1021                                                         << "}\n";
1022                                 }
1023                         }
1024                 } else if (was_title && !already_title) {
1025                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
1026                                 os << "\\end{" << from_ascii(tclass.titlename())
1027                                                 << "}\n";
1028                         }
1029                         else {
1030                                 os << "\\" << from_ascii(tclass.titlename())
1031                                                 << "\n";
1032                         }
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, runparams, everypar);
1041                         continue;
1042                 }
1043                 
1044                 TeXEnvironmentData const data =
1045                         prepareEnvironment(buf, text, par, os, runparams);
1046                 // pit can be changed in TeXEnvironment.
1047                 TeXEnvironment(buf, text, runparams, pit, os);
1048                 finishEnvironment(os, 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         }
1057
1058         // It might be that we only have a title in this document
1059         if (was_title && !already_title) {
1060                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
1061                         os << "\\end{" << from_ascii(tclass.titlename())
1062                            << "}\n";
1063                 } else {
1064                         os << "\\" << from_ascii(tclass.titlename())
1065                            << "\n";
1066                 }
1067         }
1068
1069         // if "auto end" is switched off, explicitly close the language at the end
1070         // but only if the last par is in a babel language
1071         string const lang_end_command = runparams.use_polyglossia ?
1072                 "\\end{$$lang}" : lyxrc.language_command_end;
1073         if (maintext && !lyxrc.language_auto_end && !mainlang.empty() &&
1074                 paragraphs.at(lastpit).getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
1075                 os << from_utf8(subst(lang_end_command,
1076                                         "$$lang",
1077                                         mainlang))
1078                         << '\n';
1079         }
1080
1081         // If the last paragraph is an environment, we'll have to close
1082         // CJK at the very end to do proper nesting.
1083         if (maintext && !is_child && open_encoding_ == CJK) {
1084                 os << "\\end{CJK}\n";
1085                 open_encoding_ = none;
1086         }
1087
1088         // reset inherited encoding
1089         if (cjk_inherited_ > 0) {
1090                 cjk_inherited_ -= 1;
1091                 if (cjk_inherited_ == 0)
1092                         open_encoding_ = CJK;
1093         }
1094 }
1095
1096
1097 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
1098                    OutputParams const & runparams, Encoding const & newEnc,
1099                    bool force)
1100 {
1101         Encoding const & oldEnc = *runparams.encoding;
1102         bool moving_arg = runparams.moving_arg;
1103         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
1104                 || moving_arg))
1105                 return make_pair(false, 0);
1106
1107         // Do nothing if the encoding is unchanged.
1108         if (oldEnc.name() == newEnc.name())
1109                 return make_pair(false, 0);
1110
1111         // FIXME We ignore encoding switches from/to encodings that do
1112         // neither support the inputenc package nor the CJK package here.
1113         // This does of course only work in special cases (e.g. switch from
1114         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
1115         // but it is the best we can do
1116         if (oldEnc.package() == Encoding::none
1117                 || newEnc.package() == Encoding::none)
1118                 return make_pair(false, 0);
1119
1120         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
1121                 << oldEnc.name() << " to " << newEnc.name());
1122         os << setEncoding(newEnc.iconvName());
1123         if (bparams.inputenc == "default")
1124                 return make_pair(true, 0);
1125
1126         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
1127         switch (newEnc.package()) {
1128                 case Encoding::none:
1129                 case Encoding::japanese:
1130                         // shouldn't ever reach here, see above
1131                         return make_pair(true, 0);
1132                 case Encoding::inputenc: {
1133                         int count = inputenc_arg.length();
1134                         if (oldEnc.package() == Encoding::CJK &&
1135                             open_encoding_ == CJK) {
1136                                 os << "\\end{CJK}";
1137                                 open_encoding_ = none;
1138                                 count += 9;
1139                         }
1140                         else if (oldEnc.package() == Encoding::inputenc &&
1141                                  open_encoding_ == inputenc) {
1142                                 os << "\\egroup";
1143                                 open_encoding_ = none;
1144                                 count += 7;
1145                         }
1146                         if (runparams.local_font != 0
1147                             &&  oldEnc.package() == Encoding::CJK) {
1148                                 // within insets, \inputenc switches need
1149                                 // to be embraced within \bgroup...\egroup;
1150                                 // else CJK fails.
1151                                 os << "\\bgroup";
1152                                 count += 7;
1153                                 open_encoding_ = inputenc;
1154                         }
1155                         // with the japanese option, inputenc is omitted.
1156                         if (runparams.use_japanese)
1157                                 return make_pair(true, count);
1158                         os << "\\inputencoding{" << inputenc_arg << '}';
1159                         return make_pair(true, count + 16);
1160                 }
1161                 case Encoding::CJK: {
1162                         int count = inputenc_arg.length();
1163                         if (oldEnc.package() == Encoding::CJK &&
1164                             open_encoding_ == CJK) {
1165                                 os << "\\end{CJK}";
1166                                 count += 9;
1167                         }
1168                         if (oldEnc.package() == Encoding::inputenc &&
1169                             open_encoding_ == inputenc) {
1170                                 os << "\\egroup";
1171                                 count += 7;
1172                         }
1173                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
1174                            << from_ascii(bparams.fonts_cjk) << "}";
1175                         open_encoding_ = CJK;
1176                         return make_pair(true, count + 15);
1177                 }
1178         }
1179         // Dead code to avoid a warning:
1180         return make_pair(true, 0);
1181
1182 }
1183
1184 } // namespace lyx