]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
Paragraph:
[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 "InsetList.h"
19 #include "Language.h"
20 #include "Layout.h"
21 #include "LyXRC.h"
22 #include "OutputParams.h"
23 #include "Paragraph.h"
24 #include "paragraph_funcs.h"
25 #include "ParagraphParameters.h"
26 #include "TextClass.h"
27 #include "TexRow.h"
28 #include "VSpace.h"
29
30 #include "insets/InsetBibitem.h"
31 #include "insets/InsetOptArg.h"
32
33 #include "support/lassert.h"
34 #include "support/debug.h"
35 #include "support/lstrings.h"
36
37 #include <boost/next_prior.hpp>
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
56
57 ParagraphList::const_iterator
58 TeXEnvironment(Buffer const & buf,
59                Text const & text,
60                ParagraphList::const_iterator pit,
61                odocstream & os, TexRow & texrow,
62                OutputParams const & runparams);
63
64 ParagraphList::const_iterator
65 TeXOnePar(Buffer const & buf,
66           Text const & text,
67           ParagraphList::const_iterator pit,
68           odocstream & os, TexRow & texrow,
69           OutputParams const & runparams,
70           string const & everypar = string());
71
72
73 ParagraphList::const_iterator
74 TeXDeeper(Buffer const & buf,
75           Text const & text,
76           ParagraphList::const_iterator pit,
77           odocstream & os, TexRow & texrow,
78           OutputParams const & runparams)
79 {
80         LYXERR(Debug::LATEX, "TeXDeeper...     " << &*pit);
81         ParagraphList::const_iterator par = pit;
82
83         ParagraphList const & paragraphs = text.paragraphs();
84
85         while (par != paragraphs.end() &&
86                      par->params().depth() == pit->params().depth()) {
87                 if (par->layout().isEnvironment()) {
88                         par = TeXEnvironment(buf, text, par,
89                                              os, texrow, runparams);
90                 } else {
91                         par = TeXOnePar(buf, text, par,
92                                              os, texrow, runparams);
93                 }
94         }
95         LYXERR(Debug::LATEX, "TeXDeeper...done ");
96
97         return par;
98 }
99
100
101 ParagraphList::const_iterator
102 TeXEnvironment(Buffer const & buf,
103                Text const & text,
104                ParagraphList::const_iterator pit,
105                odocstream & os, TexRow & texrow,
106                OutputParams const & runparams)
107 {
108         LYXERR(Debug::LATEX, "TeXEnvironment...     " << &*pit);
109
110         BufferParams const & bparams = buf.params();
111
112         Layout const & style = pit->forcePlainLayout() ?
113                 bparams.documentClass().plainLayout() : pit->layout();
114
115         ParagraphList const & paragraphs = text.paragraphs();
116
117         Language const * const par_language = pit->getParLanguage(bparams);
118         Language const * const doc_language = bparams.language;
119         Language const * const prev_par_language =
120                 (pit != paragraphs.begin())
121                 ? boost::prior(pit)->getParLanguage(bparams)
122                 : doc_language;
123         if (par_language->babel() != prev_par_language->babel()) {
124
125                 if (!lyxrc.language_command_end.empty() &&
126                     prev_par_language->babel() != doc_language->babel() &&
127                     !prev_par_language->babel().empty()) {
128                         os << from_ascii(subst(
129                                 lyxrc.language_command_end,
130                                 "$$lang",
131                                 prev_par_language->babel()))
132                            // the '%' is necessary to prevent unwanted whitespace
133                            << "%\n";
134                         texrow.newline();
135                 }
136
137                 if ((lyxrc.language_command_end.empty() ||
138                      par_language->babel() != doc_language->babel()) &&
139                     !par_language->babel().empty()) {
140                         os << from_ascii(subst(
141                                 lyxrc.language_command_begin,
142                                 "$$lang",
143                                 par_language->babel()))
144                            // the '%' is necessary to prevent unwanted whitespace
145                            << "%\n";
146                         texrow.newline();
147                 }
148         }
149
150         bool leftindent_open = false;
151         if (!pit->params().leftIndent().zero()) {
152                 os << "\\begin{LyXParagraphLeftIndent}{"
153                    << from_ascii(pit->params().leftIndent().asLatexString())
154                    << "}\n";
155                 texrow.newline();
156                 leftindent_open = true;
157         }
158
159         if (style.isEnvironment()) {
160                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
161                 if (style.optionalargs > 0) {
162                         int ret = latexOptArgInsets(*pit, os, runparams,
163                                                     style.optionalargs);
164                         while (ret > 0) {
165                                 texrow.newline();
166                                 --ret;
167                         }
168                 }
169                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
170                         os << '{'
171                            << pit->params().labelWidthString()
172                            << "}\n";
173                 } else if (style.labeltype == LABEL_BIBLIO) {
174                         // ale970405
175                         os << '{' << bibitemWidest(buf) << "}\n";
176                 } else
177                         os << from_ascii(style.latexparam()) << '\n';
178                 texrow.newline();
179         }
180
181         // in multilingual environments, the CJK tags have to be nested properly
182         bool cjk_nested = false;
183         if (par_language->encoding()->package() == Encoding::CJK &&
184             open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
185                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
186                    << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
187                 open_encoding_ = CJK;
188                 cjk_nested = true;
189                 texrow.newline();
190         }
191
192         ParagraphList::const_iterator par = pit;
193         do {
194                 par = TeXOnePar(buf, text, par, os, texrow, runparams);
195
196                 if (par == paragraphs.end()) {
197                         // Make sure that the last paragraph is
198                         // correctly terminated (because TeXOnePar does
199                         // not add a \n in this case)
200                         os << '\n';
201                         texrow.newline();
202                 } else if (par->params().depth() > pit->params().depth()) {
203                         if (par->layout().isParagraph()) {
204                           // Thinko!
205                           // How to handle this? (Lgb)
206                           //&& !suffixIs(os, "\n\n")
207
208                                 // There should be at least one '\n' already
209                                 // but we need there to be two for Standard
210                                 // paragraphs that are depth-increment'ed to be
211                                 // output correctly.  However, tables can
212                                 // also be paragraphs so don't adjust them.
213                                 // ARRae
214                                 // Thinkee:
215                                 // Will it ever harm to have one '\n' too
216                                 // many? i.e. that we sometimes will have
217                                 // three in a row. (Lgb)
218                                 os << '\n';
219                                 texrow.newline();
220                         }
221                         par = TeXDeeper(buf, text, par, os, texrow,
222                                         runparams);
223                 }
224         } while (par != paragraphs.end()
225                  && par->layout() == pit->layout()
226                  && par->params().depth() == pit->params().depth()
227                  && par->params().leftIndent() == pit->params().leftIndent());
228
229         if (open_encoding_ == CJK && cjk_nested) {
230                 // We need to close the encoding even if it does not change
231                 // to do correct environment nesting
232                 os << "\\end{CJK}\n";
233                 texrow.newline();
234                 open_encoding_ = none;
235         }
236
237         if (style.isEnvironment()) {
238                 os << "\\end{" << from_ascii(style.latexname()) << "}\n";
239                 texrow.newline();
240         }
241
242         if (leftindent_open) {
243                 os << "\\end{LyXParagraphLeftIndent}\n";
244                 texrow.newline();
245         }
246
247         if (par != paragraphs.end())
248                 LYXERR(Debug::LATEX, "TeXEnvironment...done " << &*par);
249
250         return par;
251 }
252
253 } // namespace anon
254
255
256 int latexOptArgInsets(Paragraph const & par, odocstream & os,
257         OutputParams const & runparams, int number)
258 {
259         int lines = 0;
260
261         InsetList::const_iterator it = par.insetList().begin();
262         InsetList::const_iterator end = par.insetList().end();
263         for (; it != end && number > 0 ; ++it) {
264                 if (it->inset->lyxCode() == OPTARG_CODE) {
265                         InsetOptArg * ins =
266                                 static_cast<InsetOptArg *>(it->inset);
267                         lines += ins->latexOptional(os, runparams);
268                         --number;
269                 }
270         }
271         return lines;
272 }
273
274
275 namespace {
276
277 ParagraphList::const_iterator
278 TeXOnePar(Buffer const & buf,
279           Text const & text,
280           ParagraphList::const_iterator const pit,
281           odocstream & os, TexRow & texrow,
282           OutputParams const & runparams_in,
283           string const & everypar)
284 {
285         LYXERR(Debug::LATEX, "TeXOnePar...     " << &*pit << " '"
286                 << everypar << "'");
287         BufferParams const & bparams = buf.params();
288         ParagraphList const & paragraphs = text.paragraphs();
289
290         ParagraphList::const_iterator priorpit = pit;
291         if (priorpit != paragraphs.begin())
292                 --priorpit;
293         ParagraphList::const_iterator nextpit = pit;
294         if (nextpit != paragraphs.end())
295                 ++nextpit;
296
297         OutputParams runparams = runparams_in;
298         runparams.isLastPar = nextpit == paragraphs.end();
299
300         if (runparams.verbatim) {
301                 int const dist = distance(paragraphs.begin(), pit);
302                 Font const outerfont = outerFont(dist, paragraphs);
303
304                 // No newline if only one paragraph in this lyxtext
305                 if (dist > 0) {
306                         os << '\n';
307                         texrow.newline();
308                 }
309
310                 /*bool need_par = */ pit->latex(bparams, outerfont,
311                         os, texrow, runparams);
312                 return nextpit;
313         }
314
315         Layout const style = pit->forcePlainLayout() ?
316                 bparams.documentClass().plainLayout() : pit->layout();
317
318         runparams.moving_arg |= style.needprotect;
319
320         bool const maintext = text.isMainText(buf);
321         // we are at the beginning of an inset and CJK is already open;
322         // we count inheritation levels to get the inset nesting right.
323         if (pit == paragraphs.begin() && !maintext
324             && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
325                 cjk_inherited_ += 1;
326                 open_encoding_ = none;
327         }
328
329         // This paragraph's language
330         Language const * const par_language = pit->getParLanguage(bparams);
331         // The document's language
332         Language const * const doc_language = bparams.language;
333         // The language that was in effect when the environment this paragraph is
334         // inside of was opened
335         Language const * const outer_language =
336                 (runparams.local_font != 0) ?
337                         runparams.local_font->language() : doc_language;
338         // The previous language that was in effect is either the language of
339         // the previous paragraph, if there is one, or else the outer language
340         // if there is no previous paragraph
341         Language const * const prev_language =
342                 (pit != paragraphs.begin()) ?
343                         priorpit->getParLanguage(bparams) : outer_language;
344
345         if (par_language->babel() != prev_language->babel()
346             // check if we already put language command in TeXEnvironment()
347             && !(style.isEnvironment()
348                  && (pit == paragraphs.begin() ||
349                      (priorpit->layout() != pit->layout() &&
350                       priorpit->getDepth() <= pit->getDepth())
351                      || priorpit->getDepth() < pit->getDepth())))
352         {
353                 if (!lyxrc.language_command_end.empty() &&
354                     prev_language->babel() != outer_language->babel() &&
355                     !prev_language->babel().empty())
356                 {
357                         os << from_ascii(subst(lyxrc.language_command_end,
358                                 "$$lang",
359                                 prev_language->babel()))
360                            // the '%' is necessary to prevent unwanted whitespace
361                            << "%\n";
362                         texrow.newline();
363                 }
364
365                 // We need to open a new language if we couldn't close the previous
366                 // one (because there's no language_command_end); and even if we closed
367                 // the previous one, if the current language is different than the
368                 // outer_language (which is currently in effect once the previous one
369                 // is closed).
370                 if ((lyxrc.language_command_end.empty() ||
371                      par_language->babel() != outer_language->babel()) &&
372                     !par_language->babel().empty()) {
373                         // If we're inside an inset, and that inset is within an \L or \R
374                         // (or equivalents), then within the inset, too, any opposite
375                         // language paragraph should appear within an \L or \R (in addition
376                         // to, outside of, the normal language switch commands).
377                         // This behavior is not correct for ArabTeX, though.
378                         if (    // not for ArabTeX
379                                         (par_language->lang() != "arabic_arabtex" &&
380                                          outer_language->lang() != "arabic_arabtex") &&
381                                         // are we in an inset?
382                                         runparams.local_font != 0 &&
383                                         // is the inset within an \L or \R?
384                                         //
385                                         // FIXME: currently, we don't check this; this means that
386                                         // we'll have unnnecessary \L and \R commands, but that
387                                         // doesn't seem to hurt (though latex will complain)
388                                         //
389                                         // is this paragraph in the opposite direction?
390                                         runparams.local_font->isRightToLeft() !=
391                                                 par_language->rightToLeft()
392                                 ) {
393                                 // FIXME: I don't have a working copy of the Arabi package, so
394                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
395                                 // or not...
396                                 if (par_language->lang() == "farsi")
397                                         os << "\\textFR{";
398                                 else if (outer_language->lang() == "farsi")
399                                         os << "\\textLR{";
400                                 else if (par_language->lang() == "arabic_arabi")
401                                         os << "\\textAR{";
402                                 else if (outer_language->lang() == "arabic_arabi")
403                                         os << "\\textLR{";
404                                 // remaining RTL languages currently is hebrew
405                                 else if (par_language->rightToLeft())
406                                         os << "\\R{";
407                                 else
408                                         os << "\\L{";
409                         }
410                         // With CJK, the CJK tag has to be closed first (see below)
411                         if (runparams.encoding->package() != Encoding::CJK) {
412                                 os << from_ascii(subst(
413                                         lyxrc.language_command_begin,
414                                         "$$lang",
415                                         par_language->babel()))
416                                    // the '%' is necessary to prevent unwanted whitespace
417                                    << "%\n";
418                                 texrow.newline();
419                         }
420                 }
421         }
422
423         // Switch file encoding if necessary; no need to do this for "default"
424         // encoding, since this only affects the position of the outputted
425         // \inputencoding command; the encoding switch will occur when necessary
426         if (bparams.inputenc == "auto" &&
427             runparams.encoding->package() != Encoding::none) {
428                 // Look ahead for future encoding changes.
429                 // We try to output them at the beginning of the paragraph,
430                 // since the \inputencoding command is not allowed e.g. in
431                 // sections.
432                 for (pos_type i = 0; i < pit->size(); ++i) {
433                         char_type const c = pit->getChar(i);
434                         Encoding const * const encoding =
435                                 pit->getFontSettings(bparams, i).language()->encoding();
436                         if (encoding->package() != Encoding::CJK &&
437                             runparams.encoding->package() == Encoding::inputenc &&
438                             c < 0x80)
439                                 continue;
440                         if (pit->isInset(i))
441                                 break;
442                         // All characters before c are in the ASCII range, and
443                         // c is non-ASCII (but no inset), so change the
444                         // encoding to that required by the language of c.
445                         // With CJK, only add switch if we have CJK content at the beginning
446                         // of the paragraph
447                         if (encoding->package() != Encoding::CJK || i == 0) {
448                                 OutputParams tmp_rp = runparams;
449                                 runparams.moving_arg = false;
450                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
451                                         *encoding);
452                                 runparams = tmp_rp;
453                                 // the following is necessary after a CJK environment in a multilingual
454                                 // context (nesting issue).
455                                 if (par_language->encoding()->package() == Encoding::CJK &&
456                                     open_encoding_ != CJK && cjk_inherited_ == 0) {
457                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
458                                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
459                                         open_encoding_ = CJK;
460                                         texrow.newline();
461                                 }
462                                 if (encoding->package() != Encoding::none && enc_switch.first) {
463                                         if (enc_switch.second > 0) {
464                                                 // the '%' is necessary to prevent unwanted whitespace
465                                                 os << "%\n";
466                                                 texrow.newline();
467                                         }
468                                         // With CJK, the CJK tag had to be closed first (see above)
469                                         if (runparams.encoding->package() == Encoding::CJK) {
470                                                 os << from_ascii(subst(
471                                                         lyxrc.language_command_begin,
472                                                         "$$lang",
473                                                         par_language->babel()))
474                                                 // the '%' is necessary to prevent unwanted whitespace
475                                                 << "%\n";
476                                                 texrow.newline();
477                                         }
478                                         runparams.encoding = encoding;
479                                 }
480                                 break;
481                         }
482                 }
483         }
484
485         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
486         if (pit->allowParagraphCustomization()) {
487                 if (pit->params().startOfAppendix()) {
488                         os << "\\appendix\n";
489                         texrow.newline();
490                 }
491
492                 if (!pit->params().spacing().isDefault()
493                         && (pit == paragraphs.begin()
494                             || !priorpit->hasSameLayout(*pit)))
495                 {
496                         os << from_ascii(pit->params().spacing().writeEnvirBegin(useSetSpace))
497                             << '\n';
498                         texrow.newline();
499                 }
500
501                 if (style.isCommand()) {
502                         os << '\n';
503                         texrow.newline();
504                 }
505         }
506
507         switch (style.latextype) {
508         case LATEX_COMMAND:
509                 os << '\\' << from_ascii(style.latexname());
510
511                 // Separate handling of optional argument inset.
512                 if (style.optionalargs > 0) {
513                         int ret = latexOptArgInsets(*pit, os, runparams,
514                                                     style.optionalargs);
515                         while (ret > 0) {
516                                 texrow.newline();
517                                 --ret;
518                         }
519                 }
520                 else
521                         os << from_ascii(style.latexparam());
522                 break;
523         case LATEX_ITEM_ENVIRONMENT:
524         case LATEX_LIST_ENVIRONMENT:
525                 os << "\\item ";
526                 break;
527         case LATEX_BIB_ENVIRONMENT:
528                 // ignore this, the inset will write itself
529                 break;
530         default:
531                 break;
532         }
533
534         Font const outerfont = outerFont(distance(paragraphs.begin(), pit),
535                           paragraphs);
536
537         // FIXME UNICODE
538         os << from_utf8(everypar);
539         bool need_par = pit->latex(bparams, outerfont,
540                                              os, texrow, runparams);
541
542         // Make sure that \\par is done with the font of the last
543         // character if this has another size as the default.
544         // This is necessary because LaTeX (and LyX on the screen)
545         // calculates the space between the baselines according
546         // to this font. (Matthias)
547         //
548         // Is this really needed ? (Dekel)
549         // We do not need to use to change the font for the last paragraph
550         // or for a command.
551
552         Font const font = pit->empty()
553                  ? pit->getLayoutFont(bparams, outerfont)
554                  : pit->getFont(bparams, pit->size() - 1, outerfont);
555
556         bool is_command = style.isCommand();
557
558         if (style.resfont.size() != font.fontInfo().size()
559             && nextpit != paragraphs.end()
560             && !is_command) {
561                 if (!need_par)
562                         os << '{';
563                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
564         } else if (need_par) {
565                 os << "\\par}";
566         } else if (is_command)
567                 os << '}';
568
569         bool pending_newline = false;
570         switch (style.latextype) {
571         case LATEX_ITEM_ENVIRONMENT:
572         case LATEX_LIST_ENVIRONMENT:
573                 if (nextpit != paragraphs.end()
574                     && (pit->params().depth() < nextpit->params().depth()))
575                         pending_newline = true;
576                 break;
577         case LATEX_ENVIRONMENT: {
578                 // if its the last paragraph of the current environment
579                 // skip it otherwise fall through
580                 ParagraphList::const_iterator next = nextpit;
581
582                 if (next != paragraphs.end() && (next->layout() != pit->layout()
583                         || next->params().depth() != pit->params().depth()))
584                         break;
585         }
586
587                 // fall through possible
588         default:
589                 // we don't need it for the last paragraph!!!
590                 if (nextpit != paragraphs.end())
591                         pending_newline = true;
592         }
593
594         if (pit->allowParagraphCustomization()) {
595                 if (!pit->params().spacing().isDefault()
596                         && (nextpit == paragraphs.end() || !nextpit->hasSameLayout(*pit)))
597                 {
598                         if (pending_newline) {
599                                 os << '\n';
600                                 texrow.newline();
601                         }
602                         os << from_ascii(pit->params().spacing().writeEnvirEnd(useSetSpace));
603                         pending_newline = true;
604                 }
605         }
606
607         // Closing the language is needed for the last paragraph; it is also
608         // needed if we're within an \L or \R that we may have opened above (not
609         // necessarily in this paragraph) and are about to close.
610         bool closing_rtl_ltr_environment =
611                 // not for ArabTeX
612                 (par_language->lang() != "arabic_arabtex" &&
613                  outer_language->lang() != "arabic_arabtex") &&
614                 // have we opened and \L or \R environment?
615                 runparams.local_font != 0 &&
616                 runparams.local_font->isRightToLeft() != par_language->rightToLeft() &&
617                 // are we about to close the language?
618                 ((nextpit != paragraphs.end() &&
619                   par_language->babel() !=
620                         (nextpit->getParLanguage(bparams))->babel()) ||
621                  (nextpit == paragraphs.end() &&
622                   par_language->babel() != outer_language->babel()));
623
624         if (closing_rtl_ltr_environment || (nextpit == paragraphs.end()
625             && par_language->babel() != outer_language->babel())) {
626                 // Since \selectlanguage write the language to the aux file,
627                 // we need to reset the language at the end of footnote or
628                 // float.
629
630                 if (pending_newline) {
631                         os << '\n';
632                         texrow.newline();
633                 }
634                 // when the paragraph uses CJK, the language has to be closed earlier
635                 if (font.language()->encoding()->package() != Encoding::CJK) {
636                         if (lyxrc.language_command_end.empty()) {
637                                 if (!prev_language->babel().empty()) {
638                                         os << from_ascii(subst(
639                                                 lyxrc.language_command_begin,
640                                                 "$$lang",
641                                                 prev_language->babel()));
642                                         pending_newline = true;
643                                 }
644                         } else if (!par_language->babel().empty()) {
645                                 os << from_ascii(subst(
646                                         lyxrc.language_command_end,
647                                         "$$lang",
648                                         par_language->babel()));
649                                 pending_newline = true;
650                         }
651                 }
652         }
653         if (closing_rtl_ltr_environment)
654                 os << "}";
655
656         if (pending_newline) {
657                 os << '\n';
658                 texrow.newline();
659         }
660
661         // if this is a CJK-paragraph and the next isn't, close CJK
662         // also if the next paragraph is a multilingual environment (because of nesting)
663         if (nextpit != paragraphs.end() && open_encoding_ == CJK &&
664             (nextpit->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
665              nextpit->layout().isEnvironment() && nextpit->isMultiLingual(bparams))
666              // in environments, CJK has to be closed later (nesting!)
667              && !style.isEnvironment()) {
668                 os << "\\end{CJK}\n";
669                 open_encoding_ = none;
670         }
671
672         // If this is the last paragraph, close the CJK environment
673         // if necessary. If it's an environment, we'll have to \end that first.
674         if (nextpit == paragraphs.end() && !style.isEnvironment()) {
675                 switch (open_encoding_) {
676                         case CJK: {
677                                 // end of main text
678                                 if (maintext) {
679                                         os << '\n';
680                                         texrow.newline();
681                                         os << "\\end{CJK}\n";
682                                         texrow.newline();
683                                 // end of an inset
684                                 } else
685                                         os << "\\end{CJK}";
686                                 open_encoding_ = none;
687                                 break;
688                         }
689                         case inputenc: {
690                                 os << "\\egroup";
691                                 open_encoding_ = none;
692                                 break;
693                         }
694                         case none:
695                         default:
696                                 // do nothing
697                                 break;
698                 }
699         }
700
701         // If this is the last paragraph, and a local_font was set upon entering
702         // the inset, and we're using "auto" or "default" encoding, the encoding
703         // should be set back to that local_font's encoding.
704         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
705             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
706             && (bparams.inputenc == "auto" || bparams.inputenc == "default")) {
707                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
708                 os << setEncoding(runparams_in.encoding->iconvName());
709         }
710         // Otherwise, the current encoding should be set for the next paragraph.
711         else
712                 runparams_in.encoding = runparams.encoding;
713
714
715         // we don't need it for the last paragraph!!!
716         // Note from JMarc: we will re-add a \n explicitely in
717         // TeXEnvironment, because it is needed in this case
718         if (nextpit != paragraphs.end()) {
719                 Layout const & next_layout = nextpit->layout();
720                 // no blank lines before environments!
721                 if (!next_layout.isEnvironment() || style == next_layout) {
722                         os << '\n';
723                         texrow.newline();
724                 }
725         }
726
727         if (nextpit != paragraphs.end())
728                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
729
730         return nextpit;
731 }
732
733 } // anon namespace
734
735
736 // LaTeX all paragraphs
737 void latexParagraphs(Buffer const & buf,
738                      Text const & text,
739                      odocstream & os,
740                      TexRow & texrow,
741                      OutputParams const & runparams,
742                      string const & everypar)
743 {
744         bool was_title = false;
745         bool already_title = false;
746         BufferParams const & bparams = buf.params();
747         DocumentClass const & tclass = bparams.documentClass();
748         ParagraphList const & paragraphs = text.paragraphs();
749         ParagraphList::const_iterator par = paragraphs.begin();
750         ParagraphList::const_iterator endpar = paragraphs.end();
751
752         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
753         // if only part of the paragraphs will be outputed
754         if (runparams.par_begin !=  runparams.par_end) {
755                 par = boost::next(paragraphs.begin(), runparams.par_begin);
756                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
757                 // runparams will be passed to nested paragraphs, so
758                 // we have to reset the range parameters.
759                 const_cast<OutputParams&>(runparams).par_begin = 0;
760                 const_cast<OutputParams&>(runparams).par_end = 0;
761         }
762
763         bool const maintext = text.isMainText(buf);
764
765         // Open a CJK environment at the beginning of the main buffer
766         // if the document's language is a CJK language
767         if (maintext && bparams.encoding().package() == Encoding::CJK) {
768                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
769                 << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
770                 texrow.newline();
771                 open_encoding_ = CJK;
772         }
773         // if "auto begin" is switched off, explicitely switch the
774         // language on at start
775         if (maintext && !lyxrc.language_auto_begin &&
776             !bparams.language->babel().empty()) {
777                 // FIXME UNICODE
778                 os << from_utf8(subst(lyxrc.language_command_begin,
779                                         "$$lang",
780                                         bparams.language->babel()))
781                         << '\n';
782         texrow.newline();
783         }
784
785         ParagraphList::const_iterator lastpar;
786         // if only_body
787         while (par != endpar) {
788                 lastpar = par;
789                 Layout const & layout = par->forcePlainLayout() ?
790                                 tclass.plainLayout() :
791                                 par->layout();
792
793                 if (layout.intitle) {
794                         if (already_title) {
795                                 lyxerr << "Error in latexParagraphs: You"
796                                         " should not mix title layouts"
797                                         " with normal ones." << endl;
798                         } else if (!was_title) {
799                                 was_title = true;
800                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
801                                         os << "\\begin{"
802                                                         << from_ascii(tclass.titlename())
803                                                         << "}\n";
804                                         texrow.newline();
805                                 }
806                         }
807                 } else if (was_title && !already_title) {
808                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
809                                 os << "\\end{" << from_ascii(tclass.titlename())
810                                                 << "}\n";
811                         }
812                         else {
813                                 os << "\\" << from_ascii(tclass.titlename())
814                                                 << "\n";
815                         }
816                         texrow.newline();
817                         already_title = true;
818                         was_title = false;
819                 }
820
821                 if (layout.isEnvironment() ||
822                                         !par->params().leftIndent().zero()) {
823                         par = TeXEnvironment(buf, text, par, os,
824                                                                 texrow, runparams);
825                 } else {
826                         par = TeXOnePar(buf, text, par, os, texrow,
827                                         runparams, everypar);
828                 }
829                 if (distance(lastpar, par) >= distance(lastpar, endpar))
830                         break;
831         }
832
833         // It might be that we only have a title in this document
834         if (was_title && !already_title) {
835                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
836                         os << "\\end{" << from_ascii(tclass.titlename())
837                             << "}\n";
838                 }
839                 else {
840                         os << "\\" << from_ascii(tclass.titlename())
841                             << "\n";
842                                 }
843                 texrow.newline();
844         }
845
846         // if "auto end" is switched off, explicitely close the language at the end
847         // but only if the last par is in a babel language
848         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
849                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
850                 os << from_utf8(subst(lyxrc.language_command_end,
851                                         "$$lang",
852                                         bparams.language->babel()))
853                         << '\n';
854                 texrow.newline();
855         }
856
857         // If the last paragraph is an environment, we'll have to close
858         // CJK at the very end to do proper nesting.
859         if (maintext && open_encoding_ == CJK) {
860                 os << "\\end{CJK}\n";
861                 texrow.newline();
862                 open_encoding_ = none;
863         }
864
865         // reset inherited encoding
866         if (cjk_inherited_ > 0) {
867                 cjk_inherited_ -= 1;
868                 if (cjk_inherited_ == 0)
869                         open_encoding_ = CJK;
870         }
871 }
872
873
874 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
875                    OutputParams const & runparams, Encoding const & newEnc,
876                    bool force)
877 {
878         Encoding const & oldEnc = *runparams.encoding;
879         bool moving_arg = runparams.moving_arg;
880         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
881                 || moving_arg))
882                 return make_pair(false, 0);
883
884         // Do nothing if the encoding is unchanged.
885         if (oldEnc.name() == newEnc.name())
886                 return make_pair(false, 0);
887
888         // FIXME We ignore encoding switches from/to encodings that do
889         // neither support the inputenc package nor the CJK package here.
890         // This does of course only work in special cases (e.g. switch from
891         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
892         // but it is the best we can do
893         if (oldEnc.package() == Encoding::none
894                 || newEnc.package() == Encoding::none)
895                 return make_pair(false, 0);
896
897         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
898                 << oldEnc.name() << " to " << newEnc.name());
899         os << setEncoding(newEnc.iconvName());
900         if (bparams.inputenc == "default")
901                 return make_pair(true, 0);
902
903         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
904         switch (newEnc.package()) {
905                 case Encoding::none:
906                 case Encoding::japanese:
907                         // shouldn't ever reach here, see above
908                         return make_pair(true, 0);
909                 case Encoding::inputenc: {
910                         int count = inputenc_arg.length();
911                         if (oldEnc.package() == Encoding::CJK &&
912                             open_encoding_ == CJK) {
913                                 os << "\\end{CJK}";
914                                 open_encoding_ = none;
915                                 count += 9;
916                         }
917                         else if (oldEnc.package() == Encoding::inputenc &&
918                                  open_encoding_ == inputenc) {
919                                 os << "\\egroup";
920                                 open_encoding_ = none;
921                                 count += 7;
922                         }
923                         if (runparams.local_font != 0
924                             && oldEnc.package() == Encoding::CJK) {
925                                 // within insets, \inputenc switches need
926                                 // to be embraced within \bgroup...\egroup;
927                                 // else CJK fails.
928                                 os << "\\bgroup";
929                                 count += 7;
930                                 open_encoding_ = inputenc;
931                         }
932                         // with the japanese option, inputenc is omitted.
933                         if (runparams.use_japanese)
934                                 return make_pair(true, count);
935                         os << "\\inputencoding{" << inputenc_arg << '}';
936                         return make_pair(true, count + 16);
937                 }
938                 case Encoding::CJK: {
939                         int count = inputenc_arg.length();
940                         if (oldEnc.package() == Encoding::CJK &&
941                             open_encoding_ == CJK) {
942                                 os << "\\end{CJK}";
943                                 count += 9;
944                         }
945                         if (oldEnc.package() == Encoding::inputenc &&
946                             open_encoding_ == inputenc) {
947                                 os << "\\egroup";
948                                 count += 7;
949                         }
950                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
951                            << from_ascii(bparams.fontsCJK) << "}";
952                         open_encoding_ = CJK;
953                         return make_pair(true, count + 15);
954                 }
955         }
956         // Dead code to avoid a warning:
957         return make_pair(true, 0);
958
959 }
960
961 } // namespace lyx