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