]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
be294b74ddc599d5e8ca780a4609b9caf2b8e084
[lyx.git] / src / output_latex.cpp
1 /**
2  * \file output_latex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "output_latex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "Encoding.h"
18 #include "InsetList.h"
19 #include "Language.h"
20 #include "Layout.h"
21 #include "LyXRC.h"
22 #include "OutputParams.h"
23 #include "Paragraph.h"
24 #include "paragraph_funcs.h"
25 #include "ParagraphParameters.h"
26 #include "TextClass.h"
27 #include "TexRow.h"
28 #include "VSpace.h"
29
30 #include "insets/InsetBibitem.h"
31 #include "insets/InsetOptArg.h"
32
33 #include "support/lassert.h"
34 #include "support/debug.h"
35 #include "support/lstrings.h"
36
37 #include <boost/next_prior.hpp>
38
39 using namespace std;
40 using namespace lyx::support;
41
42
43 namespace lyx {
44
45 namespace {
46
47 enum OpenEncoding {
48                 none,
49                 inputenc,
50                 CJK
51 };
52
53 static int open_encoding_ = none;
54 static int cjk_inherited_ = 0;
55
56
57 ParagraphList::const_iterator
58 TeXEnvironment(Buffer const & buf,
59                Text const & text,
60                ParagraphList::const_iterator pit,
61                odocstream & os, TexRow & texrow,
62                OutputParams const & runparams);
63
64
65 ParagraphList::const_iterator
66 TeXDeeper(Buffer const & buf,
67           Text const & text,
68           ParagraphList::const_iterator pit,
69           odocstream & os, TexRow & texrow,
70           OutputParams const & runparams)
71 {
72         LYXERR(Debug::LATEX, "TeXDeeper...     " << &*pit);
73         ParagraphList::const_iterator par = pit;
74
75         ParagraphList const & paragraphs = text.paragraphs();
76
77         while (par != paragraphs.end() &&
78                                         par->params().depth() == pit->params().depth()) {
79                 // FIXME This test should not be necessary.
80                 // We should perhaps issue an error if it is.
81                 Layout const & style = par->forcePlainLayout() ?
82                         buf.params().documentClass().plainLayout() : par->layout();
83                 if (style.isEnvironment()) {
84                         par = TeXEnvironment(buf, text, par,
85                                              os, texrow, runparams);
86                 } else {
87                         par = TeXOnePar(buf, text, par,
88                                              os, texrow, runparams);
89                 }
90         }
91         LYXERR(Debug::LATEX, "TeXDeeper...done ");
92
93         return par;
94 }
95
96
97 ParagraphList::const_iterator
98 TeXEnvironment(Buffer const & buf,
99                Text const & text,
100                ParagraphList::const_iterator pit,
101                odocstream & os, TexRow & texrow,
102                OutputParams const & runparams)
103 {
104         LYXERR(Debug::LATEX, "TeXEnvironment...     " << &*pit);
105
106         BufferParams const & bparams = buf.params();
107
108         // FIXME This test should not be necessary.
109         // We should perhaps issue an error if it is.
110         Layout const & style = pit->forcePlainLayout() ?
111                 bparams.documentClass().plainLayout() : pit->layout();
112
113         ParagraphList const & paragraphs = text.paragraphs();
114
115         Language const * const par_language = pit->getParLanguage(bparams);
116         Language const * const doc_language = bparams.language;
117         Language const * const prev_par_language =
118                 (pit != paragraphs.begin())
119                 ? boost::prior(pit)->getParLanguage(bparams)
120                 : doc_language;
121         if (par_language->babel() != prev_par_language->babel()) {
122
123                 if (!lyxrc.language_command_end.empty() &&
124                     prev_par_language->babel() != doc_language->babel() &&
125                     !prev_par_language->babel().empty()) {
126                         os << from_ascii(subst(
127                                 lyxrc.language_command_end,
128                                 "$$lang",
129                                 prev_par_language->babel()))
130                            // the '%' is necessary to prevent unwanted whitespace
131                            << "%\n";
132                         texrow.newline();
133                 }
134
135                 if ((lyxrc.language_command_end.empty() ||
136                      par_language->babel() != doc_language->babel()) &&
137                     !par_language->babel().empty()) {
138                         os << from_ascii(subst(
139                                 lyxrc.language_command_begin,
140                                 "$$lang",
141                                 par_language->babel()))
142                            // the '%' is necessary to prevent unwanted whitespace
143                            << "%\n";
144                         texrow.newline();
145                 }
146         }
147
148         bool leftindent_open = false;
149         if (!pit->params().leftIndent().zero()) {
150                 os << "\\begin{LyXParagraphLeftIndent}{"
151                    << from_ascii(pit->params().leftIndent().asLatexString())
152                    << "}\n";
153                 texrow.newline();
154                 leftindent_open = true;
155         }
156
157         if (style.isEnvironment()) {
158                 os << "\\begin{" << from_ascii(style.latexname()) << '}';
159                 if (style.optionalargs > 0) {
160                         int ret = latexOptArgInsets(*pit, os, runparams,
161                                                     style.optionalargs);
162                         while (ret > 0) {
163                                 texrow.newline();
164                                 --ret;
165                         }
166                 }
167                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
168                         os << '{'
169                            << pit->params().labelWidthString()
170                            << "}\n";
171                 } else if (style.labeltype == LABEL_BIBLIO) {
172                         // ale970405
173                         os << '{' << bibitemWidest(buf) << "}\n";
174                 } else
175                         os << from_ascii(style.latexparam()) << '\n';
176                 texrow.newline();
177         }
178
179         // in multilingual environments, the CJK tags have to be nested properly
180         bool cjk_nested = false;
181         if (par_language->encoding()->package() == Encoding::CJK &&
182             open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
183                 if (prev_par_language->encoding()->package() == Encoding::CJK)
184                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
185                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\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 // FIXME: this should be anonymous
274 ParagraphList::const_iterator TeXOnePar(Buffer const & buf,
275           Text const & text,
276           ParagraphList::const_iterator const pit,
277           odocstream & os, TexRow & texrow,
278           OutputParams const & runparams_in,
279           string const & everypar,
280           int start_pos, int end_pos)
281 {
282         LYXERR(Debug::LATEX, "TeXOnePar...     " << &*pit << " '"
283                 << everypar << "'");
284         BufferParams const & bparams = buf.params();
285         ParagraphList const & paragraphs = text.paragraphs();
286
287         ParagraphList::const_iterator const priorpit = 
288                 pit == paragraphs.begin() ? pit : boost::prior(pit);
289         ParagraphList::const_iterator const nextpit = 
290                 pit == paragraphs.end() ? pit : boost::next(pit);
291
292         OutputParams runparams = runparams_in;
293         runparams.isLastPar = nextpit == paragraphs.end();
294
295         if (runparams.verbatim) {
296                 int const dist = distance(paragraphs.begin(), pit);
297                 Font const outerfont = outerFont(dist, paragraphs);
298
299                 // No newline if only one paragraph in this lyxtext
300                 if (dist > 0) {
301                         os << '\n';
302                         texrow.newline();
303                 }
304
305                 /*bool need_par = */ pit->latex(bparams, outerfont,
306                         os, texrow, runparams, start_pos, end_pos);
307                 return nextpit;
308         }
309
310         // FIXME This check should not really be needed.
311         // Perhaps we should issue an error if it is.
312         Layout const style = pit->forcePlainLayout() ?
313                 bparams.documentClass().plainLayout() : pit->layout();
314
315         runparams.moving_arg |= style.needprotect;
316
317         bool const maintext = text.isMainText(buf);
318         // we are at the beginning of an inset and CJK is already open;
319         // we count inheritation levels to get the inset nesting right.
320         if (pit == paragraphs.begin() && !maintext
321             && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
322                 cjk_inherited_ += 1;
323                 open_encoding_ = none;
324         }
325
326         // This paragraph's language
327         Language const * const par_language = pit->getParLanguage(bparams);
328         // The document's language
329         Language const * const doc_language = bparams.language;
330         // The language that was in effect when the environment this paragraph is
331         // inside of was opened
332         Language const * const outer_language =
333                 (runparams.local_font != 0) ?
334                         runparams.local_font->language() : doc_language;
335         // The previous language that was in effect is either the language of
336         // the previous paragraph, if there is one, or else the outer language
337         // if there is no previous paragraph
338         Language const * const prev_language =
339                 (pit != paragraphs.begin()) ?
340                         priorpit->getParLanguage(bparams) : outer_language;
341
342         if (par_language->babel() != prev_language->babel()
343             // check if we already put language command in TeXEnvironment()
344             && !(style.isEnvironment()
345                  && (pit == paragraphs.begin() ||
346                      (priorpit->layout() != pit->layout() &&
347                       priorpit->getDepth() <= pit->getDepth())
348                      || priorpit->getDepth() < pit->getDepth())))
349         {
350                 if (!lyxrc.language_command_end.empty() &&
351                     prev_language->babel() != outer_language->babel() &&
352                     !prev_language->babel().empty())
353                 {
354                         os << from_ascii(subst(lyxrc.language_command_end,
355                                 "$$lang",
356                                 prev_language->babel()))
357                            // the '%' is necessary to prevent unwanted whitespace
358                            << "%\n";
359                         texrow.newline();
360                 }
361
362                 // We need to open a new language if we couldn't close the previous
363                 // one (because there's no language_command_end); and even if we closed
364                 // the previous one, if the current language is different than the
365                 // outer_language (which is currently in effect once the previous one
366                 // is closed).
367                 if ((lyxrc.language_command_end.empty() ||
368                      par_language->babel() != outer_language->babel()) &&
369                     !par_language->babel().empty()) {
370                         // If we're inside an inset, and that inset is within an \L or \R
371                         // (or equivalents), then within the inset, too, any opposite
372                         // language paragraph should appear within an \L or \R (in addition
373                         // to, outside of, the normal language switch commands).
374                         // This behavior is not correct for ArabTeX, though.
375                         if (    // not for ArabTeX
376                                         (par_language->lang() != "arabic_arabtex" &&
377                                          outer_language->lang() != "arabic_arabtex") &&
378                                         // are we in an inset?
379                                         runparams.local_font != 0 &&
380                                         // is the inset within an \L or \R?
381                                         //
382                                         // FIXME: currently, we don't check this; this means that
383                                         // we'll have unnnecessary \L and \R commands, but that
384                                         // doesn't seem to hurt (though latex will complain)
385                                         //
386                                         // is this paragraph in the opposite direction?
387                                         runparams.local_font->isRightToLeft() !=
388                                                 par_language->rightToLeft()
389                                 ) {
390                                 // FIXME: I don't have a working copy of the Arabi package, so
391                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
392                                 // or not...
393                                 if (par_language->lang() == "farsi")
394                                         os << "\\textFR{";
395                                 else if (outer_language->lang() == "farsi")
396                                         os << "\\textLR{";
397                                 else if (par_language->lang() == "arabic_arabi")
398                                         os << "\\textAR{";
399                                 else if (outer_language->lang() == "arabic_arabi")
400                                         os << "\\textLR{";
401                                 // remaining RTL languages currently is hebrew
402                                 else if (par_language->rightToLeft())
403                                         os << "\\R{";
404                                 else
405                                         os << "\\L{";
406                         }
407                         // With CJK, the CJK tag has to be closed first (see below)
408                         if (runparams.encoding->package() != Encoding::CJK) {
409                                 os << from_ascii(subst(
410                                         lyxrc.language_command_begin,
411                                         "$$lang",
412                                         par_language->babel()))
413                                    // the '%' is necessary to prevent unwanted whitespace
414                                    << "%\n";
415                                 texrow.newline();
416                         }
417                 }
418         }
419
420         // Switch file encoding if necessary; no need to do this for "default"
421         // encoding, since this only affects the position of the outputted
422         // \inputencoding command; the encoding switch will occur when necessary
423         if (bparams.inputenc == "auto" &&
424             runparams.encoding->package() != Encoding::none) {
425                 // Look ahead for future encoding changes.
426                 // We try to output them at the beginning of the paragraph,
427                 // since the \inputencoding command is not allowed e.g. in
428                 // sections.
429                 for (pos_type i = 0; i < pit->size(); ++i) {
430                         char_type const c = pit->getChar(i);
431                         Encoding const * const encoding =
432                                 pit->getFontSettings(bparams, i).language()->encoding();
433                         if (encoding->package() != Encoding::CJK &&
434                             runparams.encoding->package() == Encoding::inputenc &&
435                             c < 0x80)
436                                 continue;
437                         if (pit->isInset(i))
438                                 break;
439                         // All characters before c are in the ASCII range, and
440                         // c is non-ASCII (but no inset), so change the
441                         // encoding to that required by the language of c.
442                         // With CJK, only add switch if we have CJK content at the beginning
443                         // of the paragraph
444                         if (encoding->package() != Encoding::CJK || i == 0) {
445                                 OutputParams tmp_rp = runparams;
446                                 runparams.moving_arg = false;
447                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
448                                         *encoding);
449                                 runparams = tmp_rp;
450                                 // the following is necessary after a CJK environment in a multilingual
451                                 // context (nesting issue).
452                                 if (par_language->encoding()->package() == Encoding::CJK &&
453                                     open_encoding_ != CJK && cjk_inherited_ == 0) {
454                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
455                                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
456                                         open_encoding_ = CJK;
457                                         texrow.newline();
458                                 }
459                                 if (encoding->package() != Encoding::none && enc_switch.first) {
460                                         if (enc_switch.second > 0) {
461                                                 // the '%' is necessary to prevent unwanted whitespace
462                                                 os << "%\n";
463                                                 texrow.newline();
464                                         }
465                                         // With CJK, the CJK tag had to be closed first (see above)
466                                         if (runparams.encoding->package() == Encoding::CJK) {
467                                                 os << from_ascii(subst(
468                                                         lyxrc.language_command_begin,
469                                                         "$$lang",
470                                                         par_language->babel()))
471                                                 // the '%' is necessary to prevent unwanted whitespace
472                                                 << "%\n";
473                                                 texrow.newline();
474                                         }
475                                         runparams.encoding = encoding;
476                                 }
477                                 break;
478                         }
479                 }
480         }
481
482         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
483         if (pit->allowParagraphCustomization()) {
484                 if (pit->params().startOfAppendix()) {
485                         os << "\\appendix\n";
486                         texrow.newline();
487                 }
488
489                 if (!pit->params().spacing().isDefault()
490                         && (pit == paragraphs.begin()
491                             || !priorpit->hasSameLayout(*pit)))
492                 {
493                         os << from_ascii(pit->params().spacing().writeEnvirBegin(useSetSpace))
494                             << '\n';
495                         texrow.newline();
496                 }
497
498                 if (style.isCommand()) {
499                         os << '\n';
500                         texrow.newline();
501                 }
502         }
503
504         switch (style.latextype) {
505         case LATEX_COMMAND:
506                 os << '\\' << from_ascii(style.latexname());
507
508                 // Separate handling of optional argument inset.
509                 if (style.optionalargs > 0) {
510                         int ret = latexOptArgInsets(*pit, os, runparams,
511                                                     style.optionalargs);
512                         while (ret > 0) {
513                                 texrow.newline();
514                                 --ret;
515                         }
516                 }
517                 else
518                         os << from_ascii(style.latexparam());
519                 break;
520         case LATEX_ITEM_ENVIRONMENT:
521         case LATEX_LIST_ENVIRONMENT:
522                 os << "\\item ";
523                 break;
524         case LATEX_BIB_ENVIRONMENT:
525                 // ignore this, the inset will write itself
526                 break;
527         default:
528                 break;
529         }
530
531         Font const outerfont = outerFont(distance(paragraphs.begin(), pit),
532                           paragraphs);
533
534         // FIXME UNICODE
535         os << from_utf8(everypar);
536         bool need_par = pit->latex(bparams, outerfont,
537                                              os, texrow, runparams, start_pos, end_pos);
538
539         // Make sure that \\par is done with the font of the last
540         // character if this has another size as the default.
541         // This is necessary because LaTeX (and LyX on the screen)
542         // calculates the space between the baselines according
543         // to this font. (Matthias)
544         //
545         // Is this really needed ? (Dekel)
546         // We do not need to use to change the font for the last paragraph
547         // or for a command.
548
549         Font const font = pit->empty()
550                  ? pit->getLayoutFont(bparams, outerfont)
551                  : pit->getFont(bparams, pit->size() - 1, outerfont);
552
553         bool const is_command = style.isCommand();
554
555         if (style.resfont.size() != font.fontInfo().size()
556             && nextpit != paragraphs.end()
557             && !is_command) {
558                 if (!need_par)
559                         os << '{';
560                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
561         } else if (need_par) {
562                 os << "\\par}";
563         } else if (is_command)
564                 os << '}';
565
566         bool pending_newline = false;
567         switch (style.latextype) {
568         case LATEX_ITEM_ENVIRONMENT:
569         case LATEX_LIST_ENVIRONMENT:
570                 if (nextpit != paragraphs.end()
571                     && (pit->params().depth() < nextpit->params().depth()))
572                         pending_newline = true;
573                 break;
574         case LATEX_ENVIRONMENT: {
575                 // if its the last paragraph of the current environment
576                 // skip it otherwise fall through
577                 if (nextpit != paragraphs.end() && 
578                     (nextpit->layout() != pit->layout()
579                      || nextpit->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              // inbetween environments, CJK has to be closed later (nesting!)
663              && (!style.isEnvironment() || !nextpit->layout().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                                 // do nothing at the end of child documents
674                                 if (maintext && buf.masterBuffer() != &buf)
675                                         break;
676                                 // end of main text
677                                 if (maintext) {
678                                         os << '\n';
679                                         texrow.newline();
680                                         os << "\\end{CJK}\n";
681                                         texrow.newline();
682                                 // end of an inset
683                                 } else
684                                         os << "\\end{CJK}";
685                                 open_encoding_ = none;
686                                 break;
687                         }
688                         case inputenc: {
689                                 os << "\\egroup";
690                                 open_encoding_ = none;
691                                 break;
692                         }
693                         case none:
694                         default:
695                                 // do nothing
696                                 break;
697                 }
698         }
699
700         // If this is the last paragraph, and a local_font was set upon entering
701         // the inset, and we're using "auto" or "default" encoding, the encoding
702         // should be set back to that local_font's encoding.
703         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
704             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
705             && (bparams.inputenc == "auto" || bparams.inputenc == "default")) {
706                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
707                 os << setEncoding(runparams_in.encoding->iconvName());
708         }
709         // Otherwise, the current encoding should be set for the next paragraph.
710         else
711                 runparams_in.encoding = runparams.encoding;
712
713
714         // we don't need a newline for the last paragraph!!!
715         // Note from JMarc: we will re-add a \n explicitly in
716         // TeXEnvironment, because it is needed in this case
717         if (nextpit != paragraphs.end()) {
718                 Layout const & next_layout = nextpit->layout();
719                 if (style == next_layout
720                     // no blank lines before environments!
721                     || !next_layout.isEnvironment()
722                     // unless there's a depth change
723                     // FIXME What we really want to do here is put every \begin and \end
724                     // tag on a new line (which was not the case with nested environments).
725                     // But in the present state of play, we don't have access to the
726                     // information whether the current TeX row is empty or not.
727                     // For some ideas about how to fix this, see this thread:
728                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
729                     || nextpit->params().depth() != pit->params().depth()) {
730                         os << '\n';
731                         texrow.newline();
732                 }
733         }
734
735         if (nextpit != paragraphs.end())
736                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
737
738         return nextpit;
739 }
740
741
742 // LaTeX all paragraphs
743 void latexParagraphs(Buffer const & buf,
744                      Text const & text,
745                      odocstream & os,
746                      TexRow & texrow,
747                      OutputParams const & runparams,
748                      string const & everypar)
749 {
750         bool was_title = false;
751         bool already_title = false;
752         BufferParams const & bparams = buf.params();
753         DocumentClass const & tclass = bparams.documentClass();
754         ParagraphList const & paragraphs = text.paragraphs();
755         ParagraphList::const_iterator par = paragraphs.begin();
756         ParagraphList::const_iterator endpar = paragraphs.end();
757
758         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
759         // if only part of the paragraphs will be outputed
760         if (runparams.par_begin !=  runparams.par_end) {
761                 par = boost::next(paragraphs.begin(), runparams.par_begin);
762                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
763                 // runparams will be passed to nested paragraphs, so
764                 // we have to reset the range parameters.
765                 const_cast<OutputParams&>(runparams).par_begin = 0;
766                 const_cast<OutputParams&>(runparams).par_end = 0;
767         }
768
769         bool const maintext = text.isMainText(buf);
770         bool const is_child = buf.masterBuffer() != &buf;
771
772         // Open a CJK environment at the beginning of the main buffer
773         // if the document's language is a CJK language
774         // (but not in child documents)
775         if (maintext && !is_child
776             && bparams.encoding().package() == Encoding::CJK) {
777                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
778                 << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
779                 texrow.newline();
780                 open_encoding_ = CJK;
781         }
782         // if "auto begin" is switched off, explicitely switch the
783         // language on at start
784         if (maintext && !lyxrc.language_auto_begin &&
785             !bparams.language->babel().empty()) {
786                 // FIXME UNICODE
787                 os << from_utf8(subst(lyxrc.language_command_begin,
788                                         "$$lang",
789                                         bparams.language->babel()))
790                         << '\n';
791         texrow.newline();
792         }
793
794         ParagraphList::const_iterator lastpar;
795         // if only_body
796         while (par != endpar) {
797                 lastpar = par;
798                 // FIXME This check should not be needed. We should
799                 // perhaps issue an error if it is.
800                 Layout const & layout = par->forcePlainLayout() ?
801                                 tclass.plainLayout() : par->layout();
802
803                 if (layout.intitle) {
804                         if (already_title) {
805                                 lyxerr << "Error in latexParagraphs: You"
806                                         " should not mix title layouts"
807                                         " with normal ones." << endl;
808                         } else if (!was_title) {
809                                 was_title = true;
810                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
811                                         os << "\\begin{"
812                                                         << from_ascii(tclass.titlename())
813                                                         << "}\n";
814                                         texrow.newline();
815                                 }
816                         }
817                 } else if (was_title && !already_title) {
818                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
819                                 os << "\\end{" << from_ascii(tclass.titlename())
820                                                 << "}\n";
821                         }
822                         else {
823                                 os << "\\" << from_ascii(tclass.titlename())
824                                                 << "\n";
825                         }
826                         texrow.newline();
827                         already_title = true;
828                         was_title = false;
829                 }
830
831                 if (layout.isEnvironment() ||
832                                         !par->params().leftIndent().zero()) {
833                         par = TeXEnvironment(buf, text, par, os,
834                                                                 texrow, runparams);
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
843         // It might be that we only have a title in this document
844         if (was_title && !already_title) {
845                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
846                         os << "\\end{" << from_ascii(tclass.titlename())
847                             << "}\n";
848                 }
849                 else {
850                         os << "\\" << from_ascii(tclass.titlename())
851                             << "\n";
852                                 }
853                 texrow.newline();
854         }
855
856         // if "auto end" is switched off, explicitely close the language at the end
857         // but only if the last par is in a babel language
858         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
859                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
860                 os << from_utf8(subst(lyxrc.language_command_end,
861                                         "$$lang",
862                                         bparams.language->babel()))
863                         << '\n';
864                 texrow.newline();
865         }
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 && !is_child && open_encoding_ == CJK) {
870                 os << "\\end{CJK}\n";
871                 texrow.newline();
872                 open_encoding_ = none;
873         }
874
875         // reset inherited encoding
876         if (cjk_inherited_ > 0) {
877                 cjk_inherited_ -= 1;
878                 if (cjk_inherited_ == 0)
879                         open_encoding_ = CJK;
880         }
881 }
882
883
884 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
885                    OutputParams const & runparams, Encoding const & newEnc,
886                    bool force)
887 {
888         Encoding const & oldEnc = *runparams.encoding;
889         bool moving_arg = runparams.moving_arg;
890         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
891                 || moving_arg))
892                 return make_pair(false, 0);
893
894         // Do nothing if the encoding is unchanged.
895         if (oldEnc.name() == newEnc.name())
896                 return make_pair(false, 0);
897
898         // FIXME We ignore encoding switches from/to encodings that do
899         // neither support the inputenc package nor the CJK package here.
900         // This does of course only work in special cases (e.g. switch from
901         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
902         // but it is the best we can do
903         if (oldEnc.package() == Encoding::none
904                 || newEnc.package() == Encoding::none)
905                 return make_pair(false, 0);
906
907         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
908                 << oldEnc.name() << " to " << newEnc.name());
909         os << setEncoding(newEnc.iconvName());
910         if (bparams.inputenc == "default")
911                 return make_pair(true, 0);
912
913         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
914         switch (newEnc.package()) {
915                 case Encoding::none:
916                 case Encoding::japanese:
917                         // shouldn't ever reach here, see above
918                         return make_pair(true, 0);
919                 case Encoding::inputenc: {
920                         int count = inputenc_arg.length();
921                         if (oldEnc.package() == Encoding::CJK &&
922                             open_encoding_ == CJK) {
923                                 os << "\\end{CJK}";
924                                 open_encoding_ = none;
925                                 count += 9;
926                         }
927                         else if (oldEnc.package() == Encoding::inputenc &&
928                                  open_encoding_ == inputenc) {
929                                 os << "\\egroup";
930                                 open_encoding_ = none;
931                                 count += 7;
932                         }
933                         if (runparams.local_font != 0
934                             &&  oldEnc.package() == Encoding::CJK) {
935                                 // within insets, \inputenc switches need
936                                 // to be embraced within \bgroup...\egroup;
937                                 // else CJK fails.
938                                 os << "\\bgroup";
939                                 count += 7;
940                                 open_encoding_ = inputenc;
941                         }
942                         // with the japanese option, inputenc is omitted.
943                         if (runparams.use_japanese)
944                                 return make_pair(true, count);
945                         os << "\\inputencoding{" << inputenc_arg << '}';
946                         return make_pair(true, count + 16);
947                 }
948                 case Encoding::CJK: {
949                         int count = inputenc_arg.length();
950                         if (oldEnc.package() == Encoding::CJK &&
951                             open_encoding_ == CJK) {
952                                 os << "\\end{CJK}";
953                                 count += 9;
954                         }
955                         if (oldEnc.package() == Encoding::inputenc &&
956                             open_encoding_ == inputenc) {
957                                 os << "\\egroup";
958                                 count += 7;
959                         }
960                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
961                            << from_ascii(bparams.fontsCJK) << "}";
962                         open_encoding_ = CJK;
963                         return make_pair(true, count + 15);
964                 }
965         }
966         // Dead code to avoid a warning:
967         return make_pair(true, 0);
968
969 }
970
971 } // namespace lyx