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