]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
2a896ab7518c88df6988436ccd3594fa2cc16cae
[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                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
184                    << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
185                 open_encoding_ = CJK;
186                 cjk_nested = true;
187                 texrow.newline();
188         }
189
190         ParagraphList::const_iterator par = pit;
191         do {
192                 par = TeXOnePar(buf, text, par, os, texrow, runparams);
193
194                 if (par == paragraphs.end()) {
195                         // Make sure that the last paragraph is
196                         // correctly terminated (because TeXOnePar does
197                         // not add a \n in this case)
198                         os << '\n';
199                         texrow.newline();
200                 } else if (par->params().depth() > pit->params().depth()) {
201                         if (par->layout().isParagraph()) {
202                           // Thinko!
203                           // How to handle this? (Lgb)
204                           //&& !suffixIs(os, "\n\n")
205
206                                 // There should be at least one '\n' already
207                                 // but we need there to be two for Standard
208                                 // paragraphs that are depth-increment'ed to be
209                                 // output correctly.  However, tables can
210                                 // also be paragraphs so don't adjust them.
211                                 // ARRae
212                                 // Thinkee:
213                                 // Will it ever harm to have one '\n' too
214                                 // many? i.e. that we sometimes will have
215                                 // three in a row. (Lgb)
216                                 os << '\n';
217                                 texrow.newline();
218                         }
219                         par = TeXDeeper(buf, text, par, os, texrow,
220                                         runparams);
221                 }
222         } while (par != paragraphs.end()
223                  && par->layout() == pit->layout()
224                  && par->params().depth() == pit->params().depth()
225                  && par->params().leftIndent() == pit->params().leftIndent());
226
227         if (open_encoding_ == CJK && cjk_nested) {
228                 // We need to close the encoding even if it does not change
229                 // to do correct environment nesting
230                 os << "\\end{CJK}\n";
231                 texrow.newline();
232                 open_encoding_ = none;
233         }
234
235         if (style.isEnvironment()) {
236                 os << "\\end{" << from_ascii(style.latexname()) << "}\n";
237                 texrow.newline();
238         }
239
240         if (leftindent_open) {
241                 os << "\\end{LyXParagraphLeftIndent}\n";
242                 texrow.newline();
243         }
244
245         if (par != paragraphs.end())
246                 LYXERR(Debug::LATEX, "TeXEnvironment...done " << &*par);
247
248         return par;
249 }
250
251 } // namespace anon
252
253
254 int latexOptArgInsets(Paragraph const & par, odocstream & os,
255         OutputParams const & runparams, int number)
256 {
257         int lines = 0;
258
259         InsetList::const_iterator it = par.insetList().begin();
260         InsetList::const_iterator end = par.insetList().end();
261         for (; it != end && number > 0 ; ++it) {
262                 if (it->inset->lyxCode() == OPTARG_CODE) {
263                         InsetOptArg * ins =
264                                 static_cast<InsetOptArg *>(it->inset);
265                         lines += ins->latexOptional(os, runparams);
266                         --number;
267                 }
268         }
269         return lines;
270 }
271
272 // FIXME: this should be anonymous
273 ParagraphList::const_iterator TeXOnePar(Buffer const & buf,
274           Text const & text,
275           ParagraphList::const_iterator const pit,
276           odocstream & os, TexRow & texrow,
277           OutputParams const & runparams_in,
278           string const & everypar,
279           int start_pos, int end_pos)
280 {
281         LYXERR(Debug::LATEX, "TeXOnePar...     " << &*pit << " '"
282                 << everypar << "'");
283         BufferParams const & bparams = buf.params();
284         ParagraphList const & paragraphs = text.paragraphs();
285
286         ParagraphList::const_iterator const priorpit = 
287                 pit == paragraphs.begin() ? pit : boost::prior(pit);
288         ParagraphList::const_iterator const nextpit = 
289                 pit == paragraphs.end() ? pit : boost::next(pit);
290
291         OutputParams runparams = runparams_in;
292         runparams.isLastPar = nextpit == paragraphs.end();
293
294         if (runparams.verbatim) {
295                 int const dist = distance(paragraphs.begin(), pit);
296                 Font const outerfont = outerFont(dist, paragraphs);
297
298                 // No newline if only one paragraph in this lyxtext
299                 if (dist > 0) {
300                         os << '\n';
301                         texrow.newline();
302                 }
303
304                 /*bool need_par = */ pit->latex(bparams, outerfont,
305                         os, texrow, runparams, start_pos, end_pos);
306                 return nextpit;
307         }
308
309         // FIXME This check should not really be needed.
310         // Perhaps we should issue an error if it is.
311         Layout const style = pit->forcePlainLayout() ?
312                 bparams.documentClass().plainLayout() : pit->layout();
313
314         runparams.moving_arg |= style.needprotect;
315
316         bool const maintext = text.isMainText(buf);
317         // we are at the beginning of an inset and CJK is already open;
318         // we count inheritation levels to get the inset nesting right.
319         if (pit == paragraphs.begin() && !maintext
320             && (cjk_inherited_ > 0 || open_encoding_ == CJK)) {
321                 cjk_inherited_ += 1;
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_ == 0) {
453                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
454                                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\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, start_pos, end_pos);
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 const 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                 if (nextpit != paragraphs.end() && 
577                     (nextpit->layout() != pit->layout()
578                      || nextpit->params().depth() != pit->params().depth()))
579                         break;
580         }
581
582                 // fall through possible
583         default:
584                 // we don't need it for the last paragraph!!!
585                 if (nextpit != paragraphs.end())
586                         pending_newline = true;
587         }
588
589         if (pit->allowParagraphCustomization()) {
590                 if (!pit->params().spacing().isDefault()
591                         && (nextpit == paragraphs.end() || !nextpit->hasSameLayout(*pit)))
592                 {
593                         if (pending_newline) {
594                                 os << '\n';
595                                 texrow.newline();
596                         }
597                         os << from_ascii(pit->params().spacing().writeEnvirEnd(useSetSpace));
598                         pending_newline = true;
599                 }
600         }
601
602         // Closing the language is needed for the last paragraph; it is also
603         // needed if we're within an \L or \R that we may have opened above (not
604         // necessarily in this paragraph) and are about to close.
605         bool closing_rtl_ltr_environment =
606                 // not for ArabTeX
607                 (par_language->lang() != "arabic_arabtex" &&
608                  outer_language->lang() != "arabic_arabtex") &&
609                 // have we opened and \L or \R environment?
610                 runparams.local_font != 0 &&
611                 runparams.local_font->isRightToLeft() != par_language->rightToLeft() &&
612                 // are we about to close the language?
613                 ((nextpit != paragraphs.end() &&
614                   par_language->babel() !=
615                     (nextpit->getParLanguage(bparams))->babel()) ||
616                   (nextpit == paragraphs.end() &&
617                     par_language->babel() != outer_language->babel()));
618
619         if (closing_rtl_ltr_environment || (nextpit == paragraphs.end()
620             && par_language->babel() != outer_language->babel())) {
621                 // Since \selectlanguage write the language to the aux file,
622                 // we need to reset the language at the end of footnote or
623                 // float.
624
625                 if (pending_newline) {
626                         os << '\n';
627                         texrow.newline();
628                 }
629                 // when the paragraph uses CJK, the language has to be closed earlier
630                 if (font.language()->encoding()->package() != Encoding::CJK) {
631                         if (lyxrc.language_command_end.empty()) {
632                                 if (!prev_language->babel().empty()) {
633                                         os << from_ascii(subst(
634                                                 lyxrc.language_command_begin,
635                                                 "$$lang",
636                                                 prev_language->babel()));
637                                         pending_newline = true;
638                                 }
639                         } else if (!par_language->babel().empty()) {
640                                 os << from_ascii(subst(
641                                         lyxrc.language_command_end,
642                                         "$$lang",
643                                         par_language->babel()));
644                                 pending_newline = true;
645                         }
646                 }
647         }
648         if (closing_rtl_ltr_environment)
649                 os << "}";
650
651         if (pending_newline) {
652                 os << '\n';
653                 texrow.newline();
654         }
655
656         // if this is a CJK-paragraph and the next isn't, close CJK
657         // also if the next paragraph is a multilingual environment (because of nesting)
658         if (nextpit != paragraphs.end() && open_encoding_ == CJK &&
659             (nextpit->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
660              nextpit->layout().isEnvironment() && nextpit->isMultiLingual(bparams))
661              // in environments, CJK has to be closed later (nesting!)
662              && !style.isEnvironment()) {
663                 os << "\\end{CJK}\n";
664                 open_encoding_ = none;
665         }
666
667         // If this is the last paragraph, close the CJK environment
668         // if necessary. If it's an environment, we'll have to \end that first.
669         if (nextpit == paragraphs.end() && !style.isEnvironment()) {
670                 switch (open_encoding_) {
671                         case CJK: {
672                                 // do nothing at the end of child documents
673                                 if (maintext && buf.masterBuffer() != &buf)
674                                         break;
675                                 // end of main text
676                                 if (maintext) {
677                                         os << '\n';
678                                         texrow.newline();
679                                         os << "\\end{CJK}\n";
680                                         texrow.newline();
681                                 // end of an inset
682                                 } else
683                                         os << "\\end{CJK}";
684                                 open_encoding_ = none;
685                                 break;
686                         }
687                         case inputenc: {
688                                 os << "\\egroup";
689                                 open_encoding_ = none;
690                                 break;
691                         }
692                         case none:
693                         default:
694                                 // do nothing
695                                 break;
696                 }
697         }
698
699         // If this is the last paragraph, and a local_font was set upon entering
700         // the inset, and we're using "auto" or "default" encoding, the encoding
701         // should be set back to that local_font's encoding.
702         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
703             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
704             && (bparams.inputenc == "auto" || bparams.inputenc == "default")) {
705                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
706                 os << setEncoding(runparams_in.encoding->iconvName());
707         }
708         // Otherwise, the current encoding should be set for the next paragraph.
709         else
710                 runparams_in.encoding = runparams.encoding;
711
712
713         // we don't need a newline for the last paragraph!!!
714         // Note from JMarc: we will re-add a \n explicitly in
715         // TeXEnvironment, because it is needed in this case
716         if (nextpit != paragraphs.end()) {
717                 Layout const & next_layout = nextpit->layout();
718                 if (style == next_layout
719                     // no blank lines before environments!
720                     || !next_layout.isEnvironment()
721                     // unless there's a depth change
722                     // FIXME What we really want to do here is put every \begin and \end
723                     // tag on a new line (which was not the case with nested environments).
724                     // But in the present state of play, we don't have access to the
725                     // information whether the current TeX row is empty or not.
726                     // For some ideas about how to fix this, see this thread:
727                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
728                     || nextpit->params().depth() != pit->params().depth()) {
729                         os << '\n';
730                         texrow.newline();
731                 }
732         }
733
734         if (nextpit != paragraphs.end())
735                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
736
737         return nextpit;
738 }
739
740
741 // LaTeX all paragraphs
742 void latexParagraphs(Buffer const & buf,
743                      Text const & text,
744                      odocstream & os,
745                      TexRow & texrow,
746                      OutputParams const & runparams,
747                      string const & everypar)
748 {
749         bool was_title = false;
750         bool already_title = false;
751         BufferParams const & bparams = buf.params();
752         DocumentClass const & tclass = bparams.documentClass();
753         ParagraphList const & paragraphs = text.paragraphs();
754         ParagraphList::const_iterator par = paragraphs.begin();
755         ParagraphList::const_iterator endpar = paragraphs.end();
756
757         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
758         // if only part of the paragraphs will be outputed
759         if (runparams.par_begin !=  runparams.par_end) {
760                 par = boost::next(paragraphs.begin(), runparams.par_begin);
761                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
762                 // runparams will be passed to nested paragraphs, so
763                 // we have to reset the range parameters.
764                 const_cast<OutputParams&>(runparams).par_begin = 0;
765                 const_cast<OutputParams&>(runparams).par_end = 0;
766         }
767
768         bool const maintext = text.isMainText(buf);
769         bool const is_child = buf.masterBuffer() != &buf;
770
771         // Open a CJK environment at the beginning of the main buffer
772         // if the document's language is a CJK language
773         // (but not in child documents)
774         if (maintext && !is_child
775             && bparams.encoding().package() == Encoding::CJK) {
776                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
777                 << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
778                 texrow.newline();
779                 open_encoding_ = CJK;
780         }
781         // if "auto begin" is switched off, explicitely switch the
782         // language on at start
783         if (maintext && !lyxrc.language_auto_begin &&
784             !bparams.language->babel().empty()) {
785                 // FIXME UNICODE
786                 os << from_utf8(subst(lyxrc.language_command_begin,
787                                         "$$lang",
788                                         bparams.language->babel()))
789                         << '\n';
790         texrow.newline();
791         }
792
793         ParagraphList::const_iterator lastpar;
794         // if only_body
795         while (par != endpar) {
796                 lastpar = par;
797                 // FIXME This check should not be needed. We should
798                 // perhaps issue an error if it is.
799                 Layout const & layout = par->forcePlainLayout() ?
800                                 tclass.plainLayout() :
801                                 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