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