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