]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
infrastructure for 'graceful asserts'
[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/assert.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 bool cjk_inherited_ = false;
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->forceEmptyLayout() ?
113                 bparams.documentClass().emptyLayout() : 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                    << "}{}%\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         if (runparams_in.verbatim) {
298                 int const dist = distance(paragraphs.begin(), pit);
299                 Font const outerfont = outerFont(dist, paragraphs);
300
301                 // No newline if only one paragraph in this lyxtext
302                 if (dist > 0) {
303                         os << '\n';
304                         texrow.newline();
305                 }
306
307                 /*bool need_par = */ pit->latex(bparams, outerfont,
308                         os, texrow, runparams_in);
309                 return nextpit;
310         }
311
312         // FIXME This comment doesn't make sense. What's the
313         // length got to do with forceEmptyLayout()? I.e., what
314         // was forceDefaultParagraphs()?
315         // In an inset with unlimited length (all in one row),
316         // force layout to default
317         Layout const style = pit->forceEmptyLayout() ?
318                 bparams.documentClass().emptyLayout() : pit->layout();
319
320         OutputParams runparams = runparams_in;
321         runparams.moving_arg |= style.needprotect;
322
323         bool const maintext = text.isMainText(buf);
324         // we are at the beginning of an inset and CJK is already open.
325         if (pit == paragraphs.begin() && !maintext && open_encoding_ == CJK) {
326                 cjk_inherited_ = true;
327                 open_encoding_ = none;
328         }
329
330         // This paragraph's language
331         Language const * const par_language = pit->getParLanguage(bparams);
332         // The document's language
333         Language const * const doc_language = bparams.language;
334         // The language that was in effect when the environment this paragraph is 
335         // inside of was opened
336         Language const * const outer_language = 
337                 (runparams.local_font != 0) ?
338                         runparams.local_font->language() : doc_language;
339         // The previous language that was in effect is either the language of
340         // the previous paragraph, if there is one, or else the outer language
341         // if there is no previous paragraph
342         Language const * const prev_language =
343                 (pit != paragraphs.begin()) ?
344                         priorpit->getParLanguage(bparams) : outer_language;
345
346         if (par_language->babel() != prev_language->babel()
347             // check if we already put language command in TeXEnvironment()
348             && !(style.isEnvironment()
349                  && (pit == paragraphs.begin() ||
350                      (priorpit->layout() != pit->layout() &&
351                       priorpit->getDepth() <= pit->getDepth())
352                      || priorpit->getDepth() < pit->getDepth())))
353         {
354                 if (!lyxrc.language_command_end.empty() &&
355                     prev_language->babel() != outer_language->babel() &&
356                     !prev_language->babel().empty())
357                 {
358                         os << from_ascii(subst(lyxrc.language_command_end,
359                                 "$$lang",
360                                 prev_language->babel()))
361                            // the '%' is necessary to prevent unwanted whitespace
362                            << "%\n";
363                         texrow.newline();
364                 }
365
366                 // We need to open a new language if we couldn't close the previous 
367                 // one (because there's no language_command_end); and even if we closed
368                 // the previous one, if the current language is different than the
369                 // outer_language (which is currently in effect once the previous one
370                 // is closed).
371                 if ((lyxrc.language_command_end.empty() ||
372                      par_language->babel() != outer_language->babel()) &&
373                     !par_language->babel().empty()) {
374                         // If we're inside an inset, and that inset is within an \L or \R
375                         // (or equivalents), then within the inset, too, any opposite
376                         // language paragraph should appear within an \L or \R (in addition
377                         // to, outside of, the normal language switch commands).
378                         // This behavior is not correct for ArabTeX, though.
379                         if (    // not for ArabTeX
380                                         (par_language->lang() != "arabic_arabtex" &&
381                                          outer_language->lang() != "arabic_arabtex") &&
382                                         // are we in an inset?
383                                         runparams.local_font != 0 &&
384                                         // is the inset within an \L or \R?
385                                         // 
386                                         // FIXME: currently, we don't check this; this means that
387                                         // we'll have unnnecessary \L and \R commands, but that 
388                                         // doesn't seem to hurt (though latex will complain)
389                                         // 
390                                         // is this paragraph in the opposite direction?
391                                         runparams.local_font->isRightToLeft() !=
392                                                 par_language->rightToLeft()
393                                 ) {
394                                 // FIXME: I don't have a working copy of the Arabi package, so
395                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
396                                 // or not...
397                                 if (par_language->lang() == "farsi")
398                                         os << "\\textFR{";
399                                 else if (outer_language->lang() == "farsi")
400                                         os << "\\textLR{";
401                                 else if (par_language->lang() == "arabic_arabi")
402                                         os << "\\textAR{";
403                                 else if (outer_language->lang() == "arabic_arabi")
404                                         os << "\\textLR{";
405                                 // remaining RTL languages currently is hebrew
406                                 else if (par_language->rightToLeft())
407                                         os << "\\R{";
408                                 else
409                                         os << "\\L{";
410                         }
411                         // With CJK, the CJK tag has to be closed first (see below)
412                         if (runparams.encoding->package() != Encoding::CJK) {
413                                 os << from_ascii(subst(
414                                         lyxrc.language_command_begin,
415                                         "$$lang",
416                                         par_language->babel()))
417                                    // the '%' is necessary to prevent unwanted whitespace
418                                    << "%\n";
419                                 texrow.newline();
420                         }
421                 }
422         }
423
424         // Switch file encoding if necessary; no need to do this for "default"
425         // encoding, since this only affects the position of the outputted
426         // \inputencoding command; the encoding switch will occur when necessary
427         if (bparams.inputenc == "auto" &&
428             runparams.encoding->package() != Encoding::none) {
429                 // Look ahead for future encoding changes.
430                 // We try to output them at the beginning of the paragraph,
431                 // since the \inputencoding command is not allowed e.g. in
432                 // sections.
433                 for (pos_type i = 0; i < pit->size(); ++i) {
434                         char_type const c = pit->getChar(i);
435                         Encoding const * const encoding =
436                                 pit->getFontSettings(bparams, i).language()->encoding();
437                         if (encoding->package() != Encoding::CJK &&
438                             runparams.encoding->package() == Encoding::inputenc &&
439                             c < 0x80)
440                                 continue;
441                         if (pit->isInset(i))
442                                 break;
443                         // All characters before c are in the ASCII range, and
444                         // c is non-ASCII (but no inset), so change the
445                         // encoding to that required by the language of c.
446                         // With CJK, only add switch if we have CJK content at the beginning
447                         // of the paragraph
448                         if (encoding->package() != Encoding::CJK || i == 0) {
449                                 OutputParams tmp_rp = runparams;
450                                 runparams.moving_arg = false;
451                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
452                                         *encoding);
453                                 runparams = tmp_rp;
454                                 // the following is necessary after a CJK environment in a multilingual
455                                 // context (nesting issue).
456                                 if (par_language->encoding()->package() == Encoding::CJK &&
457                                     open_encoding_ != CJK && !cjk_inherited_) {
458                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
459                                            << "}{}%\n";
460                                         open_encoding_ = CJK;
461                                         texrow.newline();
462                                 }
463                                 if (encoding->package() != Encoding::none && enc_switch.first) {
464                                         if (enc_switch.second > 0) {
465                                                 // the '%' is necessary to prevent unwanted whitespace
466                                                 os << "%\n";
467                                                 texrow.newline();
468                                         }
469                                         // With CJK, the CJK tag had to be closed first (see above)
470                                         if (runparams.encoding->package() == Encoding::CJK) {
471                                                 os << from_ascii(subst(
472                                                         lyxrc.language_command_begin,
473                                                         "$$lang",
474                                                         par_language->babel()))
475                                                 // the '%' is necessary to prevent unwanted whitespace
476                                                 << "%\n";
477                                                 texrow.newline();
478                                         }
479                                         runparams.encoding = encoding;
480                                 }
481                                 break;
482                         }
483                 }
484         }
485
486         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
487         if (pit->allowParagraphCustomization()) {
488                 if (pit->params().startOfAppendix()) {
489                         os << "\\appendix\n";
490                         texrow.newline();
491                 }
492
493                 if (!pit->params().spacing().isDefault()
494                         && (pit == paragraphs.begin()
495                             || !priorpit->hasSameLayout(*pit)))
496                 {
497                         os << from_ascii(pit->params().spacing().writeEnvirBegin(useSetSpace))
498                             << '\n';
499                         texrow.newline();
500                 }
501
502                 if (style.isCommand()) {
503                         os << '\n';
504                         texrow.newline();
505                 }
506         }
507
508         switch (style.latextype) {
509         case LATEX_COMMAND:
510                 os << '\\' << from_ascii(style.latexname());
511
512                 // Separate handling of optional argument inset.
513                 if (style.optionalargs > 0) {
514                         int ret = latexOptArgInsets(*pit, os, runparams,
515                                                     style.optionalargs);
516                         while (ret > 0) {
517                                 texrow.newline();
518                                 --ret;
519                         }
520                 }
521                 else
522                         os << from_ascii(style.latexparam());
523                 break;
524         case LATEX_ITEM_ENVIRONMENT:
525         case LATEX_LIST_ENVIRONMENT:
526                 os << "\\item ";
527                 break;
528         case LATEX_BIB_ENVIRONMENT:
529                 // ignore this, the inset will write itself
530                 break;
531         default:
532                 break;
533         }
534
535         Font const outerfont = outerFont(distance(paragraphs.begin(), pit),
536                           paragraphs);
537
538         // FIXME UNICODE
539         os << from_utf8(everypar);
540         bool need_par = pit->latex(bparams, outerfont,
541                                              os, texrow, runparams);
542
543         // Make sure that \\par is done with the font of the last
544         // character if this has another size as the default.
545         // This is necessary because LaTeX (and LyX on the screen)
546         // calculates the space between the baselines according
547         // to this font. (Matthias)
548         //
549         // Is this really needed ? (Dekel)
550         // We do not need to use to change the font for the last paragraph
551         // or for a command.
552
553         Font const font = pit->empty()
554                  ? pit->getLayoutFont(bparams, outerfont)
555                  : pit->getFont(bparams, pit->size() - 1, outerfont);
556
557         bool is_command = style.isCommand();
558
559         if (style.resfont.size() != font.fontInfo().size()
560             && nextpit != paragraphs.end()
561             && !is_command) {
562                 if (!need_par)
563                         os << '{';
564                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
565         } else if (need_par) {
566                 os << "\\par}";
567         } else if (is_command)
568                 os << '}';
569
570         bool pending_newline = false;
571         switch (style.latextype) {
572         case LATEX_ITEM_ENVIRONMENT:
573         case LATEX_LIST_ENVIRONMENT:
574                 if (nextpit != paragraphs.end()
575                     && (pit->params().depth() < nextpit->params().depth()))
576                         pending_newline = true;
577                 break;
578         case LATEX_ENVIRONMENT: {
579                 // if its the last paragraph of the current environment
580                 // skip it otherwise fall through
581                 ParagraphList::const_iterator next = nextpit;
582
583                 if (next != paragraphs.end() && (next->layout() != pit->layout()
584                         || next->params().depth() != pit->params().depth()))
585                         break;
586         }
587
588                 // fall through possible
589         default:
590                 // we don't need it for the last paragraph!!!
591                 if (nextpit != paragraphs.end())
592                         pending_newline = true;
593         }
594
595         if (pit->allowParagraphCustomization()) {
596                 if (!pit->params().spacing().isDefault()
597                         && (nextpit == paragraphs.end() || !nextpit->hasSameLayout(*pit)))
598                 {
599                         if (pending_newline) {
600                                 os << '\n';
601                                 texrow.newline();
602                         }
603                         os << from_ascii(pit->params().spacing().writeEnvirEnd(useSetSpace));
604                         pending_newline = true;
605                 }
606         }
607
608         // Closing the language is needed for the last paragraph; it is also
609         // needed if we're within an \L or \R that we may have opened above (not
610         // necessarily in this paragraph) and are about to close.
611         bool closing_rtl_ltr_environment = 
612                 // not for ArabTeX
613                 (par_language->lang() != "arabic_arabtex" &&
614                  outer_language->lang() != "arabic_arabtex") &&
615                 // have we opened and \L or \R environment?
616                 runparams.local_font != 0 &&
617                 runparams.local_font->isRightToLeft() != par_language->rightToLeft() &&
618                 // are we about to close the language?
619                 ((nextpit != paragraphs.end() &&
620                   par_language->babel() != 
621                         (nextpit->getParLanguage(bparams))->babel()) ||
622                  (nextpit == paragraphs.end() &&
623                   par_language->babel() != outer_language->babel()));
624
625         if (closing_rtl_ltr_environment || (nextpit == paragraphs.end()
626             && par_language->babel() != outer_language->babel())) {
627                 // Since \selectlanguage write the language to the aux file,
628                 // we need to reset the language at the end of footnote or
629                 // float.
630
631                 if (pending_newline) {
632                         os << '\n';
633                         texrow.newline();
634                 }
635                 // when the paragraph uses CJK, the language has to be closed earlier
636                 if (font.language()->encoding()->package() != Encoding::CJK) {
637                         if (lyxrc.language_command_end.empty()) {
638                                 if (!prev_language->babel().empty()) {
639                                         os << from_ascii(subst(
640                                                 lyxrc.language_command_begin,
641                                                 "$$lang",
642                                                 prev_language->babel()));
643                                         pending_newline = true;
644                                 }
645                         } else if (!par_language->babel().empty()) {
646                                 os << from_ascii(subst(
647                                         lyxrc.language_command_end,
648                                         "$$lang",
649                                         par_language->babel()));
650                                 pending_newline = true;
651                         }
652                 }
653         }
654         if (closing_rtl_ltr_environment)
655                 os << "}";
656
657         if (pending_newline) {
658                 os << '\n';
659                 texrow.newline();
660         }
661
662         // if this is a CJK-paragraph and the next isn't, close CJK
663         // also if the next paragraph is a multilingual environment (because of nesting)
664         if (nextpit != paragraphs.end() && open_encoding_ == CJK &&
665             (nextpit->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
666              nextpit->layout().isEnvironment() && nextpit->isMultiLingual(bparams))
667              // in environments, CJK has to be closed later (nesting!)
668              && !style.isEnvironment()) {
669                 os << "\\end{CJK}\n";
670                 open_encoding_ = none;
671         }
672
673         // If this is the last paragraph, close the CJK environment
674         // if necessary. If it's an environment, we'll have to \end that first.
675         if (nextpit == paragraphs.end() && !style.isEnvironment()) {
676                 switch (open_encoding_) {
677                         case CJK: {
678                                 // end of main text
679                                 if (maintext) {
680                                         os << '\n';
681                                         texrow.newline();
682                                         os << "\\end{CJK}\n";
683                                         texrow.newline();
684                                 // end of an inset
685                                 } else
686                                         os << "\\end{CJK}";
687                                 open_encoding_ = none;
688                                 break;
689                         }
690                         case inputenc: {
691                                 os << "\\egroup";
692                                 open_encoding_ = none;
693                                 break;
694                         }
695                         case none:
696                         default:
697                                 // do nothing
698                                 break;
699                 }
700         }
701
702         // If this is the last paragraph, and a local_font was set upon entering
703         // the inset, and we're using "auto" or "default" encoding, the encoding
704         // should be set back to that local_font's encoding.
705         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
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         }
711         // Otherwise, the current encoding should be set for the next paragraph.
712         else
713                 runparams_in.encoding = runparams.encoding;
714
715
716         // we don't need it for the last paragraph!!!
717         // Note from JMarc: we will re-add a \n explicitely in
718         // TeXEnvironment, because it is needed in this case
719         if (nextpit != paragraphs.end()) {
720                 os << '\n';
721                 texrow.newline();
722         }
723
724         if (nextpit != paragraphs.end())
725                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
726
727         return nextpit;
728 }
729
730 } // anon namespace
731
732
733 // LaTeX all paragraphs
734 void latexParagraphs(Buffer const & buf,
735                      Text const & text,
736                      odocstream & os,
737                      TexRow & texrow,
738                      OutputParams const & runparams,
739                      string const & everypar)
740 {
741         bool was_title = false;
742         bool already_title = false;
743         BufferParams const & bparams = buf.params();
744         DocumentClass const & tclass = bparams.documentClass();
745         ParagraphList const & paragraphs = text.paragraphs();
746         ParagraphList::const_iterator par = paragraphs.begin();
747         ParagraphList::const_iterator endpar = paragraphs.end();
748
749         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
750         // if only part of the paragraphs will be outputed
751         if (runparams.par_begin !=  runparams.par_end) {
752                 par = boost::next(paragraphs.begin(), runparams.par_begin);
753                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
754                 // runparams will be passed to nested paragraphs, so
755                 // we have to reset the range parameters.
756                 const_cast<OutputParams&>(runparams).par_begin = 0;
757                 const_cast<OutputParams&>(runparams).par_end = 0;
758         }
759
760         bool const maintext = text.isMainText(buf);
761
762         // Open a CJK environment at the beginning of the main buffer
763         // if the document's language is a CJK language
764         if (maintext && bparams.encoding().package() == Encoding::CJK) {
765                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
766                 << "}{}%\n";
767                 texrow.newline();
768                 open_encoding_ = CJK;
769         }
770         // if "auto begin" is switched off, explicitely switch the
771         // language on at start
772         if (maintext && !lyxrc.language_auto_begin &&
773             !bparams.language->babel().empty()) {
774                 // FIXME UNICODE
775                 os << from_utf8(subst(lyxrc.language_command_begin,
776                                         "$$lang",
777                                         bparams.language->babel()))
778                         << '\n';
779         texrow.newline();
780         }
781
782         ParagraphList::const_iterator lastpar;
783         // if only_body
784         while (par != endpar) {
785                 lastpar = par;
786                 // well we have to check if we are in an inset with unlimited
787                 // length (all in one row) if that is true then we don't allow
788                 // any special options in the paragraph and also we don't allow
789                 // any environment other than the default layout of the
790                 // text class to be valid!
791                 if (par->allowParagraphCustomization()) {
792                         Layout const & layout = par->forceEmptyLayout() ?
793                                         tclass.emptyLayout() :
794                                         par->layout();
795
796                         if (layout.intitle) {
797                                 if (already_title) {
798                                         lyxerr << "Error in latexParagraphs: You"
799                                                 " should not mix title layouts"
800                                                 " with normal ones." << endl;
801                                 } else if (!was_title) {
802                                         was_title = true;
803                                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
804                                                 os << "\\begin{"
805                                                     << from_ascii(tclass.titlename())
806                                                     << "}\n";
807                                                 texrow.newline();
808                                         }
809                                 }
810                         } else if (was_title && !already_title) {
811                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
812                                         os << "\\end{" << from_ascii(tclass.titlename())
813                                             << "}\n";
814                                 }
815                                 else {
816                                         os << "\\" << from_ascii(tclass.titlename())
817                                             << "\n";
818                                 }
819                                 texrow.newline();
820                                 already_title = true;
821                                 was_title = false;
822                         }
823
824                         if (layout.is_environment) {
825                                 par = TeXOnePar(buf, text, par, os, texrow,
826                                                 runparams, everypar);
827                         } else if (layout.isEnvironment() ||
828                                    !par->params().leftIndent().zero()) {
829                                 par = TeXEnvironment(buf, text, par, os,
830                                                      texrow, runparams);
831                         } else {
832                                 par = TeXOnePar(buf, text, par, os, texrow,
833                                                 runparams, everypar);
834                         }
835                 } else {
836                         par = TeXOnePar(buf, text, par, os, texrow,
837                                         runparams, everypar);
838                 }
839                 if (distance(lastpar, par) >= distance(lastpar, endpar))
840                         break;
841         }
842         // It might be that we only have a title in this document
843         if (was_title && !already_title) {
844                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
845                         os << "\\end{" << from_ascii(tclass.titlename())
846                             << "}\n";
847                 }
848                 else {
849                         os << "\\" << from_ascii(tclass.titlename())
850                             << "\n";
851                                 }
852                 texrow.newline();
853         }
854         // if "auto end" is switched off, explicitely close the language at the end
855         // but only if the last par is in a babel language
856         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
857                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
858                 os << from_utf8(subst(lyxrc.language_command_end,
859                                         "$$lang",
860                                         bparams.language->babel()))
861                         << '\n';
862                 texrow.newline();
863         }
864         // If the last paragraph is an environment, we'll have to close
865         // CJK at the very end to do proper nesting.
866         if (maintext && open_encoding_ == CJK) {
867                 os << "\\end{CJK}\n";
868                 texrow.newline();
869                 open_encoding_ = none;
870         }
871         // reset inherited encoding
872         if (cjk_inherited_) {
873                 open_encoding_ = CJK;
874                 cjk_inherited_ = false;
875         }
876 }
877
878
879 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
880                    OutputParams const & runparams, Encoding const & newEnc)
881 {
882         Encoding const oldEnc = *runparams.encoding;
883         bool moving_arg = runparams.moving_arg;
884         if ((bparams.inputenc != "auto" && bparams.inputenc != "default")
885                 || moving_arg)
886                 return make_pair(false, 0);
887
888         // Do nothing if the encoding is unchanged.
889         if (oldEnc.name() == newEnc.name())
890                 return make_pair(false, 0);
891
892         // FIXME We ignore encoding switches from/to encodings that do
893         // neither support the inputenc package nor the CJK package here.
894         // This does of course only work in special cases (e.g. switch from
895         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
896         // but it is the best we can do
897         if (oldEnc.package() == Encoding::none
898                 || newEnc.package() == Encoding::none)
899                 return make_pair(false, 0);
900
901         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
902                 << oldEnc.name() << " to " << newEnc.name());
903         os << setEncoding(newEnc.iconvName());
904         if (bparams.inputenc == "default")
905                 return make_pair(true, 0);
906
907         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
908         switch (newEnc.package()) {
909                 case Encoding::none:
910                         // shouldn't ever reach here, see above
911                         return make_pair(true, 0);
912                 case Encoding::inputenc: {
913                         int count = inputenc_arg.length();
914                         if (oldEnc.package() == Encoding::CJK &&
915                             open_encoding_ == CJK) {
916                                 os << "\\end{CJK}";
917                                 open_encoding_ = none;
918                                 count += 9;
919                         }
920                         else if (oldEnc.package() == Encoding::inputenc &&
921                                  open_encoding_ == inputenc) {
922                                 os << "\\egroup";
923                                 open_encoding_ = none;
924                                 count += 7;
925                         }
926                         if (runparams.local_font != 0 && oldEnc.package() == Encoding::CJK) {
927                                 // within insets, \inputenc switches need to be 
928                                 // embraced within \bgroup ... \egroup; else CJK fails.
929                                 os << "\\bgroup";
930                                 count += 7;
931                                 open_encoding_ = inputenc;
932                         }
933                         os << "\\inputencoding{" << inputenc_arg << '}';
934                         return make_pair(true, count + 16);
935                 }
936                 case Encoding::CJK: {
937                         int count = inputenc_arg.length();
938                         if (oldEnc.package() == Encoding::CJK && 
939                             open_encoding_ == CJK) {
940                                 os << "\\end{CJK}";
941                                 count += 9;
942                         }
943                         if (oldEnc.package() == Encoding::inputenc && 
944                             open_encoding_ == inputenc) {
945                                 os << "\\egroup";
946                                 count += 7;
947                         }
948                         os << "\\begin{CJK}{" << inputenc_arg << "}{}";
949                         open_encoding_ = CJK;
950                         return make_pair(true, count + 15);
951                 }
952         }
953         // Dead code to avoid a warning:
954         return make_pair(true, 0);
955
956 }
957
958 } // namespace lyx