]> git.lyx.org Git - lyx.git/blob - src/LaTeXFeatures.cpp
Remember navigate back bookmark through sessions
[lyx.git] / src / LaTeXFeatures.cpp
1 /**
2  * \file LaTeXFeatures.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author José Matos
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Jürgen Vigna
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "LaTeXFeatures.h"
18
19 #include "Buffer.h"
20 #include "BufferParams.h"
21 #include "ColorSet.h"
22 #include "Converter.h"
23 #include "Encoding.h"
24 #include "Floating.h"
25 #include "FloatList.h"
26 #include "Language.h"
27 #include "Layout.h"
28 #include "Lexer.h"
29 #include "LyXRC.h"
30 #include "TextClass.h"
31
32 #include "insets/InsetLayout.h"
33
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/FileName.h"
37 #include "support/filetools.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
40
41 #include <algorithm>
42
43
44 using namespace std;
45 using namespace lyx::support;
46
47
48 namespace lyx {
49
50 /////////////////////////////////////////////////////////////////////
51 //
52 // Strings
53 //
54 /////////////////////////////////////////////////////////////////////
55
56 //\NeedsTeXFormat{LaTeX2e}
57 //\ProvidesPackage{lyx}[1996/01/11 LLE v0.2 (LyX LaTeX Extensions)]
58 //\message{LyX LaTeX Extensions (LLE v0.2) of 11-Jan-1996.}
59
60 static docstring const lyx_def = from_ascii(
61         "\\providecommand{\\LyX}{L\\kern-.1667em\\lower.25em\\hbox{Y}\\kern-.125emX\\@}");
62
63 static docstring const lyxline_def = from_ascii(
64         "\\newcommand{\\lyxline}[1][1pt]{%\n"
65         "  \\par\\noindent%\n"
66         "  \\rule[.5ex]{\\linewidth}{#1}\\par}");
67
68 static docstring const noun_def = from_ascii(
69         "\\newcommand{\\noun}[1]{\\textsc{#1}}");
70
71 static docstring const lyxarrow_def = from_ascii(
72         "\\DeclareRobustCommand*{\\lyxarrow}{%\n"
73         "\\@ifstar\n"
74         "{\\leavevmode\\,$\\triangleleft$\\,\\allowbreak}\n"
75         "{\\leavevmode\\,$\\triangleright$\\,\\allowbreak}}");
76
77 // for quotes without babel. This does not give perfect results, but
78 // anybody serious about non-english quotes should use babel (JMarc).
79
80 static docstring const quotedblbase_def = from_ascii(
81         "\\ProvideTextCommandDefault{\\quotedblbase}{%\n"
82         "  \\raisebox{-1.4ex}[1ex][.5ex]{\\textquotedblright}%\n"
83         "  \\penalty10000\\hskip0em\\relax%\n"
84         "}");
85
86 static docstring const quotesinglbase_def = from_ascii(
87         "\\ProvideTextCommandDefault{\\quotesinglbase}{%\n"
88         "  \\raisebox{-1.4ex}[1ex][.5ex]{\\textquoteright}%\n"
89         "  \\penalty10000\\hskip0em\\relax%\n"
90         "}");
91
92 static docstring const guillemotleft_def = from_ascii(
93         "\\ProvideTextCommandDefault{\\guillemotleft}{%\n"
94         "  {\\usefont{U}{lasy}{m}{n}\\char'50\\kern-.15em\\char'50}%\n"
95         "\\penalty10000\\hskip0pt\\relax%\n"
96         "}");
97
98 static docstring const guillemotright_def = from_ascii(
99         "\\ProvideTextCommandDefault{\\guillemotright}{%\n"
100         "  \\penalty10000\\hskip0pt%\n"
101         "  {\\usefont{U}{lasy}{m}{n}\\char'51\\kern-.15em\\char'51}%\n"
102         "}");
103
104 static docstring const guilsinglleft_def = from_ascii(
105         "\\ProvideTextCommandDefault{\\guilsinglleft}{%\n"
106         "  {\\usefont{U}{lasy}{m}{n}\\char'50}%\n"
107         "  \\penalty10000\\hskip0pt\\relax%\n"
108         "}");
109
110 static docstring const guilsinglright_def = from_ascii(
111         "\\ProvideTextCommandDefault{\\guilsinglright}{%\n"
112         "  \\penalty10000\\hskip0pt%\n"
113         "  {\\usefont{U}{lasy}{m}{n}\\char'51}%\n"
114         "}");
115
116 static docstring const paragraphleftindent_def = from_ascii(
117         "\\newenvironment{LyXParagraphLeftIndent}[1]%\n"
118         "{\n"
119         "  \\begin{list}{}{%\n"
120         "    \\setlength{\\topsep}{0pt}%\n"
121         "    \\addtolength{\\leftmargin}{#1}\n"
122 // ho hum, yet more things commented out with no hint as to why they
123 // weren't just removed
124 //      "%%    \\addtolength{\\leftmargin}{#1\\textwidth}\n"
125 //      "%%    \\setlength{\\textwidth}{#2\\textwidth}\n"
126 //      "%%    \\setlength\\listparindent\\parindent%\n"
127 //      "%%    \\setlength\\itemindent\\parindent%\n"
128         "    \\setlength{\\parsep}{0pt plus 1pt}%\n"
129         "  }\n"
130         "  \\item[]\n"
131         "}\n"
132         "{\\end{list}}\n");
133
134 static docstring const floatingfootnote_def = from_ascii(
135         "%% Special footnote code from the package 'stblftnt.sty'\n"
136         "%% Author: Robin Fairbairns -- Last revised Dec 13 1996\n"
137         "\\let\\SF@@footnote\\footnote\n"
138         "\\def\\footnote{\\ifx\\protect\\@typeset@protect\n"
139         "    \\expandafter\\SF@@footnote\n"
140         "  \\else\n"
141         "    \\expandafter\\SF@gobble@opt\n"
142         "  \\fi\n"
143         "}\n"
144         "\\expandafter\\def\\csname SF@gobble@opt \\endcsname{\\@ifnextchar[%]\n"
145         "  \\SF@gobble@twobracket\n"
146         "  \\@gobble\n"
147         "}\n"
148         "\\edef\\SF@gobble@opt{\\noexpand\\protect\n"
149         "  \\expandafter\\noexpand\\csname SF@gobble@opt \\endcsname}\n"
150         "\\def\\SF@gobble@twobracket[#1]#2{}\n");
151
152 static docstring const binom_def = from_ascii(
153         "%% Binom macro for standard LaTeX users\n"
154         "\\newcommand{\\binom}[2]{{#1 \\choose #2}}\n");
155
156 static docstring const mathcircumflex_def = from_ascii(
157         "%% For printing a cirumflex inside a formula\n"
158         "\\newcommand{\\mathcircumflex}[0]{\\mbox{\\^{}}}\n");
159
160 static docstring const tabularnewline_def = from_ascii(
161         "%% Because html converters don't know tabularnewline\n"
162         "\\providecommand{\\tabularnewline}{\\\\}\n");
163         
164 static docstring const lyxgreyedout_def = from_ascii(
165         "%% The greyedout annotation environment\n"
166         "\\newenvironment{lyxgreyedout}{\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n");
167
168 // We want to omit the file extension for includegraphics, but this does not
169 // work when the filename contains other dots.
170 // Idea from http://www.tex.ac.uk/cgi-bin/texfaq2html?label=unkgrfextn
171 static docstring const lyxdot_def = from_ascii(
172         "%% A simple dot to overcome graphicx limitations\n"
173         "\\newcommand{\\lyxdot}{.}\n");
174
175 static docstring const changetracking_dvipost_def = from_ascii(
176         "%% Change tracking with dvipost\n"
177         "\\dvipostlayout\n"
178         "\\dvipost{osstart color push Red}\n"
179         "\\dvipost{osend color pop}\n"
180         "\\dvipost{cbstart color push Blue}\n"
181         "\\dvipost{cbend color pop}\n"
182         "\\newcommand{\\lyxadded}[3]{\\changestart#3\\changeend}\n"
183         "\\newcommand{\\lyxdeleted}[3]{%\n"
184         "\\changestart\\overstrikeon#3\\overstrikeoff\\changeend}\n");
185
186 static docstring const changetracking_xcolor_ulem_def = from_ascii(
187         "%% Change tracking with ulem\n"
188         "\\newcommand{\\lyxadded}[3]{{\\color{lyxadded}{}#3}}\n"
189         "\\newcommand{\\lyxdeleted}[3]{{\\color{lyxdeleted}\\sout{#3}}}\n");
190
191 static docstring const changetracking_xcolor_ulem_hyperref_def = from_ascii(
192         "%% Change tracking with ulem\n"
193         "\\newcommand{\\lyxadded}[3]{{\\texorpdfstring{\\color{lyxadded}{}}{}#3}}\n"
194         "\\newcommand{\\lyxdeleted}[3]{{\\texorpdfstring{\\color{lyxdeleted}\\sout{#3}}{}}}\n");
195
196 static docstring const changetracking_none_def = from_ascii(
197         "\\newcommand{\\lyxadded}[3]{#3}\n"
198         "\\newcommand{\\lyxdeleted}[3]{}\n");
199
200 static docstring const textgreek_def = from_ascii(
201         "\\DeclareRobustCommand{\\greektext}{%\n"
202         "  \\fontencoding{LGR}\\selectfont\\def\\encodingdefault{LGR}}\n"
203         "\\DeclareRobustCommand{\\textgreek}[1]{\\leavevmode{\\greektext #1}}\n"
204         "\\DeclareFontEncoding{LGR}{}{}\n"
205         "\\DeclareTextSymbol{\\~}{LGR}{126}");
206
207 static docstring const textcyr_def = from_ascii(
208         "\\DeclareRobustCommand{\\cyrtext}{%\n"
209         "  \\fontencoding{T2A}\\selectfont\\def\\encodingdefault{T2A}}\n"
210         "\\DeclareRobustCommand{\\textcyr}[1]{\\leavevmode{\\cyrtext #1}}\n"
211         "\\AtBeginDocument{\\DeclareFontEncoding{T2A}{}{}}\n");
212
213 static docstring const lyxmathsym_def = from_ascii(
214         "\\newcommand{\\lyxmathsym}[1]{\\ifmmode\\begingroup\\def\\b@ld{bold}\n"
215         "  \\text{\\ifx\\math@version\\b@ld\\bfseries\\fi#1}\\endgroup\\else#1\\fi}\n");
216
217 static docstring const papersizedvi_def = from_ascii(
218         "\\special{papersize=\\the\\paperwidth,\\the\\paperheight}\n");
219
220 static docstring const papersizepdf_def = from_ascii(
221         "\\pdfpageheight\\paperheight\n"
222         "\\pdfpagewidth\\paperwidth\n");
223
224 static docstring const cedilla_def = from_ascii(
225         "\\newcommand{\\docedilla}[2]{\\underaccent{#1\\mathchar'30}{#2}}\n"
226         "\\newcommand{\\cedilla}[1]{\\mathpalette\\docedilla{#1}}\n");
227
228 static docstring const subring_def = from_ascii(
229         "\\newcommand{\\dosubring}[2]{\\underaccent{#1\\mathchar'27}{#2}}\n"
230         "\\newcommand{\\subring}[1]{\\mathpalette\\dosubring{#1}}\n");
231
232 static docstring const subdot_def = from_ascii(
233         "\\newcommand{\\dosubdot}[2]{\\underaccent{#1.}{#2}}\n"
234         "\\newcommand{\\subdot}[1]{\\mathpalette\\dosubdot{#1}}\n");
235
236 static docstring const subhat_def = from_ascii(
237         "\\newcommand{\\dosubhat}[2]{\\underaccent{#1\\mathchar'136}{#2}}\n"
238         "\\newcommand{\\subhat}[1]{\\mathpalette\\dosubhat{#1}}\n");
239
240 static docstring const subtilde_def = from_ascii(
241         "\\newcommand{\\dosubtilde}[2]{\\underaccent{#1\\mathchar'176}{#2}}\n"
242         "\\newcommand{\\subtilde}[1]{\\mathpalette\\dosubtilde{#1}}\n");
243
244 static docstring const dacute_def = from_ascii(
245         "\\DeclareMathAccent{\\dacute}{\\mathalpha}{operators}{'175}\n");
246
247 static docstring const tipasymb_def = from_ascii(
248         "\\DeclareFontEncoding{T3}{}{}\n"
249         "\\DeclareSymbolFont{tipasymb}{T3}{cmr}{m}{n}\n");
250
251 static docstring const dgrave_def = from_ascii(
252         "\\DeclareMathAccent{\\dgrave}{\\mathord}{tipasymb}{'15}\n");
253
254 static docstring const rcap_def = from_ascii(
255         "\\DeclareMathAccent{\\rcap}{\\mathord}{tipasymb}{'20}\n");
256
257 static docstring const ogonek_def = from_ascii(
258         "\\newcommand{\\doogonek}[2]{\\setbox0=\\hbox{$#1#2$}\\underaccent{#1\\mkern-6mu\n"
259         "  \\ifx#2O\\hskip0.5\\wd0\\else\\ifx#2U\\hskip0.5\\wd0\\else\\hskip\\wd0\\fi\\fi\n"
260         "  \\ifx#2o\\mkern-2mu\\else\\ifx#2e\\mkern-1mu\\fi\\fi\n"
261         "  \\mathchar\"0\\hexnumber@\\symtipasymb0C}{#2}}\n"
262         "\\newcommand{\\ogonek}[1]{\\mathpalette\\doogonek{#1}}\n");
263
264 /////////////////////////////////////////////////////////////////////
265 //
266 // LaTeXFeatures
267 //
268 /////////////////////////////////////////////////////////////////////
269
270 LaTeXFeatures::Packages LaTeXFeatures::packages_;
271
272
273 LaTeXFeatures::LaTeXFeatures(Buffer const & b, BufferParams const & p,
274                              OutputParams const & r)
275         : buffer_(&b), params_(p), runparams_(r), in_float_(false)
276 {}
277
278
279 bool LaTeXFeatures::useBabel() const
280 {
281         return lyxrc.language_use_babel ||
282                 (bufferParams().language->lang() != lyxrc.default_language &&
283                  !bufferParams().language->babel().empty()) ||
284                 this->hasLanguages();
285 }
286
287
288 void LaTeXFeatures::require(string const & name)
289 {
290         features_.insert(name);
291 }
292
293
294 void LaTeXFeatures::require(set<string> const & names)
295 {
296         features_.insert(names.begin(), names.end());
297 }
298
299
300 void LaTeXFeatures::getAvailable()
301 {
302         Lexer lex;
303         support::FileName const real_file = libFileSearch("", "packages.lst");
304
305         if (real_file.empty())
306                 return;
307
308         lex.setFile(real_file);
309
310         if (!lex.isOK())
311                 return;
312
313         // Make sure that we are clean
314         packages_.clear();
315
316         bool finished = false;
317         // Parse config-file
318         while (lex.isOK() && !finished) {
319                 switch (lex.lex()) {
320                 case Lexer::LEX_FEOF:
321                         finished = true;
322                         break;
323                 default:
324                         packages_.insert(lex.getString());
325                 }
326         }
327 }
328
329
330 void LaTeXFeatures::useLayout(docstring const & layoutname)
331 {
332         // Some code to avoid loops in dependency definition
333         static int level = 0;
334         const int maxlevel = 30;
335         if (level > maxlevel) {
336                 lyxerr << "LaTeXFeatures::useLayout: maximum level of "
337                        << "recursion attained by layout "
338                        << to_utf8(layoutname) << endl;
339                 return;
340         }
341
342         DocumentClass const & tclass = params_.documentClass();
343         if (tclass.hasLayout(layoutname)) {
344                 // Is this layout already in usedLayouts?
345                 if (find(usedLayouts_.begin(), usedLayouts_.end(), layoutname) 
346                     != usedLayouts_.end())
347                         return;
348
349                 Layout const & layout = tclass[layoutname];
350                 require(layout.requires());
351
352                 if (!layout.depends_on().empty()) {
353                         ++level;
354                         useLayout(layout.depends_on());
355                         --level;
356                 }
357                 usedLayouts_.push_back(layoutname);
358         } else {
359                 lyxerr << "LaTeXFeatures::useLayout: layout `"
360                        << to_utf8(layoutname) << "' does not exist in this class"
361                        << endl;
362         }
363
364         --level;
365 }
366
367
368 void LaTeXFeatures::useInsetLayout(InsetLayout const & lay)
369 {
370         docstring const & lname = lay.name();
371         DocumentClass const & tclass = params_.documentClass();
372
373         // this is a default inset layout, nothing useful here
374         if (!tclass.hasInsetLayout(lname))
375                 return;
376         // Is this layout already in usedInsetLayouts?
377         if (find(usedInsetLayouts_.begin(), usedInsetLayouts_.end(), lname) 
378                         != usedInsetLayouts_.end())
379                 return;
380
381         require(lay.requires());
382         usedInsetLayouts_.push_back(lname);
383 }
384
385
386 bool LaTeXFeatures::isRequired(string const & name) const
387 {
388         return features_.find(name) != features_.end();
389 }
390
391
392 bool LaTeXFeatures::mustProvide(string const & name) const
393 {
394         return isRequired(name) && !params_.documentClass().provides(name);
395 }
396
397
398 bool LaTeXFeatures::isAvailable(string const & name)
399 {
400         string::size_type const i = name.find("->");
401         if (i != string::npos) {
402                 string const from = name.substr(0,i);
403                 string const to = name.substr(i+2);
404                 //LYXERR0("from=[" << from << "] to=[" << to << "]");
405                 return theConverters().isReachable(from, to);
406         }
407
408         if (packages_.empty())
409                 getAvailable();
410         string n = name;
411         if (suffixIs(n, ".sty"))
412                 n.erase(name.length() - 4);
413         return packages_.find(n) != packages_.end();
414 }
415
416
417 void LaTeXFeatures::addPreambleSnippet(string const & preamble)
418 {
419         SnippetList::const_iterator begin = preamble_snippets_.begin();
420         SnippetList::const_iterator end   = preamble_snippets_.end();
421         if (find(begin, end, preamble) == end)
422                 preamble_snippets_.push_back(preamble);
423 }
424
425
426 void LaTeXFeatures::useFloat(string const & name, bool subfloat)
427 {
428         if (!usedFloats_[name])
429                 usedFloats_[name] = subfloat;
430         if (subfloat)
431                 require("subfig");
432         // We only need float.sty if we use non builtin floats, or if we
433         // use the "H" modifier. This includes modified table and
434         // figure floats. (Lgb)
435         Floating const & fl = params_.documentClass().floats().getType(name);
436         if (!fl.floattype().empty() && fl.needsFloatPkg()) {
437                 require("float");
438         }
439 }
440
441
442 void LaTeXFeatures::useLanguage(Language const * lang)
443 {
444         if (!lang->babel().empty())
445                 UsedLanguages_.insert(lang);
446         if (lang->lang() == "vietnamese")
447                 require("vietnamese");
448         // CJK languages do not have a babel name.
449         // They use the CJK package
450         if (lang->encoding()->package() == Encoding::CJK)
451                 require("CJK");
452         // japanese package is special
453         if (lang->encoding()->package() == Encoding::japanese)
454                 require("japanese");
455 }
456
457
458 void LaTeXFeatures::includeFile(docstring const & key, string const & name)
459 {
460         IncludedFiles_[key] = name;
461 }
462
463
464 bool LaTeXFeatures::hasLanguages() const
465 {
466         return !UsedLanguages_.empty();
467 }
468
469
470 string LaTeXFeatures::getLanguages() const
471 {
472         ostringstream languages;
473
474         LanguageList::const_iterator const begin = UsedLanguages_.begin();
475         for (LanguageList::const_iterator cit = begin;
476              cit != UsedLanguages_.end();
477              ++cit) {
478                 if (cit != begin)
479                         languages << ',';
480                 languages << (*cit)->babel();
481         }
482         return languages.str();
483 }
484
485
486 set<string> LaTeXFeatures::getEncodingSet(string const & doc_encoding) const
487 {
488         // This does only find encodings of languages supported by babel, but
489         // that does not matter since we don't have a language with an
490         // encoding supported by inputenc but without babel support.
491         set<string> encodings;
492         LanguageList::const_iterator it  = UsedLanguages_.begin();
493         LanguageList::const_iterator end = UsedLanguages_.end();
494         for (; it != end; ++it)
495                 if ((*it)->encoding()->latexName() != doc_encoding &&
496                     ((*it)->encoding()->package() == Encoding::inputenc
497                      || (*it)->encoding()->package() == Encoding::japanese))
498                         encodings.insert((*it)->encoding()->latexName());
499         return encodings;
500 }
501
502 namespace {
503
504 char const * simplefeatures[] = {
505 // note that the package order here will be the same in the LaTeX-output
506         "array",
507         "verbatim",
508         "longtable",
509         "rotating",
510         "latexsym",
511         "pifont",
512         // subfig is handled in BufferParams.cpp
513         "varioref",
514         "prettyref",
515         /*For a successful cooperation of the `wrapfig' package with the
516           `float' package you should load the `wrapfig' package *after*
517           the `float' package. See the caption package documentation
518           for explanation.*/
519         "float",
520         "rotfloat",
521         "wrapfig",
522         "booktabs",
523         "dvipost",
524         "fancybox",
525         "calc",
526         "units",
527         "tipa",
528         "tipx",
529         "framed",
530         "soul",
531         "textcomp",
532         "pmboxdraw",
533         "bbding",
534         "ifsym",
535         "marvosym",
536         "txfonts",
537         "mathrsfs",
538         "ascii",
539         "url",
540         "covington",
541         "csquotes",
542         "enumitem",
543         "endnotes",
544         "ifthen",
545         "amsthm",
546         // listings is handled in BufferParams.cpp
547         "bm",
548         "pdfpages",
549         "amscd",
550         "slashed",
551         "multirow"
552 };
553
554 int const nb_simplefeatures = sizeof(simplefeatures) / sizeof(char const *);
555
556 }
557
558
559 string const LaTeXFeatures::getColorOptions() const
560 {
561         ostringstream colors;
562
563         // Handling the color packages separately is needed to be able to load them
564         // before babel when hyperref is loaded with the colorlinks option
565         // for more info see Bufferparams.cpp
566
567         // [x]color.sty
568         if (mustProvide("color") || mustProvide("xcolor")) {
569                 string const package =
570                         (mustProvide("xcolor") ? "xcolor" : "color");
571                 if (params_.graphicsDriver == "default"
572                         || params_.graphicsDriver == "none")
573                         colors << "\\usepackage{" << package << "}\n";
574                 else
575                         colors << "\\usepackage["
576                                  << params_.graphicsDriver
577                                  << "]{" << package << "}\n";
578         }
579
580         // pdfcolmk must be loaded after color
581         if (mustProvide("pdfcolmk"))
582                 colors << "\\usepackage{pdfcolmk}\n";
583
584         // the following 3 color commands must be set after color
585         // is loaded and before pdfpages, therefore add the command
586         // here define the set color
587         if (mustProvide("pagecolor")) {
588                 colors << "\\definecolor{page_backgroundcolor}{rgb}{";
589                 colors << outputLaTeXColor(params_.backgroundcolor) << "}\n";
590                 // set the page color
591                 colors << "\\pagecolor{page_backgroundcolor}\n";
592         }
593
594         if (mustProvide("fontcolor")) {
595                 colors << "\\definecolor{document_fontcolor}{rgb}{";
596                 colors << outputLaTeXColor(params_.fontcolor) << "}\n";
597                 // set the color
598                 colors << "\\color{document_fontcolor}\n";
599         }
600
601         if (mustProvide("lyxgreyedout")) {
602                 colors << "\\definecolor{note_fontcolor}{rgb}{";
603                 colors << outputLaTeXColor(params_.notefontcolor) << "}\n";
604                 // the color will be set together with the definition of
605                 // the lyxgreyedout environment (see lyxgreyedout_def)
606         }
607
608         // color for shaded boxes
609         if (isRequired("framed") && mustProvide("color")) {
610                 colors << "\\definecolor{shadecolor}{rgb}{";
611                 colors << outputLaTeXColor(params_.boxbgcolor) << "}\n";
612                 // this color is automatically used by the LaTeX-package "framed"
613         }
614
615         return colors.str();
616 }
617
618
619 string const LaTeXFeatures::getPackages() const
620 {
621         ostringstream packages;
622         DocumentClass const & tclass = params_.documentClass();
623
624         // FIXME: currently, we can only load packages and macros known
625         // to LyX.
626         // However, with the Require tag of layouts/custom insets,
627         // also inknown packages can be requested. They are silently
628         // swallowed now. We should change this eventually.
629
630         //
631         //  These are all the 'simple' includes.  i.e
632         //  packages which we just \usepackage{package}
633         //
634         for (int i = 0; i < nb_simplefeatures; ++i) {
635                 if (mustProvide(simplefeatures[i]))
636                         packages << "\\usepackage{"
637                                  << simplefeatures[i] << "}\n";
638         }
639
640         //
641         // The rest of these packages are somewhat more complicated
642         // than those above.
643         //
644
645         // esint is preferred for esintoramsmath
646         if ((mustProvide("amsmath")
647              && params_.use_amsmath != BufferParams::package_off)
648             || (mustProvide("esintoramsmath")
649                 && params_.use_esint == BufferParams::package_off
650                 && params_.use_amsmath != BufferParams::package_off)) {
651                 packages << "\\usepackage{amsmath}\n";
652         } else {
653                 // amsbsy and amstext are already provided by amsmath
654                 if (mustProvide("amsbsy"))
655                         packages << "\\usepackage{amsbsy}\n";
656                 if (mustProvide("amstext"))
657                         packages << "\\usepackage{amstext}\n";
658         }
659         
660         // wasysym is a simple feature, but it must be after amsmath if both
661         // are used
662         // wasysym redefines some integrals (e.g. iint) from amsmath. That
663         // leads to inconsistent integrals. We only load this package if
664         // the document does not contain integrals (then isRequired("esint")
665         // is false) or if esint is used, since esint redefines all relevant
666         // integral symbols from wasysym and amsmath.
667         // See http://www.lyx.org/trac/ticket/1942
668         if (mustProvide("wasysym") &&
669             (params_.use_esint != BufferParams::package_off || !isRequired("esint")))
670                 packages << "\\usepackage{wasysym}\n";
671
672         // accents must be loaded after amsmath
673         if (mustProvide("accents"))
674                 packages << "\\usepackage{accents}\n";
675
676         // mathdots must be loaded after amsmath
677         if (mustProvide("mathdots"))
678                 packages << "\\usepackage{mathdots}\n";
679
680         // yhmath must be loaded after amsmath
681         if (mustProvide("yhmath"))
682                 packages << "\\usepackage{yhmath}\n";
683
684         // [x]color and pdfcolmk are handled in getColorOptions() above
685         
686         // makeidx.sty
687         if (isRequired("makeidx") || isRequired("splitidx")) {
688                 if (!tclass.provides("makeidx") && !isRequired("splitidx"))
689                         packages << "\\usepackage{makeidx}\n";
690                 if (!tclass.provides("splitidx") && isRequired("splitidx"))
691                         packages << "\\usepackage{splitidx}\n";
692                 packages << "\\makeindex\n";
693         }
694
695         // graphicx.sty
696         if (mustProvide("graphicx") && params_.graphicsDriver != "none") {
697                 if (params_.graphicsDriver == "default")
698                         packages << "\\usepackage{graphicx}\n";
699                 else
700                         packages << "\\usepackage["
701                                  << params_.graphicsDriver
702                                  << "]{graphicx}\n";
703         }
704         
705         // lyxskak.sty --- newer chess support based on skak.sty
706         if (mustProvide("chess"))
707                 packages << "\\usepackage[ps,mover]{lyxskak}\n";
708
709         // setspace.sty
710         if (mustProvide("setspace") && !tclass.provides("SetSpace"))
711                 packages << "\\usepackage{setspace}\n";
712
713         // amssymb.sty
714         if (mustProvide("amssymb")
715             || params_.use_amsmath == BufferParams::package_on)
716                 packages << "\\usepackage{amssymb}\n";
717
718         // esint must be after amsmath and wasysym, since it will redeclare
719         // inconsistent integral symbols
720         if ((mustProvide("esint") || mustProvide("esintoramsmath")) &&
721             params_.use_esint != BufferParams::package_off)
722                 packages << "\\usepackage{esint}\n";
723
724         // natbib.sty
725         // Some classes load natbib themselves, but still allow (or even require)
726         // plain numeric citations (ReVTeX is such a case, see bug 5182).
727         // This special case is indicated by the "natbib-internal" key.
728         if (mustProvide("natbib") && !tclass.provides("natbib-internal")) {
729                 packages << "\\usepackage[";
730                 if (params_.citeEngine() == ENGINE_NATBIB_NUMERICAL)
731                         packages << "numbers";
732                 else
733                         packages << "authoryear";
734                 packages << "]{natbib}\n";
735         }
736
737         // jurabib -- we need version 0.6 at least.
738         if (mustProvide("jurabib"))
739                 packages << "\\usepackage{jurabib}[2004/01/25]\n";
740         
741         // xargs -- we need version 1.09 at least
742         if (mustProvide("xargs"))
743                 packages << "\\usepackage{xargs}[2008/03/08]\n";
744
745         // bibtopic -- the dot provides the aux file naming which
746         // LyX can detect.
747         if (mustProvide("bibtopic"))
748                 packages << "\\usepackage[dot]{bibtopic}\n";
749
750         if (mustProvide("xy"))
751                 packages << "\\usepackage[all]{xy}\n";
752
753         if (mustProvide("ulem"))
754                 packages << "\\PassOptionsToPackage{normalem}{ulem}\n"
755                             "\\usepackage{ulem}\n";
756
757         if (mustProvide("mhchem") &&
758                 params_.use_mhchem != BufferParams::package_off)
759                 packages << "\\PassOptionsToPackage{version=3}{mhchem}\n"
760                             "\\usepackage{mhchem}\n";
761
762         if (mustProvide("nomencl")) {
763                 // Make it work with the new and old version of the package,
764                 // but don't use the compatibility option since it is
765                 // incompatible to other packages.
766                 packages << "\\usepackage{nomencl}\n"
767                             "% the following is useful when we have the old nomencl.sty package\n"
768                             "\\providecommand{\\printnomenclature}{\\printglossary}\n"
769                             "\\providecommand{\\makenomenclature}{\\makeglossary}\n"
770                             "\\makenomenclature\n";
771         }
772
773         return packages.str();
774 }
775
776
777 string LaTeXFeatures::getPreambleSnippets() const 
778 {
779         ostringstream snip;
780         SnippetList::const_iterator pit  = preamble_snippets_.begin();
781         SnippetList::const_iterator pend = preamble_snippets_.end();
782         for (; pit != pend; ++pit)
783                 snip << *pit << '\n';
784         return snip.str();
785 }
786
787
788 docstring const LaTeXFeatures::getMacros() const
789 {
790         odocstringstream macros;
791
792         if (!preamble_snippets_.empty()) {
793                 macros << '\n';
794                 macros << from_utf8(getPreambleSnippets());
795         }
796
797         if (mustProvide("papersize")) {
798                 if (runparams_.flavor == OutputParams::LATEX)
799                         macros << papersizedvi_def << '\n';
800                 else
801                         macros << papersizepdf_def << '\n';
802         }
803
804         if (mustProvide("LyX"))
805                 macros << lyx_def << '\n';
806
807         if (mustProvide("lyxline"))
808                 macros << lyxline_def << '\n';
809
810         if (mustProvide("noun"))
811                 macros << noun_def << '\n';
812
813         if (mustProvide("lyxarrow"))
814                 macros << lyxarrow_def << '\n';
815
816         if (mustProvide("textgreek")) {
817                 // Avoid a LaTeX error if times fonts are used and the grtimes
818                 // package is installed but actual fonts are not (bug 6469).
819                 if (params_.fontsRoman == "times")
820                         macros << subst(textgreek_def,
821                                         from_ascii("\\greektext #1"),
822                                         from_ascii("%\n  \\IfFileExists"
823                                                    "{grtm10.tfm}{}{\\fontfamily"
824                                                    "{cmr}}\\greektext #1"))
825                                << '\n';
826                 else
827                         macros << textgreek_def << '\n';
828         }
829
830         if (mustProvide("textcyr"))
831                 macros << textcyr_def << '\n';
832
833         if (mustProvide("lyxmathsym"))
834                 macros << lyxmathsym_def << '\n';
835
836         if (mustProvide("cedilla"))
837                 macros << cedilla_def << '\n';
838
839         if (mustProvide("subring"))
840                 macros << subring_def << '\n';
841
842         if (mustProvide("subdot"))
843                 macros << subdot_def << '\n';
844
845         if (mustProvide("subhat"))
846                 macros << subhat_def << '\n';
847
848         if (mustProvide("subtilde"))
849                 macros << subtilde_def << '\n';
850
851         if (mustProvide("dacute"))
852                 macros << dacute_def << '\n';
853
854         if (mustProvide("tipasymb"))
855                 macros << tipasymb_def << '\n';
856
857         if (mustProvide("dgrave"))
858                 macros << dgrave_def << '\n';
859
860         if (mustProvide("rcap"))
861                 macros << rcap_def << '\n';
862
863         if (mustProvide("ogonek"))
864                 macros << ogonek_def << '\n';
865
866         // quotes.
867         if (mustProvide("quotesinglbase"))
868                 macros << quotesinglbase_def << '\n';
869         if (mustProvide("quotedblbase"))
870                 macros << quotedblbase_def << '\n';
871         if (mustProvide("guilsinglleft"))
872                 macros << guilsinglleft_def << '\n';
873         if (mustProvide("guilsinglright"))
874                 macros << guilsinglright_def << '\n';
875         if (mustProvide("guillemotleft"))
876                 macros << guillemotleft_def << '\n';
877         if (mustProvide("guillemotright"))
878                 macros << guillemotright_def << '\n';
879
880         // Math mode
881         if (mustProvide("binom") && !isRequired("amsmath"))
882                 macros << binom_def << '\n';
883         if (mustProvide("mathcircumflex"))
884                 macros << mathcircumflex_def << '\n';
885
886         // other
887         if (mustProvide("ParagraphLeftIndent"))
888                 macros << paragraphleftindent_def;
889         if (mustProvide("NeedLyXFootnoteCode"))
890                 macros << floatingfootnote_def;
891
892         // some problems with tex->html converters
893         if (mustProvide("NeedTabularnewline"))
894                 macros << tabularnewline_def;
895
896         // greyed-out environment (note inset)
897         // the color is specified in the routine
898         // getColorOptions() to avoid LaTeX-package clashes
899         if (mustProvide("lyxgreyedout"))
900                 macros << lyxgreyedout_def;
901
902         if (mustProvide("lyxdot"))
903                 macros << lyxdot_def << '\n';
904
905         // floats
906         getFloatDefinitions(macros);
907
908         // change tracking
909         if (mustProvide("ct-dvipost"))
910                 macros << changetracking_dvipost_def;
911
912         if (mustProvide("ct-xcolor-ulem")) {
913                 int const prec = macros.precision(2);
914         
915                 RGBColor cadd = rgbFromHexName(lcolor.getX11Name(Color_addedtext));
916                 macros << "\\providecolor{lyxadded}{rgb}{"
917                        << cadd.r / 255.0 << ',' << cadd.g / 255.0 << ',' << cadd.b / 255.0 << "}\n";
918
919                 RGBColor cdel = rgbFromHexName(lcolor.getX11Name(Color_deletedtext));
920                 macros << "\\providecolor{lyxdeleted}{rgb}{"
921                        << cdel.r / 255.0 << ',' << cdel.g / 255.0 << ',' << cdel.b / 255.0 << "}\n";
922
923                 macros.precision(prec);
924                 
925                 if (isRequired("hyperref"))
926                         macros << changetracking_xcolor_ulem_hyperref_def;
927                 else
928                         macros << changetracking_xcolor_ulem_def;
929         }
930
931         if (mustProvide("ct-none"))
932                 macros << changetracking_none_def;
933
934         return macros.str();
935 }
936
937
938 string const LaTeXFeatures::getBabelOptions() const
939 {
940         ostringstream tmp;
941
942         LanguageList::const_iterator it  = UsedLanguages_.begin();
943         LanguageList::const_iterator end =  UsedLanguages_.end();
944         for (; it != end; ++it)
945                 if (!(*it)->latex_options().empty())
946                         tmp << (*it)->latex_options() << '\n';
947         if (!params_.language->latex_options().empty())
948                 tmp << params_.language->latex_options() << '\n';
949
950         return tmp.str();
951 }
952
953
954 docstring const LaTeXFeatures::getTClassPreamble() const
955 {
956         // the text class specific preamble
957         DocumentClass const & tclass = params_.documentClass();
958         odocstringstream tcpreamble;
959
960         tcpreamble << tclass.preamble();
961
962         list<docstring>::const_iterator cit = usedLayouts_.begin();
963         list<docstring>::const_iterator end = usedLayouts_.end();
964         for (; cit != end; ++cit)
965                 tcpreamble << tclass[*cit].preamble();
966
967         cit = usedInsetLayouts_.begin();
968         end = usedInsetLayouts_.end();
969         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
970         for (; cit != end; ++cit) {
971                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
972                 if (it == ils.end())
973                         continue;
974                 tcpreamble << it->second.preamble();
975         }
976
977         return tcpreamble.str();
978 }
979
980
981 docstring const LaTeXFeatures::getTClassHTMLPreamble() const 
982 {
983         DocumentClass const & tclass = params_.documentClass();
984         odocstringstream tcpreamble;
985
986         tcpreamble << tclass.htmlpreamble();
987
988         list<docstring>::const_iterator cit = usedLayouts_.begin();
989         list<docstring>::const_iterator end = usedLayouts_.end();
990         for (; cit != end; ++cit)
991                 tcpreamble << tclass[*cit].htmlpreamble();
992
993         cit = usedInsetLayouts_.begin();
994         end = usedInsetLayouts_.end();
995         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
996         for (; cit != end; ++cit) {
997                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
998                 if (it == ils.end())
999                         continue;
1000                 tcpreamble << it->second.htmlpreamble();
1001         }
1002
1003         return tcpreamble.str();
1004 }
1005
1006
1007 docstring const LaTeXFeatures::getTClassHTMLStyles() const {
1008         DocumentClass const & tclass = params_.documentClass();
1009         odocstringstream tcpreamble;
1010
1011         list<docstring>::const_iterator cit = usedLayouts_.begin();
1012         list<docstring>::const_iterator end = usedLayouts_.end();
1013         for (; cit != end; ++cit)
1014                 tcpreamble << tclass[*cit].htmlstyle();
1015
1016         cit = usedInsetLayouts_.begin();
1017         end = usedInsetLayouts_.end();
1018         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1019         for (; cit != end; ++cit) {
1020                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1021                 if (it == ils.end())
1022                         continue;
1023                 tcpreamble << it->second.htmlstyle();
1024         }
1025
1026         return tcpreamble.str();
1027 }
1028
1029
1030 namespace {
1031 docstring const getFloatI18nPreamble(docstring const & type, docstring const & name, docstring const & lang)
1032 {
1033         odocstringstream os;
1034         os << "\\addto\\captions" << lang
1035            << "{\\renewcommand{\\" << type << "name}{" << name << "}}\n";
1036         return os.str();
1037 }
1038 }
1039
1040
1041 docstring const LaTeXFeatures::getTClassI18nPreamble(bool use_babel) const
1042 {
1043         DocumentClass const & tclass = params_.documentClass();
1044         // collect preamble snippets in a set to prevent multiple identical
1045         // commands (would happen if e.g. both theorem and theorem* are used)
1046         set<docstring> snippets;
1047         typedef LanguageList::const_iterator lang_it;
1048         lang_it const lbeg = UsedLanguages_.begin();
1049         lang_it const lend =  UsedLanguages_.end();
1050         list<docstring>::const_iterator cit = usedLayouts_.begin();
1051         list<docstring>::const_iterator end = usedLayouts_.end();
1052         for (; cit != end; ++cit) {
1053                 // language dependent commands (once per document)
1054                 snippets.insert(tclass[*cit].langpreamble(buffer().language()));
1055                 // commands for language changing (for multilanguage documents)
1056                 if (use_babel && !UsedLanguages_.empty()) {
1057                         snippets.insert(tclass[*cit].babelpreamble(buffer().language()));
1058                         for (lang_it lit = lbeg; lit != lend; ++lit)
1059                                 snippets.insert(tclass[*cit].babelpreamble(*lit));
1060                 }
1061         }
1062         if (use_babel && !UsedLanguages_.empty()) {
1063                 FloatList const & floats = params_.documentClass().floats();
1064                 UsedFloats::const_iterator fit = usedFloats_.begin();
1065                 UsedFloats::const_iterator fend = usedFloats_.end();
1066                 for (; fit != fend; ++fit) {
1067                         Floating const & fl = floats.getType(fit->first);
1068                         docstring const type = from_ascii(fl.floattype());
1069                         docstring const flname = from_utf8(fl.name());
1070                         docstring name = translateIfPossible(flname,
1071                                 buffer().language()->code());
1072                         snippets.insert(getFloatI18nPreamble(
1073                                 type, name,
1074                                 from_ascii(buffer().language()->babel())));
1075                         for (lang_it lit = lbeg; lit != lend; ++lit) {
1076                                 name = translateIfPossible(flname,
1077                                         (*lit)->code());
1078                                 snippets.insert(getFloatI18nPreamble(
1079                                         type, name,
1080                                         from_ascii((*lit)->babel())));
1081                         }
1082                 }
1083         }
1084
1085         odocstringstream tcpreamble;
1086         set<docstring>::const_iterator const send = snippets.end();
1087         set<docstring>::const_iterator it = snippets.begin();
1088         for (; it != send; ++it)
1089                 tcpreamble << *it;
1090         return tcpreamble.str();
1091 }
1092
1093
1094 docstring const LaTeXFeatures::getLyXSGMLEntities() const
1095 {
1096         // Definition of entities used in the document that are LyX related.
1097         odocstringstream entities;
1098
1099         if (mustProvide("lyxarrow")) {
1100                 entities << "<!ENTITY lyxarrow \"-&gt;\">" << '\n';
1101         }
1102
1103         return entities.str();
1104 }
1105
1106
1107 docstring const LaTeXFeatures::getIncludedFiles(string const & fname) const
1108 {
1109         odocstringstream sgmlpreamble;
1110         // FIXME UNICODE
1111         docstring const basename(from_utf8(onlyPath(fname)));
1112
1113         FileMap::const_iterator end = IncludedFiles_.end();
1114         for (FileMap::const_iterator fi = IncludedFiles_.begin();
1115              fi != end; ++fi)
1116                 // FIXME UNICODE
1117                 sgmlpreamble << "\n<!ENTITY " << fi->first
1118                              << (isSGMLFileName(fi->second) ? " SYSTEM \"" : " \"")
1119                              << makeRelPath(from_utf8(fi->second), basename) << "\">";
1120
1121         return sgmlpreamble.str();
1122 }
1123
1124
1125 void LaTeXFeatures::showStruct() const
1126 {
1127         lyxerr << "LyX needs the following commands when LaTeXing:"
1128                << "\n***** Packages:" << getPackages()
1129                << "\n***** Macros:" << to_utf8(getMacros())
1130                << "\n***** Textclass stuff:" << to_utf8(getTClassPreamble())
1131                << "\n***** done." << endl;
1132 }
1133
1134
1135 Buffer const & LaTeXFeatures::buffer() const
1136 {
1137         return *buffer_;
1138 }
1139
1140
1141 void LaTeXFeatures::setBuffer(Buffer const & buffer)
1142 {
1143         buffer_ = &buffer;
1144 }
1145
1146
1147 BufferParams const & LaTeXFeatures::bufferParams() const
1148 {
1149         return params_;
1150 }
1151
1152
1153 void LaTeXFeatures::getFloatDefinitions(odocstream & os) const
1154 {
1155         FloatList const & floats = params_.documentClass().floats();
1156
1157         // Here we will output the code to create the needed float styles.
1158         // We will try to do this as minimal as possible.
1159         // \floatstyle{ruled}
1160         // \newfloat{algorithm}{htbp}{loa}
1161         // \providecommand{\algorithmname}{Algorithm}
1162         // \floatname{algorithm}{\protect\algorithmname}
1163         UsedFloats::const_iterator cit = usedFloats_.begin();
1164         UsedFloats::const_iterator end = usedFloats_.end();
1165         for (; cit != end; ++cit) {
1166                 Floating const & fl = floats.getType(cit->first);
1167
1168                 // For builtin floats we do nothing.
1169                 if (!fl.needsFloatPkg()) 
1170                         continue;
1171
1172                 // We have to special case "table" and "figure"
1173                 if (fl.floattype() == "tabular" || fl.floattype() == "figure") {
1174                         // Output code to modify "table" or "figure"
1175                         // but only if builtin == false
1176                         // and that have to be true at this point in the
1177                         // function.
1178                         docstring const type = from_ascii(fl.floattype());
1179                         docstring const placement = from_ascii(fl.placement());
1180                         docstring const style = from_ascii(fl.style());
1181                         if (!style.empty()) {
1182                                 os << "\\floatstyle{" << style << "}\n"
1183                                    << "\\restylefloat{" << type << "}\n";
1184                         }
1185                         if (!placement.empty()) {
1186                                 os << "\\floatplacement{" << type << "}{"
1187                                    << placement << "}\n";
1188                         }
1189                 } else {
1190                         // The other non builtin floats.
1191
1192                         docstring const type = from_ascii(fl.floattype());
1193                         docstring const placement = from_ascii(fl.placement());
1194                         docstring const ext = from_ascii(fl.ext());
1195                         docstring const within = from_ascii(fl.within());
1196                         docstring const style = from_ascii(fl.style());
1197                         docstring const name = translateIfPossible(
1198                                         from_utf8(fl.name()),
1199                                         buffer().language()->code());
1200                         os << "\\floatstyle{" << style << "}\n"
1201                            << "\\newfloat{" << type << "}{" << placement
1202                            << "}{" << ext << '}';
1203                         if (!within.empty())
1204                                 os << '[' << within << ']';
1205                         os << '\n'
1206                            << "\\providecommand{\\" << type << "name}{"
1207                            << name << "}\n"
1208                            << "\\floatname{" << type << "}{\\protect\\"
1209                            << type << "name}\n";
1210
1211                         // What missing here is to code to minimalize the code
1212                         // output so that the same floatstyle will not be
1213                         // used several times, when the same style is still in
1214                         // effect. (Lgb)
1215                 }
1216                 if (cit->second)
1217                         os << "\n\\newsubfloat{" << from_ascii(fl.floattype()) << "}\n";
1218         }
1219 }
1220
1221
1222 } // namespace lyx