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