]> git.lyx.org Git - lyx.git/blob - src/output_latex.cpp
* Cursor::isRTL(): correctly deal with the inner paragraph when within mathed.
[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 "debug.h"
18 #include "Encoding.h"
19 #include "Language.h"
20 #include "LyXRC.h"
21 #include "OutputParams.h"
22 #include "Paragraph.h"
23 #include "paragraph_funcs.h"
24 #include "ParagraphParameters.h"
25 #include "TexRow.h"
26 #include "VSpace.h"
27
28 #include "insets/InsetBibitem.h"
29 #include "insets/InsetOptArg.h"
30
31 #include "support/lstrings.h"
32
33
34 namespace lyx {
35
36 using support::subst;
37
38 using std::endl;
39 using std::string;
40
41
42 namespace {
43
44 ParagraphList::const_iterator
45 TeXEnvironment(Buffer const & buf,
46                ParagraphList const & paragraphs,
47                ParagraphList::const_iterator pit,
48                odocstream & os, TexRow & texrow,
49                OutputParams const & runparams);
50
51 ParagraphList::const_iterator
52 TeXOnePar(Buffer const & buf,
53           ParagraphList const & paragraphs,
54           ParagraphList::const_iterator pit,
55           odocstream & os, TexRow & texrow,
56           OutputParams const & runparams,
57           string const & everypar = string());
58
59
60 ParagraphList::const_iterator
61 TeXDeeper(Buffer const & buf,
62           ParagraphList const & paragraphs,
63           ParagraphList::const_iterator pit,
64           odocstream & os, TexRow & texrow,
65           OutputParams const & runparams)
66 {
67         LYXERR(Debug::LATEX) << "TeXDeeper...     " << &*pit << endl;
68         ParagraphList::const_iterator par = pit;
69
70         while (par != paragraphs.end() &&
71                      par->params().depth() == pit->params().depth()) {
72                 if (par->layout()->isEnvironment()) {
73                         par = TeXEnvironment(buf, paragraphs, par,
74                                              os, texrow, runparams);
75                 } else {
76                         par = TeXOnePar(buf, paragraphs, par,
77                                              os, texrow, runparams);
78                 }
79         }
80         LYXERR(Debug::LATEX) << "TeXDeeper...done " << endl;
81
82         return par;
83 }
84
85
86 ParagraphList::const_iterator
87 TeXEnvironment(Buffer const & buf,
88                ParagraphList const & paragraphs,
89                ParagraphList::const_iterator pit,
90                odocstream & os, TexRow & texrow,
91                OutputParams const & runparams)
92 {
93         LYXERR(Debug::LATEX) << "TeXEnvironment...     " << &*pit << endl;
94
95         BufferParams const & bparams = buf.params();
96
97         Layout_ptr const & style = pit->layout();
98
99         Language const * const par_language = pit->getParLanguage(bparams);
100         Language const * const doc_language = bparams.language;
101         Language const * const prev_par_language =
102                 (pit != paragraphs.begin())
103                 ? boost::prior(pit)->getParLanguage(bparams)
104                 : doc_language;
105         if (par_language->babel() != prev_par_language->babel()) {
106
107                 if (!lyxrc.language_command_end.empty() &&
108                     prev_par_language->babel() != doc_language->babel()) {
109                         os << from_ascii(subst(
110                                 lyxrc.language_command_end,
111                                 "$$lang",
112                                 prev_par_language->babel()))
113                            << '\n';
114                         texrow.newline();
115                 }
116
117                 if (lyxrc.language_command_end.empty() ||
118                     par_language->babel() != doc_language->babel()) {
119                         os << from_ascii(subst(
120                                 lyxrc.language_command_begin,
121                                 "$$lang",
122                                 par_language->babel()))
123                            << '\n';
124                         texrow.newline();
125                 }
126         }
127
128         bool leftindent_open = false;
129         if (!pit->params().leftIndent().zero()) {
130                 os << "\\begin{LyXParagraphLeftIndent}{"
131                    << from_ascii(pit->params().leftIndent().asLatexString())
132                    << "}\n";
133                 texrow.newline();
134                 leftindent_open = true;
135         }
136
137         if (style->isEnvironment()) {
138                 os << "\\begin{" << from_ascii(style->latexname()) << '}';
139                 if (style->optionalargs > 0) {
140                         int ret = latexOptArgInsets(buf, *pit, os, runparams,
141                                                     style->optionalargs);
142                         while (ret > 0) {
143                                 texrow.newline();
144                                 --ret;
145                         }
146                 }
147                 if (style->latextype == LATEX_LIST_ENVIRONMENT) {
148                         os << '{'
149                            << pit->params().labelWidthString()
150                            << "}\n";
151                 } else if (style->labeltype == LABEL_BIBLIO) {
152                         // ale970405
153                         os << '{' << bibitemWidest(buf) << "}\n";
154                 } else
155                         os << from_ascii(style->latexparam()) << '\n';
156                 texrow.newline();
157         }
158         ParagraphList::const_iterator par = pit;
159         do {
160                 par = TeXOnePar(buf, paragraphs, par, os, texrow, runparams);
161
162                 if (par == paragraphs.end()) {
163                         // Make sure that the last paragraph is
164                         // correctly terminated (because TeXOnePar does
165                         // not add a \n in this case)
166                         os << '\n';
167                         texrow.newline();
168                 } else if (par->params().depth() > pit->params().depth()) {
169                             if (par->layout()->isParagraph()) {
170
171                             // Thinko!
172                             // How to handle this? (Lgb)
173                             //&& !suffixIs(os, "\n\n")
174                                     //) {
175                                 // There should be at least one '\n' already
176                                 // but we need there to be two for Standard
177                                 // paragraphs that are depth-increment'ed to be
178                                 // output correctly.  However, tables can
179                                 // also be paragraphs so don't adjust them.
180                                 // ARRae
181                                 // Thinkee:
182                                 // Will it ever harm to have one '\n' too
183                                 // many? i.e. that we sometimes will have
184                                 // three in a row. (Lgb)
185                                 os << '\n';
186                                 texrow.newline();
187                         }
188                         par = TeXDeeper(buf, paragraphs, par, os, texrow,
189                                         runparams);
190                 }
191         } while (par != paragraphs.end()
192                  && par->layout() == pit->layout()
193                  && par->params().depth() == pit->params().depth()
194                  && par->params().leftIndent() == pit->params().leftIndent());
195
196         if (style->isEnvironment()) {
197                 os << "\\end{" << from_ascii(style->latexname()) << "}\n";
198                 texrow.newline();
199         }
200
201         if (leftindent_open) {
202                 os << "\\end{LyXParagraphLeftIndent}\n";
203                 texrow.newline();
204         }
205
206         if (par != paragraphs.end())
207                 LYXERR(Debug::LATEX) << "TeXEnvironment...done " << &*par << endl;
208         return par;
209 }
210
211 }
212
213
214 int latexOptArgInsets(Buffer const & buf, Paragraph const & par,
215                       odocstream & os, OutputParams const & runparams, int number)
216 {
217         int lines = 0;
218
219         InsetList::const_iterator it = par.insetlist.begin();
220         InsetList::const_iterator end = par.insetlist.end();
221         for (; it != end && number > 0 ; ++it) {
222                 if (it->inset->lyxCode() == Inset::OPTARG_CODE) {
223                         InsetOptArg * ins =
224                                 static_cast<InsetOptArg *>(it->inset);
225                         lines += ins->latexOptional(buf, os, runparams);
226                         --number;
227                 }
228         }
229         return lines;
230 }
231
232
233 namespace {
234
235 ParagraphList::const_iterator
236 TeXOnePar(Buffer const & buf,
237           ParagraphList const & paragraphs,
238           ParagraphList::const_iterator pit,
239           odocstream & os, TexRow & texrow,
240           OutputParams const & runparams_in,
241           string const & everypar)
242 {
243         LYXERR(Debug::LATEX) << "TeXOnePar...     " << &*pit << " '"
244                 << everypar << "'" << endl;
245         BufferParams const & bparams = buf.params();
246         Layout_ptr style;
247
248         // In an inset with unlimited length (all in one row),
249         // force layout to default
250         if (!pit->forceDefaultParagraphs())
251                 style = pit->layout();
252         else
253                 style = bparams.getTextClass().defaultLayout();
254
255         OutputParams runparams = runparams_in;
256         runparams.moving_arg |= style->needprotect;
257
258         Language const * const par_language = pit->getParLanguage(bparams);
259         Language const * const doc_language = bparams.language;
260         Language const * const prev_par_language =
261                 (pit != paragraphs.begin())
262                 ? boost::prior(pit)->getParLanguage(bparams)
263                 : doc_language;
264
265         if (par_language->babel() != prev_par_language->babel()
266             // check if we already put language command in TeXEnvironment()
267             && !(style->isEnvironment()
268                  && (pit == paragraphs.begin() ||
269                      (boost::prior(pit)->layout() != pit->layout() &&
270                       boost::prior(pit)->getDepth() <= pit->getDepth())
271                      || boost::prior(pit)->getDepth() < pit->getDepth())))
272         {
273                 if (!lyxrc.language_command_end.empty() &&
274                     prev_par_language->babel() != doc_language->babel())
275                 {
276                         os << from_ascii(subst(lyxrc.language_command_end,
277                                 "$$lang",
278                                 prev_par_language->babel()))
279                            << '\n';
280                         texrow.newline();
281                 }
282
283                 if (lyxrc.language_command_end.empty() ||
284                     par_language->babel() != doc_language->babel())
285                 {
286                         os << from_ascii(subst(
287                                 lyxrc.language_command_begin,
288                                 "$$lang",
289                                 par_language->babel()))
290                            << '\n';
291                         texrow.newline();
292                 }
293         }
294
295         // Switch file encoding if necessary
296         if (bparams.inputenc == "auto") {
297                 // Look ahead for future encoding changes.
298                 // We try to output them at the beginning of the paragraph,
299                 // since the \inputencoding command is not allowed e.g. in
300                 // sections.
301                 for (pos_type i = 0; i < pit->size(); ++i) {
302                         char_type const c = pit->getChar(i);
303                         if (c < 0x80)
304                                 continue;
305                         if (pit->isInset(i))
306                                 break;
307                         // All characters before c are in the ASCII range, and
308                         // c is non-ASCII (but no inset), so change the
309                         // encoding to that required by the language of c.
310                         Encoding const * const encoding =
311                                 pit->getFontSettings(bparams, i).language()->encoding();
312                         if (switchEncoding(os, bparams, false,
313                                            *(runparams.encoding), *encoding) > 0) {
314                                 runparams.encoding = encoding;
315                                 os << '\n';
316                                 texrow.newline();
317                         }
318                         break;
319                 }
320         }
321
322         // In an inset with unlimited length (all in one row),
323         // don't allow any special options in the paragraph
324         if (!pit->forceDefaultParagraphs()) {
325                 if (pit->params().startOfAppendix()) {
326                         os << "\\appendix\n";
327                         texrow.newline();
328                 }
329
330                 if (!pit->params().spacing().isDefault()
331                         && (pit == paragraphs.begin()
332                             || !boost::prior(pit)->hasSameLayout(*pit)))
333                 {
334                         os << from_ascii(pit->params().spacing().writeEnvirBegin())
335                             << '\n';
336                         texrow.newline();
337                 }
338
339                 if (style->isCommand()) {
340                         os << '\n';
341                         texrow.newline();
342                 }
343         }
344
345         switch (style->latextype) {
346         case LATEX_COMMAND:
347                 os << '\\' << from_ascii(style->latexname());
348
349                 // Separate handling of optional argument inset.
350                 if (style->optionalargs > 0) {
351                         int ret = latexOptArgInsets(buf, *pit, os, runparams,
352                                                     style->optionalargs);
353                         while (ret > 0) {
354                                 texrow.newline();
355                                 --ret;
356                         }
357                 }
358                 else
359                         os << from_ascii(style->latexparam());
360                 break;
361         case LATEX_ITEM_ENVIRONMENT:
362         case LATEX_LIST_ENVIRONMENT:
363                 os << "\\item ";
364                 break;
365         case LATEX_BIB_ENVIRONMENT:
366                 // ignore this, the inset will write itself
367                 break;
368         default:
369                 break;
370         }
371
372         Font const outerfont =
373                 outerFont(std::distance(paragraphs.begin(), pit),
374                           paragraphs);
375
376         // FIXME UNICODE
377         os << from_utf8(everypar);
378         bool need_par = pit->simpleTeXOnePar(buf, bparams, outerfont,
379                                              os, texrow, runparams);
380
381         // Make sure that \\par is done with the font of the last
382         // character if this has another size as the default.
383         // This is necessary because LaTeX (and LyX on the screen)
384         // calculates the space between the baselines according
385         // to this font. (Matthias)
386         //
387         // Is this really needed ? (Dekel)
388         // We do not need to use to change the font for the last paragraph
389         // or for a command.
390
391         Font const font =
392                 (pit->empty()
393                  ? pit->getLayoutFont(bparams, outerfont)
394                  : pit->getFont(bparams, pit->size() - 1, outerfont));
395
396         bool is_command = style->isCommand();
397
398         if (style->resfont.size() != font.size()
399             && boost::next(pit) != paragraphs.end()
400             && !is_command) {
401                 if (!need_par)
402                         os << '{';
403                 os << "\\" << from_ascii(font.latexSize()) << " \\par}";
404         } else if (need_par) {
405                 os << "\\par}";
406         } else if (is_command)
407                 os << '}';
408
409         bool pending_newline = false;
410         switch (style->latextype) {
411         case LATEX_ITEM_ENVIRONMENT:
412         case LATEX_LIST_ENVIRONMENT:
413                 if (boost::next(pit) != paragraphs.end()
414                     && (pit->params().depth() < boost::next(pit)->params().depth()))
415                         pending_newline = true;
416                 break;
417         case LATEX_ENVIRONMENT: {
418                 // if its the last paragraph of the current environment
419                 // skip it otherwise fall through
420                 ParagraphList::const_iterator next = boost::next(pit);
421
422                 if (next != paragraphs.end()
423                     && (next->layout() != pit->layout()
424                         || next->params().depth() != pit->params().depth()))
425                         break;
426         }
427
428                 // fall through possible
429         default:
430                 // we don't need it for the last paragraph!!!
431                 if (boost::next(pit) != paragraphs.end())
432                         pending_newline = true;
433         }
434
435         if (!pit->forceDefaultParagraphs()) {
436                 if (!pit->params().spacing().isDefault()
437                         && (boost::next(pit) == paragraphs.end()
438                             || !boost::next(pit)->hasSameLayout(*pit)))
439                 {
440                         if (pending_newline) {
441                                 os << '\n';
442                                 texrow.newline();
443                         }
444                         os << from_ascii(pit->params().spacing().writeEnvirEnd());
445                         pending_newline = true;
446                 }
447         }
448
449         if (boost::next(pit) == paragraphs.end()
450             && par_language->babel() != doc_language->babel()) {
451                 // Since \selectlanguage write the language to the aux file,
452                 // we need to reset the language at the end of footnote or
453                 // float.
454
455                 if (pending_newline) {
456                         os << '\n';
457                         texrow.newline();
458                 }
459                 if (lyxrc.language_command_end.empty())
460                         os << from_ascii(subst(
461                                 lyxrc.language_command_begin,
462                                 "$$lang",
463                                 doc_language->babel()));
464                 else
465                         os << from_ascii(subst(
466                                 lyxrc.language_command_end,
467                                 "$$lang",
468                                 par_language->babel()));
469                 pending_newline = true;
470         }
471
472         if (pending_newline) {
473                 os << '\n';
474                 texrow.newline();
475         }
476         runparams_in.encoding = runparams.encoding;
477
478         // we don't need it for the last paragraph!!!
479         // Note from JMarc: we will re-add a \n explicitely in
480         // TeXEnvironment, because it is needed in this case
481         if (boost::next(pit) != paragraphs.end()) {
482                 os << '\n';
483                 texrow.newline();
484         }
485
486         if (boost::next(pit) != paragraphs.end())
487                 LYXERR(Debug::LATEX) << "TeXOnePar...done " << &*boost::next(pit) << endl;
488
489         return ++pit;
490 }
491
492 } // anon namespace
493
494
495 // LaTeX all paragraphs
496 void latexParagraphs(Buffer const & buf,
497                      ParagraphList const & paragraphs,
498                      odocstream & os,
499                      TexRow & texrow,
500                      OutputParams const & runparams,
501                      string const & everypar)
502 {
503         bool was_title = false;
504         bool already_title = false;
505         TextClass const & tclass = buf.params().getTextClass();
506         ParagraphList::const_iterator par = paragraphs.begin();
507         ParagraphList::const_iterator endpar = paragraphs.end();
508
509         BOOST_ASSERT(runparams.par_begin <= runparams.par_end);
510         // if only part of the paragraphs will be outputed
511         if (runparams.par_begin !=  runparams.par_end) {
512                 par = boost::next(paragraphs.begin(), runparams.par_begin);
513                 endpar = boost::next(paragraphs.begin(), runparams.par_end);
514                 // runparams will be passed to nested paragraphs, so
515                 // we have to reset the range parameters.
516                 const_cast<OutputParams&>(runparams).par_begin = 0;
517                 const_cast<OutputParams&>(runparams).par_end = 0;
518         }
519
520         // if only_body
521         while (par != endpar) {
522                 ParagraphList::const_iterator lastpar = par;
523                 // well we have to check if we are in an inset with unlimited
524                 // length (all in one row) if that is true then we don't allow
525                 // any special options in the paragraph and also we don't allow
526                 // any environment other than the default layout of the
527                 // text class to be valid!
528                 if (!par->forceDefaultParagraphs()) {
529                         Layout_ptr const & layout = par->layout();
530
531                         if (layout->intitle) {
532                                 if (already_title) {
533                                         lyxerr << "Error in latexParagraphs: You"
534                                                 " should not mix title layouts"
535                                                 " with normal ones." << endl;
536                                 } else if (!was_title) {
537                                         was_title = true;
538                                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
539                                                 os << "\\begin{"
540                                                     << from_ascii(tclass.titlename())
541                                                     << "}\n";
542                                                 texrow.newline();
543                                         }
544                                 }
545                         } else if (was_title && !already_title) {
546                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
547                                         os << "\\end{" << from_ascii(tclass.titlename())
548                                             << "}\n";
549                                 }
550                                 else {
551                                         os << "\\" << from_ascii(tclass.titlename())
552                                             << "\n";
553                                 }
554                                 texrow.newline();
555                                 already_title = true;
556                                 was_title = false;
557                         }
558
559                         if (layout->is_environment) {
560                                 par = TeXOnePar(buf, paragraphs, par, os, texrow,
561                                                 runparams, everypar);
562                         } else if (layout->isEnvironment() ||
563                                    !par->params().leftIndent().zero()) {
564                                 par = TeXEnvironment(buf, paragraphs, par, os,
565                                                      texrow, runparams);
566                         } else {
567                                 par = TeXOnePar(buf, paragraphs, par, os, texrow,
568                                                 runparams, everypar);
569                         }
570                 } else {
571                         par = TeXOnePar(buf, paragraphs, par, os, texrow,
572                                         runparams, everypar);
573                 }
574                 if (std::distance(lastpar, par) >= std::distance(lastpar, endpar))
575                         break;
576         }
577         // It might be that we only have a title in this document
578         if (was_title && !already_title) {
579                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
580                         os << "\\end{" << from_ascii(tclass.titlename())
581                             << "}\n";
582                 }
583                 else {
584                         os << "\\" << from_ascii(tclass.titlename())
585                             << "\n";
586                                 }
587                 texrow.newline();
588         }
589 }
590
591
592 int switchEncoding(odocstream & os, BufferParams const & bparams,
593                    bool moving_arg, Encoding const & oldEnc,
594                    Encoding const & newEnc)
595 {
596         // FIXME thailatex does not support the inputenc package, so we
597         // ignore switches from/to tis620-0 encoding here. This does of
598         // course only work as long as the non-thai text contains ASCII
599         // only, but it is the best we can do.
600         // Since the \inputencoding command does not work inside sections
601         // we ignore the encoding switch also in moving arguments.
602         if (((bparams.inputenc == "auto" && !moving_arg) ||
603              bparams.inputenc == "default") &&
604             oldEnc.name() != newEnc.name() &&
605             oldEnc.name() != "ascii" && newEnc.name() != "ascii" &&
606             oldEnc.name() != "tis620-0" && newEnc.name() != "tis620-0") {
607                 LYXERR(Debug::LATEX) << "Changing LaTeX encoding from "
608                                      << oldEnc.name() << " to "
609                                      << newEnc.name() << endl;
610                 os << setEncoding(newEnc.iconvName());
611                 if (bparams.inputenc != "default") {
612                         docstring const inputenc(from_ascii(newEnc.latexName()));
613                         os << "\\inputencoding{" << inputenc << '}';
614                         return 16 + inputenc.length();
615                 }
616         }
617         return 0;
618 }
619
620 } // namespace lyx