]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
ea4418fe0a5ad7e7e79746d084fba11c904dc03e
[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/debug.h"
34 #include "support/lstrings.h"
35
36 #include <boost/next_prior.hpp>
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42
43 namespace {
44
45
46 enum OpenEncoding {
47                 none,
48                 inputenc,
49                 CJK
50 };
51
52 static int open_encoding_ = none;
53 static bool cjk_inherited_ = false;
54
55
56 ParagraphList::const_iterator
57 TeXEnvironment(Buffer const & buf,
58                Text const & text,
59                ParagraphList::const_iterator pit,
60                odocstream & os, TexRow & texrow,
61                OutputParams const & runparams);
62
63 ParagraphList::const_iterator
64 TeXOnePar(Buffer const & buf,
65           Text const & text,
66           ParagraphList::const_iterator pit,
67           odocstream & os, TexRow & texrow,
68           OutputParams const & runparams,
69           string const & everypar = string());
70
71
72 ParagraphList::const_iterator
73 TeXDeeper(Buffer const & buf,
74           Text const & text,
75           ParagraphList::const_iterator pit,
76           odocstream & os, TexRow & texrow,
77           OutputParams const & runparams)
78 {
79         LYXERR(Debug::LATEX, "TeXDeeper...     " << &*pit);
80         ParagraphList::const_iterator par = pit;
81
82         ParagraphList const & paragraphs = text.paragraphs();
83
84         while (par != paragraphs.end() &&
85                      par->params().depth() == pit->params().depth()) {
86                 if (par->layout().isEnvironment()) {
87                         par = TeXEnvironment(buf, text, par,
88                                              os, texrow, runparams);
89                 } else {
90                         par = TeXOnePar(buf, text, par,
91                                              os, texrow, runparams);
92                 }
93         }
94         LYXERR(Debug::LATEX, "TeXDeeper...done ");
95
96         return par;
97 }
98
99
100 ParagraphList::const_iterator
101 TeXEnvironment(Buffer const & buf,
102                Text const & text,
103                ParagraphList::const_iterator pit,
104                odocstream & os, TexRow & texrow,
105                OutputParams const & runparams)
106 {
107         LYXERR(Debug::LATEX, "TeXEnvironment...     " << &*pit);
108
109         BufferParams const & bparams = buf.params();
110
111         Layout const & style = pit->forceEmptyLayout() ?
112                 bparams.documentClass().emptyLayout() : pit->layout();
113
114         ParagraphList const & paragraphs = text.paragraphs();
115
116         Language const * const par_language = pit->getParLanguage(bparams);
117         Language const * const doc_language = bparams.language;
118         Language const * const prev_par_language =
119                 (pit != paragraphs.begin())
120                 ? boost::prior(pit)->getParLanguage(bparams)
121                 : doc_language;
122         if (par_language->babel() != prev_par_language->babel()) {
123
124                 if (!lyxrc.language_command_end.empty() &&
125                     prev_par_language->babel() != doc_language->babel() &&
126                     !prev_par_language->babel().empty()) {
127                         os << from_ascii(subst(
128                                 lyxrc.language_command_end,
129                                 "$$lang",
130                                 prev_par_language->babel()))
131                            // the '%' is necessary to prevent unwanted whitespace
132                            << "%\n";
133                         texrow.newline();
134                 }
135
136                 if ((lyxrc.language_command_end.empty() ||
137                      par_language->babel() != doc_language->babel()) &&
138                     !par_language->babel().empty()) {
139                         os << from_ascii(subst(
140                                 lyxrc.language_command_begin,
141                                 "$$lang",
142                                 par_language->babel()))
143                            // the '%' is necessary to prevent unwanted whitespace
144                            << "%\n";
145                         texrow.newline();
146                 }
147         }
148
149         bool leftindent_open = false;
150         if (!pit->params().leftIndent().zero()) {
151                 os << "\\begin{LyXParagraphLeftIndent}{"
152                    << from_ascii(pit->params().leftIndent().asLatexString())
153                    << "}\n";
154                 texrow.newline();
155                 leftindent_open = true;
156         }
157
158         if (style.isEnvironment()) {
159                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
160                 if (style.optionalargs > 0) {
161                         int ret = latexOptArgInsets(*pit, os, runparams,
162                                                     style.optionalargs);
163                         while (ret > 0) {
164                                 texrow.newline();
165                                 --ret;
166                         }
167                 }
168                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
169                         os << '{'
170                            << pit->params().labelWidthString()
171                            << "}\n";
172                 } else if (style.labeltype == LABEL_BIBLIO) {
173                         // ale970405
174                         os << '{' << bibitemWidest(buf) << "}\n";
175                 } else
176                         os << from_ascii(style.latexparam()) << '\n';
177                 texrow.newline();
178         }
179
180         // in multilingual environments, the CJK tags have to be nested properly
181         bool cjk_nested = false;
182         if (par_language->encoding()->package() == Encoding::CJK &&
183             open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
184                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
185                    << "}{}%\n";
186                 open_encoding_ = CJK;
187                 cjk_nested = true;
188                 texrow.newline();
189         }
190
191         ParagraphList::const_iterator par = pit;
192         do {
193                 par = TeXOnePar(buf, text, par, os, texrow, runparams);
194
195                 if (par == paragraphs.end()) {
196                         // Make sure that the last paragraph is
197                         // correctly terminated (because TeXOnePar does
198                         // not add a \n in this case)
199                         os << '\n';
200                         texrow.newline();
201                 } else if (par->params().depth() > pit->params().depth()) {
202                         if (par->layout().isParagraph()) {
203                           // Thinko!
204                           // How to handle this? (Lgb)
205                           //&& !suffixIs(os, "\n\n")
206
207                                 // There should be at least one '\n' already
208                                 // but we need there to be two for Standard
209                                 // paragraphs that are depth-increment'ed to be
210                                 // output correctly.  However, tables can
211                                 // also be paragraphs so don't adjust them.
212                                 // ARRae
213                                 // Thinkee:
214                                 // Will it ever harm to have one '\n' too
215                                 // many? i.e. that we sometimes will have
216                                 // three in a row. (Lgb)
217                                 os << '\n';
218                                 texrow.newline();
219                         }
220                         par = TeXDeeper(buf, text, par, os, texrow,
221                                         runparams);
222                 }
223         } while (par != paragraphs.end()
224                  && par->layout() == pit->layout()
225                  && par->params().depth() == pit->params().depth()
226                  && par->params().leftIndent() == pit->params().leftIndent());
227
228         if (open_encoding_ == CJK && cjk_nested) {
229                 // We need to close the encoding even if it does not change
230                 // to do correct environment nesting
231                 os << "\\end{CJK}\n";
232                 texrow.newline();
233                 open_encoding_ = none;
234         }
235
236         if (style.isEnvironment()) {
237                 os << "\\end{" << from_ascii(style.latexname()) << "}\n";
238                 texrow.newline();
239         }
240
241         if (leftindent_open) {
242                 os << "\\end{LyXParagraphLeftIndent}\n";
243                 texrow.newline();
244         }
245
246         if (par != paragraphs.end())
247                 LYXERR(Debug::LATEX, "TeXEnvironment...done " << &*par);
248
249         return par;
250 }
251
252 } // namespace anon
253
254
255 int latexOptArgInsets(Paragraph const & par, odocstream & os,
256         OutputParams const & runparams, int number)
257 {
258         int lines = 0;
259
260         InsetList::const_iterator it = par.insetList().begin();
261         InsetList::const_iterator end = par.insetList().end();
262         for (; it != end && number > 0 ; ++it) {
263                 if (it->inset->lyxCode() == OPTARG_CODE) {
264                         InsetOptArg * ins =
265                                 static_cast<InsetOptArg *>(it->inset);
266                         lines += ins->latexOptional(os, runparams);
267                         --number;
268                 }
269         }
270         return lines;
271 }
272
273
274 namespace {
275
276 ParagraphList::const_iterator
277 TeXOnePar(Buffer const & buf,
278           Text const & text,
279           ParagraphList::const_iterator const pit,
280           odocstream & os, TexRow & texrow,
281           OutputParams const & runparams_in,
282           string const & everypar)
283 {
284         LYXERR(Debug::LATEX, "TeXOnePar...     " << &*pit << " '"
285                 << everypar << "'");
286         BufferParams const & bparams = buf.params();
287         ParagraphList const & paragraphs = text.paragraphs();
288
289         ParagraphList::const_iterator priorpit = pit;
290         if (priorpit != paragraphs.begin())
291                 --priorpit;
292         ParagraphList::const_iterator nextpit = pit;
293         if (nextpit != paragraphs.end())
294                 ++nextpit;
295
296         if (runparams_in.verbatim) {
297                 int const dist = distance(paragraphs.begin(), pit);
298                 Font const outerfont = outerFont(dist, paragraphs);
299
300                 // No newline if only one paragraph in this lyxtext
301                 if (dist > 0) {
302                         os << '\n';
303                         texrow.newline();
304                 }
305
306                 /*bool need_par = */ pit->latex(bparams, outerfont,
307                         os, texrow, runparams_in);
308                 return nextpit;
309         }
310
311         // FIXME This comment doesn't make sense. What's the
312         // length got to do with forceEmptyLayout()? I.e., what
313         // was forceDefaultParagraphs()?
314         // In an inset with unlimited length (all in one row),
315         // force layout to default
316         Layout const style = pit->forceEmptyLayout() ?
317                 bparams.documentClass().emptyLayout() : pit->layout();
318
319         OutputParams runparams = runparams_in;
320         runparams.moving_arg |= style.needprotect;
321
322         bool const maintext = text.isMainText(buf);
323         // we are at the beginning of an inset and CJK is already open.
324         if (pit == paragraphs.begin() && !maintext && open_encoding_ == CJK) {
325                 cjk_inherited_ = true;
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_) {
457                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
458                                            << "}{}%\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, the encoding should be set back to that local_font's 
703         // encoding. We don't use switchEncoding(), because no explicit encoding
704         // switch command is needed, since latex will automatically revert to it
705         // when this inset closes.
706         // This switch is only necessary if we're using "auto" or "default" 
707         // encoding. 
708         if (nextpit == paragraphs.end() && runparams_in.local_font != 0) {
709                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
710                 if (bparams.inputenc == "auto" || bparams.inputenc == "default")
711                         os << setEncoding(runparams_in.encoding->iconvName());
712
713         }
714         // Otherwise, the current encoding should be set for the next paragraph.
715         else
716                 runparams_in.encoding = runparams.encoding;
717
718
719         // we don't need it for the last paragraph!!!
720         // Note from JMarc: we will re-add a \n explicitely in
721         // TeXEnvironment, because it is needed in this case
722         if (nextpit != paragraphs.end()) {
723                 os << '\n';
724                 texrow.newline();
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         BOOST_ASSERT(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                 << "}{}%\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                 // well we have to check if we are in an inset with unlimited
790                 // length (all in one row) if that is true then we don't allow
791                 // any special options in the paragraph and also we don't allow
792                 // any environment other than the default layout of the
793                 // text class to be valid!
794                 if (par->allowParagraphCustomization()) {
795                         Layout const & layout = par->forceEmptyLayout() ?
796                                         tclass.emptyLayout() :
797                                         par->layout();
798
799                         if (layout.intitle) {
800                                 if (already_title) {
801                                         lyxerr << "Error in latexParagraphs: You"
802                                                 " should not mix title layouts"
803                                                 " with normal ones." << endl;
804                                 } else if (!was_title) {
805                                         was_title = true;
806                                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
807                                                 os << "\\begin{"
808                                                     << from_ascii(tclass.titlename())
809                                                     << "}\n";
810                                                 texrow.newline();
811                                         }
812                                 }
813                         } else if (was_title && !already_title) {
814                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
815                                         os << "\\end{" << from_ascii(tclass.titlename())
816                                             << "}\n";
817                                 }
818                                 else {
819                                         os << "\\" << from_ascii(tclass.titlename())
820                                             << "\n";
821                                 }
822                                 texrow.newline();
823                                 already_title = true;
824                                 was_title = false;
825                         }
826
827                         if (layout.is_environment) {
828                                 par = TeXOnePar(buf, text, par, os, texrow,
829                                                 runparams, everypar);
830                         } else if (layout.isEnvironment() ||
831                                    !par->params().leftIndent().zero()) {
832                                 par = TeXEnvironment(buf, text, par, os,
833                                                      texrow, runparams);
834                         } else {
835                                 par = TeXOnePar(buf, text, par, os, texrow,
836                                                 runparams, everypar);
837                         }
838                 } else {
839                         par = TeXOnePar(buf, text, par, os, texrow,
840                                         runparams, everypar);
841                 }
842                 if (distance(lastpar, par) >= distance(lastpar, endpar))
843                         break;
844         }
845         // It might be that we only have a title in this document
846         if (was_title && !already_title) {
847                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
848                         os << "\\end{" << from_ascii(tclass.titlename())
849                             << "}\n";
850                 }
851                 else {
852                         os << "\\" << from_ascii(tclass.titlename())
853                             << "\n";
854                                 }
855                 texrow.newline();
856         }
857         // if "auto end" is switched off, explicitely close the language at the end
858         // but only if the last par is in a babel language
859         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
860                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
861                 os << from_utf8(subst(lyxrc.language_command_end,
862                                         "$$lang",
863                                         bparams.language->babel()))
864                         << '\n';
865                 texrow.newline();
866         }
867         // If the last paragraph is an environment, we'll have to close
868         // CJK at the very end to do proper nesting.
869         if (maintext && open_encoding_ == CJK) {
870                 os << "\\end{CJK}\n";
871                 texrow.newline();
872                 open_encoding_ = none;
873         }
874         // reset inherited encoding
875         if (cjk_inherited_) {
876                 open_encoding_ = CJK;
877                 cjk_inherited_ = false;
878         }
879 }
880
881
882 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
883                    OutputParams const & runparams, Encoding const & newEnc)
884 {
885         Encoding const oldEnc = *runparams.encoding;
886         bool moving_arg = runparams.moving_arg;
887         if ((bparams.inputenc != "auto" && bparams.inputenc != "default")
888                 || moving_arg)
889                 return make_pair(false, 0);
890
891         // Do nothing if the encoding is unchanged.
892         if (oldEnc.name() == newEnc.name())
893                 return make_pair(false, 0);
894
895         // FIXME We ignore encoding switches from/to encodings that do
896         // neither support the inputenc package nor the CJK package here.
897         // This does of course only work in special cases (e.g. switch from
898         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
899         // but it is the best we can do
900         if (oldEnc.package() == Encoding::none
901                 || newEnc.package() == Encoding::none)
902                 return make_pair(false, 0);
903
904         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
905                 << oldEnc.name() << " to " << newEnc.name());
906         os << setEncoding(newEnc.iconvName());
907         if (bparams.inputenc == "default")
908                 return make_pair(true, 0);
909
910         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
911         switch (newEnc.package()) {
912                 case Encoding::none:
913                         // shouldn't ever reach here, see above
914                         return make_pair(true, 0);
915                 case Encoding::inputenc: {
916                         int count = inputenc_arg.length();
917                         if (oldEnc.package() == Encoding::CJK &&
918                             open_encoding_ == CJK) {
919                                 os << "\\end{CJK}";
920                                 open_encoding_ = none;
921                                 count += 9;
922                         }
923                         else if (oldEnc.package() == Encoding::inputenc &&
924                                  open_encoding_ == inputenc) {
925                                 os << "\\egroup";
926                                 open_encoding_ = none;
927                                 count += 7;
928                         }
929                         if (runparams.local_font != 0 && oldEnc.package() == Encoding::CJK) {
930                                 // within insets, \inputenc switches need to be 
931                                 // embraced within \bgroup ... \egroup; else CJK fails.
932                                 os << "\\bgroup";
933                                 count += 7;
934                                 open_encoding_ = inputenc;
935                         }
936                         os << "\\inputencoding{" << inputenc_arg << '}';
937                         return make_pair(true, count + 16);
938                 }
939                 case Encoding::CJK: {
940                         int count = inputenc_arg.length();
941                         if (oldEnc.package() == Encoding::CJK && 
942                             open_encoding_ == CJK) {
943                                 os << "\\end{CJK}";
944                                 count += 9;
945                         }
946                         if (oldEnc.package() == Encoding::inputenc && 
947                             open_encoding_ == inputenc) {
948                                 os << "\\egroup";
949                                 count += 7;
950                         }
951                         os << "\\begin{CJK}{" << inputenc_arg << "}{}";
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