]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
Fix bug #2213 (part 1): GuiChanges lacks "Previous Change" button.
[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                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
446                                         *encoding);
447                                 // the following is necessary after a CJK environment in a multilingual
448                                 // context (nesting issue).
449                                 if (par_language->encoding()->package() == Encoding::CJK &&
450                                     open_encoding_ != CJK && cjk_inherited_ == 0) {
451                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
452                                            << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
453                                         open_encoding_ = CJK;
454                                         texrow.newline();
455                                 }
456                                 if (encoding->package() != Encoding::none && enc_switch.first) {
457                                         if (enc_switch.second > 0) {
458                                                 // the '%' is necessary to prevent unwanted whitespace
459                                                 os << "%\n";
460                                                 texrow.newline();
461                                         }
462                                         // With CJK, the CJK tag had to be closed first (see above)
463                                         if (runparams.encoding->package() == Encoding::CJK) {
464                                                 os << from_ascii(subst(
465                                                         lyxrc.language_command_begin,
466                                                         "$$lang",
467                                                         par_language->babel()))
468                                                 // the '%' is necessary to prevent unwanted whitespace
469                                                 << "%\n";
470                                                 texrow.newline();
471                                         }
472                                         runparams.encoding = encoding;
473                                 }
474                                 break;
475                         }
476                 }
477         }
478
479         bool const useSetSpace = bparams.documentClass().provides("SetSpace");
480         if (pit->allowParagraphCustomization()) {
481                 if (pit->params().startOfAppendix()) {
482                         os << "\\appendix\n";
483                         texrow.newline();
484                 }
485
486                 if (!pit->params().spacing().isDefault()
487                         && (pit == paragraphs.begin()
488                             || !priorpit->hasSameLayout(*pit)))
489                 {
490                         os << from_ascii(pit->params().spacing().writeEnvirBegin(useSetSpace))
491                             << '\n';
492                         texrow.newline();
493                 }
494
495                 if (style.isCommand()) {
496                         os << '\n';
497                         texrow.newline();
498                 }
499         }
500
501         switch (style.latextype) {
502         case LATEX_COMMAND:
503                 os << '\\' << from_ascii(style.latexname());
504
505                 // Separate handling of optional argument inset.
506                 if (style.optionalargs > 0) {
507                         int ret = latexOptArgInsets(*pit, os, runparams,
508                                                     style.optionalargs);
509                         while (ret > 0) {
510                                 texrow.newline();
511                                 --ret;
512                         }
513                 }
514                 else
515                         os << from_ascii(style.latexparam());
516                 break;
517         case LATEX_ITEM_ENVIRONMENT:
518         case LATEX_LIST_ENVIRONMENT:
519                 os << "\\item ";
520                 break;
521         case LATEX_BIB_ENVIRONMENT:
522                 // ignore this, the inset will write itself
523                 break;
524         default:
525                 break;
526         }
527
528         Font const outerfont = outerFont(distance(paragraphs.begin(), pit),
529                           paragraphs);
530
531         // FIXME UNICODE
532         os << from_utf8(everypar);
533         bool need_par = pit->latex(bparams, outerfont,
534                                              os, texrow, runparams, start_pos, end_pos);
535
536         // Make sure that \\par is done with the font of the last
537         // character if this has another size as the default.
538         // This is necessary because LaTeX (and LyX on the screen)
539         // calculates the space between the baselines according
540         // to this font. (Matthias)
541         //
542         // Is this really needed ? (Dekel)
543         // We do not need to use to change the font for the last paragraph
544         // or for a command.
545
546         Font const font = pit->empty()
547                  ? pit->getLayoutFont(bparams, outerfont)
548                  : pit->getFont(bparams, pit->size() - 1, outerfont);
549
550         bool const is_command = style.isCommand();
551
552         if (style.resfont.size() != font.fontInfo().size()
553             && nextpit != paragraphs.end()
554             && !is_command) {
555                 if (!need_par)
556                         os << '{';
557                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
558         } else if (need_par) {
559                 os << "\\par}";
560         } else if (is_command)
561                 os << '}';
562
563         bool pending_newline = false;
564         switch (style.latextype) {
565         case LATEX_ITEM_ENVIRONMENT:
566         case LATEX_LIST_ENVIRONMENT:
567                 if (nextpit != paragraphs.end()
568                     && (pit->params().depth() < nextpit->params().depth()))
569                         pending_newline = true;
570                 break;
571         case LATEX_ENVIRONMENT: {
572                 // if its the last paragraph of the current environment
573                 // skip it otherwise fall through
574                 if (nextpit != paragraphs.end() && 
575                     (nextpit->layout() != pit->layout()
576                      || nextpit->params().depth() != pit->params().depth()))
577                         break;
578         }
579
580         // fall through possible
581         default:
582                 // we don't need it for the last paragraph!!!
583                 if (nextpit != paragraphs.end())
584                         pending_newline = true;
585         }
586
587         if (pit->allowParagraphCustomization()) {
588                 if (!pit->params().spacing().isDefault()
589                         && (nextpit == paragraphs.end() || !nextpit->hasSameLayout(*pit)))
590                 {
591                         if (pending_newline) {
592                                 os << '\n';
593                                 texrow.newline();
594                         }
595                         os << from_ascii(pit->params().spacing().writeEnvirEnd(useSetSpace));
596                         pending_newline = true;
597                 }
598         }
599
600         // Closing the language is needed for the last paragraph; it is also
601         // needed if we're within an \L or \R that we may have opened above (not
602         // necessarily in this paragraph) and are about to close.
603         bool closing_rtl_ltr_environment =
604                 // not for ArabTeX
605                 (par_language->lang() != "arabic_arabtex" &&
606                  outer_language->lang() != "arabic_arabtex") &&
607                 // have we opened and \L or \R environment?
608                 runparams.local_font != 0 &&
609                 runparams.local_font->isRightToLeft() != par_language->rightToLeft() &&
610                 // are we about to close the language?
611                 ((nextpit != paragraphs.end() &&
612                   par_language->babel() !=
613                     (nextpit->getParLanguage(bparams))->babel()) ||
614                   (nextpit == paragraphs.end() &&
615                     par_language->babel() != outer_language->babel()));
616
617         if (closing_rtl_ltr_environment || (nextpit == paragraphs.end()
618             && par_language->babel() != outer_language->babel())) {
619                 // Since \selectlanguage write the language to the aux file,
620                 // we need to reset the language at the end of footnote or
621                 // float.
622
623                 if (pending_newline) {
624                         os << '\n';
625                         texrow.newline();
626                 }
627                 // when the paragraph uses CJK, the language has to be closed earlier
628                 if (font.language()->encoding()->package() != Encoding::CJK) {
629                         if (lyxrc.language_command_end.empty()) {
630                                 if (!prev_language->babel().empty()) {
631                                         os << from_ascii(subst(
632                                                 lyxrc.language_command_begin,
633                                                 "$$lang",
634                                                 prev_language->babel()));
635                                         pending_newline = true;
636                                 }
637                         } else if (!par_language->babel().empty()) {
638                                 os << from_ascii(subst(
639                                         lyxrc.language_command_end,
640                                         "$$lang",
641                                         par_language->babel()));
642                                 pending_newline = true;
643                         }
644                 }
645         }
646         if (closing_rtl_ltr_environment)
647                 os << "}";
648
649         if (pending_newline) {
650                 os << '\n';
651                 texrow.newline();
652         }
653
654         // if this is a CJK-paragraph and the next isn't, close CJK
655         // also if the next paragraph is a multilingual environment (because of nesting)
656         if (nextpit != paragraphs.end() && open_encoding_ == CJK &&
657             (nextpit->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
658              (nextpit->layout().isEnvironment() && nextpit->isMultiLingual(bparams)))
659              // inbetween environments, CJK has to be closed later (nesting!)
660              && (!style.isEnvironment() || !nextpit->layout().isEnvironment())) {
661                 os << "\\end{CJK}\n";
662                 open_encoding_ = none;
663         }
664
665         // If this is the last paragraph, close the CJK environment
666         // if necessary. If it's an environment, we'll have to \end that first.
667         if (nextpit == paragraphs.end() && !style.isEnvironment()) {
668                 switch (open_encoding_) {
669                         case CJK: {
670                                 // do nothing at the end of child documents
671                                 if (maintext && buf.masterBuffer() != &buf)
672                                         break;
673                                 // end of main text
674                                 if (maintext) {
675                                         os << '\n';
676                                         texrow.newline();
677                                         os << "\\end{CJK}\n";
678                                         texrow.newline();
679                                 // end of an inset
680                                 } else
681                                         os << "\\end{CJK}";
682                                 open_encoding_ = none;
683                                 break;
684                         }
685                         case inputenc: {
686                                 os << "\\egroup";
687                                 open_encoding_ = none;
688                                 break;
689                         }
690                         case none:
691                         default:
692                                 // do nothing
693                                 break;
694                 }
695         }
696
697         // If this is the last paragraph, and a local_font was set upon entering
698         // the inset, and we're using "auto" or "default" encoding, the encoding
699         // should be set back to that local_font's encoding.
700         if (nextpit == paragraphs.end() && runparams_in.local_font != 0
701             && runparams_in.encoding != runparams_in.local_font->language()->encoding()
702             && (bparams.inputenc == "auto" || bparams.inputenc == "default")) {
703                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
704                 os << setEncoding(runparams_in.encoding->iconvName());
705         }
706         // Otherwise, the current encoding should be set for the next paragraph.
707         else
708                 runparams_in.encoding = runparams.encoding;
709
710
711         // we don't need a newline for the last paragraph!!!
712         // Note from JMarc: we will re-add a \n explicitly in
713         // TeXEnvironment, because it is needed in this case
714         if (nextpit != paragraphs.end()) {
715                 Layout const & next_layout = nextpit->layout();
716                 if (style == next_layout
717                     // no blank lines before environments!
718                     || !next_layout.isEnvironment()
719                     // unless there's a depth change
720                     // FIXME What we really want to do here is put every \begin and \end
721                     // tag on a new line (which was not the case with nested environments).
722                     // But in the present state of play, we don't have access to the
723                     // information whether the current TeX row is empty or not.
724                     // For some ideas about how to fix this, see this thread:
725                     // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg145787.html
726                     || nextpit->params().depth() != pit->params().depth()) {
727                         os << '\n';
728                         texrow.newline();
729                 }
730         }
731
732         if (nextpit != paragraphs.end())
733                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*nextpit);
734
735         return nextpit;
736 }
737
738
739 // LaTeX all paragraphs
740 void latexParagraphs(Buffer const & buf,
741                      Text const & text,
742                      odocstream & os,
743                      TexRow & texrow,
744                      OutputParams const & runparams,
745                      string const & everypar)
746 {
747         bool was_title = false;
748         bool already_title = false;
749         BufferParams const & bparams = buf.params();
750         DocumentClass const & tclass = bparams.documentClass();
751         ParagraphList const & paragraphs = text.paragraphs();
752         ParagraphList::const_iterator par = paragraphs.begin();
753         ParagraphList::const_iterator endpar = paragraphs.end();
754
755         LASSERT(runparams.par_begin <= runparams.par_end, /**/);
756         // if only part of the paragraphs will be outputed
757         if (runparams.par_begin !=  runparams.par_end) {
758                 par = boost::next(paragraphs.begin(), runparams.par_begin);
759                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
760                 // runparams will be passed to nested paragraphs, so
761                 // we have to reset the range parameters.
762                 const_cast<OutputParams&>(runparams).par_begin = 0;
763                 const_cast<OutputParams&>(runparams).par_end = 0;
764         }
765
766         bool const maintext = text.isMainText(buf);
767         bool const is_child = buf.masterBuffer() != &buf;
768
769         // Open a CJK environment at the beginning of the main buffer
770         // if the document's language is a CJK language
771         // (but not in child documents)
772         if (maintext && !is_child
773             && bparams.encoding().package() == Encoding::CJK) {
774                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
775                 << "}{" << from_ascii(bparams.fontsCJK) << "}%\n";
776                 texrow.newline();
777                 open_encoding_ = CJK;
778         }
779         // if "auto begin" is switched off, explicitely switch the
780         // language on at start
781         if (maintext && !lyxrc.language_auto_begin &&
782             !bparams.language->babel().empty()) {
783                 // FIXME UNICODE
784                 os << from_utf8(subst(lyxrc.language_command_begin,
785                                         "$$lang",
786                                         bparams.language->babel()))
787                         << '\n';
788         texrow.newline();
789         }
790
791         ParagraphList::const_iterator lastpar;
792         // if only_body
793         while (par != endpar) {
794                 lastpar = par;
795                 // FIXME This check should not be needed. We should
796                 // perhaps issue an error if it is.
797                 Layout const & layout = par->forcePlainLayout() ?
798                                 tclass.plainLayout() : par->layout();
799
800                 if (layout.intitle) {
801                         if (already_title) {
802                                 lyxerr << "Error in latexParagraphs: You"
803                                         " should not mix title layouts"
804                                         " with normal ones." << endl;
805                         } else if (!was_title) {
806                                 was_title = true;
807                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
808                                         os << "\\begin{"
809                                                         << from_ascii(tclass.titlename())
810                                                         << "}\n";
811                                         texrow.newline();
812                                 }
813                         }
814                 } else if (was_title && !already_title) {
815                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
816                                 os << "\\end{" << from_ascii(tclass.titlename())
817                                                 << "}\n";
818                         }
819                         else {
820                                 os << "\\" << from_ascii(tclass.titlename())
821                                                 << "\n";
822                         }
823                         texrow.newline();
824                         already_title = true;
825                         was_title = false;
826                 }
827
828                 if (layout.isEnvironment() ||
829                                         !par->params().leftIndent().zero()) {
830                         par = TeXEnvironment(buf, text, par, os,
831                                                                 texrow, runparams);
832                 } else {
833                         par = TeXOnePar(buf, text, par, os, texrow,
834                                         runparams, everypar);
835                 }
836                 if (distance(lastpar, par) >= distance(lastpar, endpar))
837                         break;
838         }
839
840         // It might be that we only have a title in this document
841         if (was_title && !already_title) {
842                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
843                         os << "\\end{" << from_ascii(tclass.titlename())
844                             << "}\n";
845                 }
846                 else {
847                         os << "\\" << from_ascii(tclass.titlename())
848                             << "\n";
849                                 }
850                 texrow.newline();
851         }
852
853         // if "auto end" is switched off, explicitely close the language at the end
854         // but only if the last par is in a babel language
855         if (maintext && !lyxrc.language_auto_end && !bparams.language->babel().empty() &&
856                 lastpar->getParLanguage(bparams)->encoding()->package() != Encoding::CJK) {
857                 os << from_utf8(subst(lyxrc.language_command_end,
858                                         "$$lang",
859                                         bparams.language->babel()))
860                         << '\n';
861                 texrow.newline();
862         }
863
864         // If the last paragraph is an environment, we'll have to close
865         // CJK at the very end to do proper nesting.
866         if (maintext && !is_child && open_encoding_ == CJK) {
867                 os << "\\end{CJK}\n";
868                 texrow.newline();
869                 open_encoding_ = none;
870         }
871
872         // reset inherited encoding
873         if (cjk_inherited_ > 0) {
874                 cjk_inherited_ -= 1;
875                 if (cjk_inherited_ == 0)
876                         open_encoding_ = CJK;
877         }
878 }
879
880
881 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
882                    OutputParams const & runparams, Encoding const & newEnc,
883                    bool force)
884 {
885         Encoding const & oldEnc = *runparams.encoding;
886         bool moving_arg = runparams.moving_arg;
887         if (!force && ((bparams.inputenc != "auto" && bparams.inputenc != "default")
888                 || moving_arg))
889                 return make_pair(false, 0);
890
891         // Do nothing if the encoding is unchanged.
892         if (oldEnc.name() == newEnc.name())
893                 return make_pair(false, 0);
894
895         // FIXME We ignore encoding switches from/to encodings that do
896         // neither support the inputenc package nor the CJK package here.
897         // This does of course only work in special cases (e.g. switch from
898         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
899         // but it is the best we can do
900         if (oldEnc.package() == Encoding::none
901                 || newEnc.package() == Encoding::none)
902                 return make_pair(false, 0);
903
904         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
905                 << oldEnc.name() << " to " << newEnc.name());
906         os << setEncoding(newEnc.iconvName());
907         if (bparams.inputenc == "default")
908                 return make_pair(true, 0);
909
910         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
911         switch (newEnc.package()) {
912                 case Encoding::none:
913                 case Encoding::japanese:
914                         // shouldn't ever reach here, see above
915                         return make_pair(true, 0);
916                 case Encoding::inputenc: {
917                         int count = inputenc_arg.length();
918                         if (oldEnc.package() == Encoding::CJK &&
919                             open_encoding_ == CJK) {
920                                 os << "\\end{CJK}";
921                                 open_encoding_ = none;
922                                 count += 9;
923                         }
924                         else if (oldEnc.package() == Encoding::inputenc &&
925                                  open_encoding_ == inputenc) {
926                                 os << "\\egroup";
927                                 open_encoding_ = none;
928                                 count += 7;
929                         }
930                         if (runparams.local_font != 0
931                             &&  oldEnc.package() == Encoding::CJK) {
932                                 // within insets, \inputenc switches need
933                                 // to be embraced within \bgroup...\egroup;
934                                 // else CJK fails.
935                                 os << "\\bgroup";
936                                 count += 7;
937                                 open_encoding_ = inputenc;
938                         }
939                         // with the japanese option, inputenc is omitted.
940                         if (runparams.use_japanese)
941                                 return make_pair(true, count);
942                         os << "\\inputencoding{" << inputenc_arg << '}';
943                         return make_pair(true, count + 16);
944                 }
945                 case Encoding::CJK: {
946                         int count = inputenc_arg.length();
947                         if (oldEnc.package() == Encoding::CJK &&
948                             open_encoding_ == CJK) {
949                                 os << "\\end{CJK}";
950                                 count += 9;
951                         }
952                         if (oldEnc.package() == Encoding::inputenc &&
953                             open_encoding_ == inputenc) {
954                                 os << "\\egroup";
955                                 count += 7;
956                         }
957                         os << "\\begin{CJK}{" << inputenc_arg << "}{"
958                            << from_ascii(bparams.fontsCJK) << "}";
959                         open_encoding_ = CJK;
960                         return make_pair(true, count + 15);
961                 }
962         }
963         // Dead code to avoid a warning:
964         return make_pair(true, 0);
965
966 }
967
968 } // namespace lyx