]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
fix a visual cursor edge-case:
[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/debug.h"
34 #include "support/lstrings.h"
35
36 #include <boost/next_prior.hpp>
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42
43 namespace {
44
45
46 enum OpenEncoding {
47                 none,
48                 inputenc,
49                 CJK
50         };
51
52 static int open_encoding_ = none;
53 static bool cjk_inherited_ = false;
54
55
56 ParagraphList::const_iterator
57 TeXEnvironment(Buffer const & buf,
58                Text const & text,
59                ParagraphList::const_iterator pit,
60                odocstream & os, TexRow & texrow,
61                OutputParams const & runparams);
62
63 ParagraphList::const_iterator
64 TeXOnePar(Buffer const & buf,
65           Text const & text,
66           ParagraphList::const_iterator pit,
67           odocstream & os, TexRow & texrow,
68           OutputParams const & runparams,
69           string const & everypar = string());
70
71
72 ParagraphList::const_iterator
73 TeXDeeper(Buffer const & buf,
74           Text const & text,
75           ParagraphList::const_iterator pit,
76           odocstream & os, TexRow & texrow,
77           OutputParams const & runparams)
78 {
79         LYXERR(Debug::LATEX, "TeXDeeper...     " << &*pit);
80         ParagraphList::const_iterator par = pit;
81
82         ParagraphList const & paragraphs = text.paragraphs();
83
84         while (par != paragraphs.end() &&
85                      par->params().depth() == pit->params().depth()) {
86                 if (par->layout()->isEnvironment()) {
87                         par = TeXEnvironment(buf, text, par,
88                                              os, texrow, runparams);
89                 } else {
90                         par = TeXOnePar(buf, text, par,
91                                              os, texrow, runparams);
92                 }
93         }
94         LYXERR(Debug::LATEX, "TeXDeeper...done ");
95
96         return par;
97 }
98
99
100 ParagraphList::const_iterator
101 TeXEnvironment(Buffer const & buf,
102                Text const & text,
103                ParagraphList::const_iterator pit,
104                odocstream & os, TexRow & texrow,
105                OutputParams const & runparams)
106 {
107         LYXERR(Debug::LATEX, "TeXEnvironment...     " << &*pit);
108
109         BufferParams const & bparams = buf.params();
110
111         LayoutPtr const & style = pit->forceEmptyLayout() ?
112                         bparams.textClass().emptyLayout() : pit->layout();
113
114         ParagraphList const & paragraphs = text.paragraphs();
115
116         Language const * const par_language = pit->getParLanguage(bparams);
117         Language const * const doc_language = bparams.language;
118         Language const * const prev_par_language =
119                 (pit != paragraphs.begin())
120                 ? boost::prior(pit)->getParLanguage(bparams)
121                 : doc_language;
122         if (par_language->babel() != prev_par_language->babel()) {
123
124                 if (!lyxrc.language_command_end.empty() &&
125                     prev_par_language->babel() != doc_language->babel() &&
126                     !prev_par_language->babel().empty()) {
127                         os << from_ascii(subst(
128                                 lyxrc.language_command_end,
129                                 "$$lang",
130                                 prev_par_language->babel()))
131                            // the '%' is necessary to prevent unwanted whitespace
132                            << "%\n";
133                         texrow.newline();
134                 }
135
136                 if ((lyxrc.language_command_end.empty() ||
137                      par_language->babel() != doc_language->babel()) &&
138                     !par_language->babel().empty()) {
139                         os << from_ascii(subst(
140                                 lyxrc.language_command_begin,
141                                 "$$lang",
142                                 par_language->babel()))
143                            // the '%' is necessary to prevent unwanted whitespace
144                            << "%\n";
145                         texrow.newline();
146                 }
147         }
148
149         bool leftindent_open = false;
150         if (!pit->params().leftIndent().zero()) {
151                 os << "\\begin{LyXParagraphLeftIndent}{"
152                    << from_ascii(pit->params().leftIndent().asLatexString())
153                    << "}\n";
154                 texrow.newline();
155                 leftindent_open = true;
156         }
157
158         if (style->isEnvironment()) {
159                 os << "\\begin{" << from_ascii(style->latexname()) << '}';
160                 if (style->optionalargs > 0) {
161                         int ret = latexOptArgInsets(buf, *pit, os, runparams,
162                                                     style->optionalargs);
163                         while (ret > 0) {
164                                 texrow.newline();
165                                 --ret;
166                         }
167                 }
168                 if (style->latextype == LATEX_LIST_ENVIRONMENT) {
169                         os << '{'
170                            << pit->params().labelWidthString()
171                            << "}\n";
172                 } else if (style->labeltype == LABEL_BIBLIO) {
173                         // ale970405
174                         os << '{' << bibitemWidest(buf) << "}\n";
175                 } else
176                         os << from_ascii(style->latexparam()) << '\n';
177                 texrow.newline();
178         }
179
180         // in multilingual environments, the CJK tags have to be nested properly
181         bool cjk_nested = false;
182         if (par_language->encoding()->package() == Encoding::CJK &&
183             open_encoding_ != CJK && pit->isMultiLingual(bparams)) {
184                 os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
185                    << "}{}%\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
208                                 // There should be at least one '\n' already
209                                 // but we need there to be two for Standard
210                                 // paragraphs that are depth-increment'ed to be
211                                 // output correctly.  However, tables can
212                                 // also be paragraphs so don't adjust them.
213                                 // ARRae
214                                 // Thinkee:
215                                 // Will it ever harm to have one '\n' too
216                                 // many? i.e. that we sometimes will have
217                                 // three in a row. (Lgb)
218                                 os << '\n';
219                                 texrow.newline();
220                         }
221                         par = TeXDeeper(buf, text, par, os, texrow,
222                                         runparams);
223                 }
224         } while (par != paragraphs.end()
225                  && par->layout() == pit->layout()
226                  && par->params().depth() == pit->params().depth()
227                  && par->params().leftIndent() == pit->params().leftIndent());
228
229         if (open_encoding_ == CJK && cjk_nested) {
230                 // We need to close the encoding even if it does not change
231                 // to do correct environment nesting
232                 os << "\\end{CJK}\n";
233                 texrow.newline();
234                 open_encoding_ = none;
235         }
236
237         if (style->isEnvironment()) {
238                 os << "\\end{" << from_ascii(style->latexname()) << "}\n";
239                 texrow.newline();
240         }
241
242         if (leftindent_open) {
243                 os << "\\end{LyXParagraphLeftIndent}\n";
244                 texrow.newline();
245         }
246
247         if (par != paragraphs.end())
248                 LYXERR(Debug::LATEX, "TeXEnvironment...done " << &*par);
249
250         return par;
251 }
252
253 }
254
255
256 int latexOptArgInsets(Buffer const & buf, Paragraph const & par,
257                       odocstream & os, OutputParams const & runparams, int number)
258 {
259         int lines = 0;
260
261         InsetList::const_iterator it = par.insetList().begin();
262         InsetList::const_iterator end = par.insetList().end();
263         for (; it != end && number > 0 ; ++it) {
264                 if (it->inset->lyxCode() == OPTARG_CODE) {
265                         InsetOptArg * ins =
266                                 static_cast<InsetOptArg *>(it->inset);
267                         lines += ins->latexOptional(buf, os, runparams);
268                         --number;
269                 }
270         }
271         return lines;
272 }
273
274
275 namespace {
276
277 ParagraphList::const_iterator
278 TeXOnePar(Buffer const & buf,
279           Text const & text,
280           ParagraphList::const_iterator pit,
281           odocstream & os, TexRow & texrow,
282           OutputParams const & runparams_in,
283           string const & everypar)
284 {
285         LYXERR(Debug::LATEX, "TeXOnePar...     " << &*pit << " '"
286                 << everypar << "'");
287         BufferParams const & bparams = buf.params();
288         ParagraphList const & paragraphs = text.paragraphs();
289
290         if (runparams_in.verbatim) {
291                 int const dist = distance(paragraphs.begin(), pit);
292                 Font const outerfont = outerFont(dist, paragraphs);
293
294                 // No newline if only one paragraph in this lyxtext
295                 if (dist > 0) {
296                         os << '\n';
297                         texrow.newline();
298                 }
299
300                 /*bool need_par = */ pit->latex(buf, bparams, outerfont,
301                         os, texrow, runparams_in);
302
303                 return ++pit;
304         }
305
306         // FIXME This comment doesn't make sense. What's the
307         // length got to do with forceEmptyLayout()? I.e., what
308         // was forceDefaultParagraphs()?
309         // In an inset with unlimited length (all in one row),
310         // force layout to default
311         LayoutPtr const style = pit->forceEmptyLayout() ?
312                 bparams.textClass().emptyLayout() : pit->layout();
313
314         OutputParams runparams = runparams_in;
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         if (pit == paragraphs.begin() && !maintext && open_encoding_ == CJK) {
320                 cjk_inherited_ = true;
321                 open_encoding_ = none;
322         }
323
324         // This paragraph's language
325         Language const * const par_language = pit->getParLanguage(bparams);
326         // The document's language
327         Language const * const doc_language = bparams.language;
328         // The language that was in effect when the environment this paragraph is 
329         // inside of was opened
330         Language const * const outer_language = 
331                 (runparams.local_font != 0) ?
332                         runparams.local_font->language() : doc_language;
333         // The previous language that was in effect is either the language of
334         // the previous paragraph, if there is one, or else the outer language
335         // if there is no previous paragraph
336         Language const * const prev_language =
337                 (pit != paragraphs.begin()) ?
338                         boost::prior(pit)->getParLanguage(bparams) : outer_language;
339
340         if (par_language->babel() != prev_language->babel()
341             // check if we already put language command in TeXEnvironment()
342             && !(style->isEnvironment()
343                  && (pit == paragraphs.begin() ||
344                      (boost::prior(pit)->layout() != pit->layout() &&
345                       boost::prior(pit)->getDepth() <= pit->getDepth())
346                      || boost::prior(pit)->getDepth() < pit->getDepth())))
347         {
348                 if (!lyxrc.language_command_end.empty() &&
349                     prev_language->babel() != outer_language->babel() &&
350                     !prev_language->babel().empty())
351                 {
352                         os << from_ascii(subst(lyxrc.language_command_end,
353                                 "$$lang",
354                                 prev_language->babel()))
355                            // the '%' is necessary to prevent unwanted whitespace
356                            << "%\n";
357                         texrow.newline();
358                 }
359
360                 // We need to open a new language if we couldn't close the previous 
361                 // one (because there's no language_command_end); and even if we closed
362                 // the previous one, if the current language is different than the
363                 // outer_language (which is currently in effect once the previous one
364                 // is closed).
365                 if ((lyxrc.language_command_end.empty() ||
366                      par_language->babel() != outer_language->babel()) &&
367                     !par_language->babel().empty()) {
368                         // If we're inside an inset, and that inset is within an \L or \R
369                         // (or equivalents), then within the inset, too, any opposite
370                         // language paragraph should appear within an \L or \R (in addition
371                         // to, outside of, the normal language switch commands).
372                         // This behavior is not correct for ArabTeX, though.
373                         if (    // not for ArabTeX
374                                         (par_language->lang() != "arabic_arabtex" &&
375                                          outer_language->lang() != "arabic_arabtex") &&
376                                         // are we in an inset?
377                                         runparams.local_font != 0 &&
378                                         // is the inset within an \L or \R?
379                                         // 
380                                         // FIXME: currently, we don't check this; this means that
381                                         // we'll have unnnecessary \L and \R commands, but that 
382                                         // doesn't seem to hurt (though latex will complain)
383                                         // 
384                                         // is this paragraph in the opposite direction?
385                                         runparams.local_font->isRightToLeft() !=
386                                                 par_language->rightToLeft()
387                                 ) {
388                                 // FIXME: I don't have a working copy of the Arabi package, so
389                                 // I'm not sure if the farsi and arabic_arabi stuff is correct
390                                 // or not...
391                                 if (par_language->lang() == "farsi")
392                                         os << "\\textFR{";
393                                 else if (outer_language->lang() == "farsi")
394                                         os << "\\textLR{";
395                                 else if (par_language->lang() == "arabic_arabi")
396                                         os << "\\textAR{";
397                                 else if (outer_language->lang() == "arabic_arabi")
398                                         os << "\\textLR{";
399                                 // remaining RTL languages currently is hebrew
400                                 else if (par_language->rightToLeft())
401                                         os << "\\R{";
402                                 else
403                                         os << "\\L{";
404                         }
405                         // With CJK, the CJK tag has to be closed first (see below)
406                         if (runparams.encoding->package() != Encoding::CJK) {
407                                 os << from_ascii(subst(
408                                         lyxrc.language_command_begin,
409                                         "$$lang",
410                                         par_language->babel()))
411                                    // the '%' is necessary to prevent unwanted whitespace
412                                    << "%\n";
413                                 texrow.newline();
414                         }
415                 }
416         }
417
418         // Switch file encoding if necessary; no need to do this for "default"
419         // encoding, since this only affects the position of the outputted
420         // \inputencoding command; the encoding switch will occur when necessary
421         if (bparams.inputenc == "auto" &&
422             runparams.encoding->package() != Encoding::none) {
423                 // Look ahead for future encoding changes.
424                 // We try to output them at the beginning of the paragraph,
425                 // since the \inputencoding command is not allowed e.g. in
426                 // sections.
427                 for (pos_type i = 0; i < pit->size(); ++i) {
428                         char_type const c = pit->getChar(i);
429                         Encoding const * const encoding =
430                                 pit->getFontSettings(bparams, i).language()->encoding();
431                         if (encoding->package() != Encoding::CJK &&
432                             runparams.encoding->package() == Encoding::inputenc &&
433                             c < 0x80)
434                                 continue;
435                         if (pit->isInset(i))
436                                 break;
437                         // All characters before c are in the ASCII range, and
438                         // c is non-ASCII (but no inset), so change the
439                         // encoding to that required by the language of c.
440                         // With CJK, only add switch if we have CJK content at the beginning
441                         // of the paragraph
442                         if (encoding->package() != Encoding::CJK || i == 0) {
443                                 OutputParams tmp_rp = runparams;
444                                 runparams.moving_arg = false;
445                                 pair<bool, int> enc_switch = switchEncoding(os, bparams, runparams,
446                                         *encoding);
447                                 runparams = tmp_rp;
448                                 // the following is necessary after a CJK environment in a multilingual
449                                 // context (nesting issue).
450                                 if (par_language->encoding()->package() == Encoding::CJK &&
451                                     open_encoding_ != CJK && !cjk_inherited_) {
452                                         os << "\\begin{CJK}{" << from_ascii(par_language->encoding()->latexName())
453                                            << "}{}%\n";
454                                         open_encoding_ = CJK;
455                                         texrow.newline();
456                                 }
457                                 if (encoding->package() != Encoding::none && enc_switch.first) {
458                                         if (enc_switch.second > 0) {
459                                                 // the '%' is necessary to prevent unwanted whitespace
460                                                 os << "%\n";
461                                                 texrow.newline();
462                                         }
463                                         // With CJK, the CJK tag had to be closed first (see above)
464                                         if (runparams.encoding->package() == Encoding::CJK) {
465                                                 os << from_ascii(subst(
466                                                         lyxrc.language_command_begin,
467                                                         "$$lang",
468                                                         par_language->babel()))
469                                                 // the '%' is necessary to prevent unwanted whitespace
470                                                 << "%\n";
471                                                 texrow.newline();
472                                         }
473                                         runparams.encoding = encoding;
474                                 }
475                                 break;
476                         }
477                 }
478         }
479
480         bool const useSetSpace = bparams.textClass().provides("SetSpace");
481         if (pit->allowParagraphCustomization()) {
482                 if (pit->params().startOfAppendix()) {
483                         os << "\\appendix\n";
484                         texrow.newline();
485                 }
486
487                 if (!pit->params().spacing().isDefault()
488                         && (pit == paragraphs.begin()
489                             || !boost::prior(pit)->hasSameLayout(*pit)))
490                 {
491                         os << from_ascii(pit->params().spacing().writeEnvirBegin(useSetSpace))
492                             << '\n';
493                         texrow.newline();
494                 }
495
496                 if (style->isCommand()) {
497                         os << '\n';
498                         texrow.newline();
499                 }
500         }
501
502         switch (style->latextype) {
503         case LATEX_COMMAND:
504                 os << '\\' << from_ascii(style->latexname());
505
506                 // Separate handling of optional argument inset.
507                 if (style->optionalargs > 0) {
508                         int ret = latexOptArgInsets(buf, *pit, os, runparams,
509                                                     style->optionalargs);
510                         while (ret > 0) {
511                                 texrow.newline();
512                                 --ret;
513                         }
514                 }
515                 else
516                         os << from_ascii(style->latexparam());
517                 break;
518         case LATEX_ITEM_ENVIRONMENT:
519         case LATEX_LIST_ENVIRONMENT:
520                 os << "\\item ";
521                 break;
522         case LATEX_BIB_ENVIRONMENT:
523                 // ignore this, the inset will write itself
524                 break;
525         default:
526                 break;
527         }
528
529         Font const outerfont =
530                 outerFont(distance(paragraphs.begin(), pit),
531                           paragraphs);
532
533         // FIXME UNICODE
534         os << from_utf8(everypar);
535         bool need_par = pit->latex(buf, bparams, outerfont,
536                                              os, texrow, runparams);
537
538         // Make sure that \\par is done with the font of the last
539         // character if this has another size as the default.
540         // This is necessary because LaTeX (and LyX on the screen)
541         // calculates the space between the baselines according
542         // to this font. (Matthias)
543         //
544         // Is this really needed ? (Dekel)
545         // We do not need to use to change the font for the last paragraph
546         // or for a command.
547
548         Font const font =
549                 (pit->empty()
550                  ? pit->getLayoutFont(bparams, outerfont)
551                  : pit->getFont(bparams, pit->size() - 1, outerfont));
552
553         bool is_command = style->isCommand();
554
555         if (style->resfont.size() != font.fontInfo().size()
556             && boost::next(pit) != paragraphs.end()
557             && !is_command) {
558                 if (!need_par)
559                         os << '{';
560                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
561         } else if (need_par) {
562                 os << "\\par}";
563         } else if (is_command)
564                 os << '}';
565
566         bool pending_newline = false;
567         switch (style->latextype) {
568         case LATEX_ITEM_ENVIRONMENT:
569         case LATEX_LIST_ENVIRONMENT:
570                 if (boost::next(pit) != paragraphs.end()
571                     && (pit->params().depth() < boost::next(pit)->params().depth()))
572                         pending_newline = true;
573                 break;
574         case LATEX_ENVIRONMENT: {
575                 // if its the last paragraph of the current environment
576                 // skip it otherwise fall through
577                 ParagraphList::const_iterator next = boost::next(pit);
578
579                 if (next != paragraphs.end()
580                     && (next->layout() != pit->layout()
581                         || next->params().depth() != pit->params().depth()))
582                         break;
583         }
584
585                 // fall through possible
586         default:
587                 // we don't need it for the last paragraph!!!
588                 if (boost::next(pit) != paragraphs.end())
589                         pending_newline = true;
590         }
591
592         if (pit->allowParagraphCustomization()) {
593                 if (!pit->params().spacing().isDefault()
594                         && (boost::next(pit) == paragraphs.end()
595                             || !boost::next(pit)->hasSameLayout(*pit)))
596                 {
597                         if (pending_newline) {
598                                 os << '\n';
599                                 texrow.newline();
600                         }
601                         os << from_ascii(pit->params().spacing().writeEnvirEnd(useSetSpace));
602                         pending_newline = true;
603                 }
604         }
605
606         // Closing the language is needed for the last paragraph; it is also
607         // needed if we're within an \L or \R that we may have opened above (not
608         // necessarily in this paragraph) and are about to close.
609         bool closing_rtl_ltr_environment = 
610                 // not for ArabTeX
611                 (par_language->lang() != "arabic_arabtex" &&
612                  outer_language->lang() != "arabic_arabtex") &&
613                 // have we opened and \L or \R environment?
614                 runparams.local_font != 0 &&
615                 runparams.local_font->isRightToLeft() != par_language->rightToLeft() &&
616                 // are we about to close the language?
617                 ((boost::next(pit) != paragraphs.end() &&
618                   par_language->babel() != 
619                         (boost::next(pit)->getParLanguage(bparams))->babel()) ||
620                  (boost::next(pit) == paragraphs.end() &&
621                   par_language->babel() != outer_language->babel()));
622
623         if (closing_rtl_ltr_environment || (boost::next(pit) == paragraphs.end()
624             && par_language->babel() != outer_language->babel())) {
625                 // Since \selectlanguage write the language to the aux file,
626                 // we need to reset the language at the end of footnote or
627                 // float.
628
629                 if (pending_newline) {
630                         os << '\n';
631                         texrow.newline();
632                 }
633                 // when the paragraph uses CJK, the language has to be closed earlier
634                 if (font.language()->encoding()->package() != Encoding::CJK) {
635                         if (lyxrc.language_command_end.empty()) {
636                                 if (!prev_language->babel().empty()) {
637                                         os << from_ascii(subst(
638                                                 lyxrc.language_command_begin,
639                                                 "$$lang",
640                                                 prev_language->babel()));
641                                         pending_newline = true;
642                                 }
643                         } else if (!par_language->babel().empty()) {
644                                 os << from_ascii(subst(
645                                         lyxrc.language_command_end,
646                                         "$$lang",
647                                         par_language->babel()));
648                                 pending_newline = true;
649                         }
650                 }
651         }
652         if (closing_rtl_ltr_environment)
653                 os << "}";
654
655         if (pending_newline) {
656                 os << '\n';
657                 texrow.newline();
658         }
659
660         // if this is a CJK-paragraph and the next isn't, close CJK
661         // also if the next paragraph is a multilingual environment (because of nesting)
662         if (boost::next(pit) != paragraphs.end() && open_encoding_ == CJK &&
663             (boost::next(pit)->getParLanguage(bparams)->encoding()->package() != Encoding::CJK ||
664              boost::next(pit)->layout()->isEnvironment() && boost::next(pit)->isMultiLingual(bparams))
665              // in environments, CJK has to be closed later (nesting!)
666              && !style->isEnvironment()) {
667                 os << "\\end{CJK}\n";
668                 open_encoding_ = none;
669         }
670
671         // If this is the last paragraph, close the CJK environment
672         // if necessary. If it's an environment, we'll have to \end that first.
673         if (boost::next(pit) == paragraphs.end() && !style->isEnvironment()) {
674                 switch (open_encoding_) {
675                         case CJK: {
676                                 // end of main text
677                                 if (maintext) {
678                                         os << '\n';
679                                         texrow.newline();
680                                         os << "\\end{CJK}\n";
681                                         texrow.newline();
682                                 // end of an inset
683                                 } else
684                                         os << "\\end{CJK}";
685                                 open_encoding_ = none;
686                                 break;
687                         }
688                         case inputenc: {
689                                 os << "\\egroup";
690                                 open_encoding_ = none;
691                                 break;
692                         }
693                         case none:
694                         default:
695                                 // do nothing
696                                 break;
697                 }
698         }
699
700         // If this is the last paragraph, and a local_font was set upon entering
701         // the inset, the encoding should be set back to that local_font's 
702         // encoding. We don't use switchEncoding(), because no explicit encoding
703         // switch command is needed, since latex will automatically revert to it
704         // when this inset closes.
705         // This switch is only necessary if we're using "auto" or "default" 
706         // encoding. 
707         if (boost::next(pit) == paragraphs.end() && runparams_in.local_font != 0) {
708                 runparams_in.encoding = runparams_in.local_font->language()->encoding();
709                 if (bparams.inputenc == "auto" || bparams.inputenc == "default")
710                         os << setEncoding(runparams_in.encoding->iconvName());
711
712         }
713         // Otherwise, the current encoding should be set for the next paragraph.
714         else
715                 runparams_in.encoding = runparams.encoding;
716
717
718         // we don't need it for the last paragraph!!!
719         // Note from JMarc: we will re-add a \n explicitely in
720         // TeXEnvironment, because it is needed in this case
721         if (boost::next(pit) != paragraphs.end()) {
722                 os << '\n';
723                 texrow.newline();
724         }
725
726         if (boost::next(pit) != paragraphs.end())
727                 LYXERR(Debug::LATEX, "TeXOnePar...done " << &*boost::next(pit));
728
729         return ++pit;
730 }
731
732 } // anon namespace
733
734
735 // LaTeX all paragraphs
736 void latexParagraphs(Buffer const & buf,
737                      Text const & text,
738                      odocstream & os,
739                      TexRow & texrow,
740                      OutputParams const & runparams,
741                      string const & everypar)
742 {
743         bool was_title = false;
744         bool already_title = false;
745         BufferParams const & bparams = buf.params();
746         TextClass const & tclass = bparams.textClass();
747         ParagraphList const & paragraphs = text.paragraphs();
748         ParagraphList::const_iterator par = paragraphs.begin();
749         ParagraphList::const_iterator endpar = paragraphs.end();
750
751         BOOST_ASSERT(runparams.par_begin <= runparams.par_end);
752         // if only part of the paragraphs will be outputed
753         if (runparams.par_begin !=  runparams.par_end) {
754                 par = boost::next(paragraphs.begin(), runparams.par_begin);
755                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
756                 // runparams will be passed to nested paragraphs, so
757                 // we have to reset the range parameters.
758                 const_cast<OutputParams&>(runparams).par_begin = 0;
759                 const_cast<OutputParams&>(runparams).par_end = 0;
760         }
761
762         bool const maintext = text.isMainText(buf);
763
764         // Open a CJK environment at the beginning of the main buffer
765         // if the document's language is a CJK language
766         if (maintext && bparams.encoding().package() == Encoding::CJK) {
767                 os << "\\begin{CJK}{" << from_ascii(bparams.encoding().latexName())
768                 << "}{}%\n";
769                 texrow.newline();
770                 open_encoding_ = CJK;
771         }
772         // if "auto begin" is switched off, explicitely switch the
773         // language on at start
774         if (maintext && !lyxrc.language_auto_begin &&
775             !bparams.language->babel().empty()) {
776                 // FIXME UNICODE
777                 os << from_utf8(subst(lyxrc.language_command_begin,
778                                         "$$lang",
779                                         bparams.language->babel()))
780                         << '\n';
781         texrow.newline();
782         }
783
784         ParagraphList::const_iterator lastpar;
785         // if only_body
786         while (par != endpar) {
787                 lastpar = par;
788                 // well we have to check if we are in an inset with unlimited
789                 // length (all in one row) if that is true then we don't allow
790                 // any special options in the paragraph and also we don't allow
791                 // any environment other than the default layout of the
792                 // text class to be valid!
793                 if (par->allowParagraphCustomization()) {
794                         LayoutPtr const & layout = par->forceEmptyLayout() ?
795                                         tclass.emptyLayout() :
796                                         par->layout();
797
798                         if (layout->intitle) {
799                                 if (already_title) {
800                                         lyxerr << "Error in latexParagraphs: You"
801                                                 " should not mix title layouts"
802                                                 " with normal ones." << endl;
803                                 } else if (!was_title) {
804                                         was_title = true;
805                                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
806                                                 os << "\\begin{"
807                                                     << from_ascii(tclass.titlename())
808                                                     << "}\n";
809                                                 texrow.newline();
810                                         }
811                                 }
812                         } else if (was_title && !already_title) {
813                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
814                                         os << "\\end{" << from_ascii(tclass.titlename())
815                                             << "}\n";
816                                 }
817                                 else {
818                                         os << "\\" << from_ascii(tclass.titlename())
819                                             << "\n";
820                                 }
821                                 texrow.newline();
822                                 already_title = true;
823                                 was_title = false;
824                         }
825
826                         if (layout->is_environment) {
827                                 par = TeXOnePar(buf, text, par, os, texrow,
828                                                 runparams, everypar);
829                         } else if (layout->isEnvironment() ||
830                                    !par->params().leftIndent().zero()) {
831                                 par = TeXEnvironment(buf, text, par, os,
832                                                      texrow, runparams);
833                         } else {
834                                 par = TeXOnePar(buf, text, par, os, texrow,
835                                                 runparams, everypar);
836                         }
837                 } else {
838                         par = TeXOnePar(buf, text, par, os, texrow,
839                                         runparams, everypar);
840                 }
841                 if (distance(lastpar, par) >= distance(lastpar, endpar))
842                         break;
843         }
844         // It might be that we only have a title in this document
845         if (was_title && !already_title) {
846                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
847                         os << "\\end{" << from_ascii(tclass.titlename())
848                             << "}\n";
849                 }
850                 else {
851                         os << "\\" << from_ascii(tclass.titlename())
852                             << "\n";
853                                 }
854                 texrow.newline();
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         // If the last paragraph is an environment, we'll have to close
867         // CJK at the very end to do proper nesting.
868         if (maintext && open_encoding_ == CJK) {
869                 os << "\\end{CJK}\n";
870                 texrow.newline();
871                 open_encoding_ = none;
872         }
873         // reset inherited encoding
874         if (cjk_inherited_) {
875                 open_encoding_ = CJK;
876                 cjk_inherited_ = false;
877         }
878 }
879
880
881 pair<bool, int> switchEncoding(odocstream & os, BufferParams const & bparams,
882                    OutputParams const & runparams, Encoding const & newEnc)
883 {
884         Encoding const oldEnc = *runparams.encoding;
885         bool moving_arg = runparams.moving_arg;
886         if ((bparams.inputenc != "auto" && bparams.inputenc != "default")
887                 || moving_arg)
888                 return make_pair(false, 0);
889
890         // Do nothing if the encoding is unchanged.
891         if (oldEnc.name() == newEnc.name())
892                 return make_pair(false, 0);
893
894         // FIXME We ignore encoding switches from/to encodings that do
895         // neither support the inputenc package nor the CJK package here.
896         // This does of course only work in special cases (e.g. switch from
897         // tis620-0 to latin1, but the text in latin1 contains ASCII only),
898         // but it is the best we can do
899         if (oldEnc.package() == Encoding::none
900                 || newEnc.package() == Encoding::none)
901                 return make_pair(false, 0);
902
903         LYXERR(Debug::LATEX, "Changing LaTeX encoding from "
904                 << oldEnc.name() << " to " << newEnc.name());
905         os << setEncoding(newEnc.iconvName());
906         if (bparams.inputenc == "default")
907                 return make_pair(true, 0);
908
909         docstring const inputenc_arg(from_ascii(newEnc.latexName()));
910         switch (newEnc.package()) {
911                 case Encoding::none:
912                         // shouldn't ever reach here, see above
913                         return make_pair(true, 0);
914                 case Encoding::inputenc: {
915                         int count = inputenc_arg.length();
916                         if (oldEnc.package() == Encoding::CJK &&
917                             open_encoding_ == CJK) {
918                                 os << "\\end{CJK}";
919                                 open_encoding_ = none;
920                                 count += 9;
921                         }
922                         else if (oldEnc.package() == Encoding::inputenc &&
923                                  open_encoding_ == inputenc) {
924                                 os << "\\egroup";
925                                 open_encoding_ = none;
926                                 count += 7;
927                         }
928                         if (runparams.local_font != 0 && oldEnc.package() == Encoding::CJK) {
929                                 // within insets, \inputenc switches need to be 
930                                 // embraced within \bgroup ... \egroup; else CJK fails.
931                                 os << "\\bgroup";
932                                 count += 7;
933                                 open_encoding_ = inputenc;
934                         }
935                         os << "\\inputencoding{" << inputenc_arg << '}';
936                         return make_pair(true, count + 16);
937                 }
938                 case Encoding::CJK: {
939                         int count = inputenc_arg.length();
940                         if (oldEnc.package() == Encoding::CJK && 
941                             open_encoding_ == CJK) {
942                                 os << "\\end{CJK}";
943                                 count += 9;
944                         }
945                         if (oldEnc.package() == Encoding::inputenc && 
946                             open_encoding_ == inputenc) {
947                                 os << "\\egroup";
948                                 count += 7;
949                         }
950                         os << "\\begin{CJK}{" << inputenc_arg << "}{}";
951                         open_encoding_ = CJK;
952                         return make_pair(true, count + 15);
953                 }
954         }
955         // Dead code to avoid a warning:
956         return make_pair(true, 0);
957
958 }
959
960 } // namespace lyx