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