]> git.lyx.org Git - lyx.git/blob - src/LaTeXFeatures.cpp
better support for the mathdots package:
[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                 params_.use_mathdots != BufferParams::package_off)
679                 packages << "\\usepackage{mathdots}\n";
680
681         // yhmath must be loaded after amsmath
682         if (mustProvide("yhmath"))
683                 packages << "\\usepackage{yhmath}\n";
684
685         // [x]color and pdfcolmk are handled in getColorOptions() above
686         
687         // makeidx.sty
688         if (isRequired("makeidx") || isRequired("splitidx")) {
689                 if (!tclass.provides("makeidx") && !isRequired("splitidx"))
690                         packages << "\\usepackage{makeidx}\n";
691                 if (!tclass.provides("splitidx") && isRequired("splitidx"))
692                         packages << "\\usepackage{splitidx}\n";
693                 packages << "\\makeindex\n";
694         }
695
696         // graphicx.sty
697         if (mustProvide("graphicx") && params_.graphicsDriver != "none") {
698                 if (params_.graphicsDriver == "default")
699                         packages << "\\usepackage{graphicx}\n";
700                 else
701                         packages << "\\usepackage["
702                                  << params_.graphicsDriver
703                                  << "]{graphicx}\n";
704         }
705         
706         // lyxskak.sty --- newer chess support based on skak.sty
707         if (mustProvide("chess"))
708                 packages << "\\usepackage[ps,mover]{lyxskak}\n";
709
710         // setspace.sty
711         if (mustProvide("setspace") && !tclass.provides("SetSpace"))
712                 packages << "\\usepackage{setspace}\n";
713
714         // amssymb.sty
715         if (mustProvide("amssymb")
716             || params_.use_amsmath == BufferParams::package_on)
717                 packages << "\\usepackage{amssymb}\n";
718
719         // esint must be after amsmath and wasysym, since it will redeclare
720         // inconsistent integral symbols
721         if ((mustProvide("esint") || mustProvide("esintoramsmath")) &&
722             params_.use_esint != BufferParams::package_off)
723                 packages << "\\usepackage{esint}\n";
724
725         // natbib.sty
726         // Some classes load natbib themselves, but still allow (or even require)
727         // plain numeric citations (ReVTeX is such a case, see bug 5182).
728         // This special case is indicated by the "natbib-internal" key.
729         if (mustProvide("natbib") && !tclass.provides("natbib-internal")) {
730                 packages << "\\usepackage[";
731                 if (params_.citeEngine() == ENGINE_NATBIB_NUMERICAL)
732                         packages << "numbers";
733                 else
734                         packages << "authoryear";
735                 packages << "]{natbib}\n";
736         }
737
738         // jurabib -- we need version 0.6 at least.
739         if (mustProvide("jurabib"))
740                 packages << "\\usepackage{jurabib}[2004/01/25]\n";
741         
742         // xargs -- we need version 1.09 at least
743         if (mustProvide("xargs"))
744                 packages << "\\usepackage{xargs}[2008/03/08]\n";
745
746         // bibtopic -- the dot provides the aux file naming which
747         // LyX can detect.
748         if (mustProvide("bibtopic"))
749                 packages << "\\usepackage[dot]{bibtopic}\n";
750
751         if (mustProvide("xy"))
752                 packages << "\\usepackage[all]{xy}\n";
753
754         if (mustProvide("ulem"))
755                 packages << "\\PassOptionsToPackage{normalem}{ulem}\n"
756                             "\\usepackage{ulem}\n";
757
758         if (mustProvide("mhchem") &&
759                 params_.use_mhchem != BufferParams::package_off)
760                 packages << "\\PassOptionsToPackage{version=3}{mhchem}\n"
761                             "\\usepackage{mhchem}\n";
762
763         if (mustProvide("nomencl")) {
764                 // Make it work with the new and old version of the package,
765                 // but don't use the compatibility option since it is
766                 // incompatible to other packages.
767                 packages << "\\usepackage{nomencl}\n"
768                             "% the following is useful when we have the old nomencl.sty package\n"
769                             "\\providecommand{\\printnomenclature}{\\printglossary}\n"
770                             "\\providecommand{\\makenomenclature}{\\makeglossary}\n"
771                             "\\makenomenclature\n";
772         }
773
774         return packages.str();
775 }
776
777
778 string LaTeXFeatures::getPreambleSnippets() const 
779 {
780         ostringstream snip;
781         SnippetList::const_iterator pit  = preamble_snippets_.begin();
782         SnippetList::const_iterator pend = preamble_snippets_.end();
783         for (; pit != pend; ++pit)
784                 snip << *pit << '\n';
785         return snip.str();
786 }
787
788
789 docstring const LaTeXFeatures::getMacros() const
790 {
791         odocstringstream macros;
792
793         if (!preamble_snippets_.empty()) {
794                 macros << '\n';
795                 macros << from_utf8(getPreambleSnippets());
796         }
797
798         if (mustProvide("papersize")) {
799                 if (runparams_.flavor == OutputParams::LATEX)
800                         macros << papersizedvi_def << '\n';
801                 else
802                         macros << papersizepdf_def << '\n';
803         }
804
805         if (mustProvide("LyX"))
806                 macros << lyx_def << '\n';
807
808         if (mustProvide("lyxline"))
809                 macros << lyxline_def << '\n';
810
811         if (mustProvide("noun"))
812                 macros << noun_def << '\n';
813
814         if (mustProvide("lyxarrow"))
815                 macros << lyxarrow_def << '\n';
816
817         if (mustProvide("textgreek")) {
818                 // Avoid a LaTeX error if times fonts are used and the grtimes
819                 // package is installed but actual fonts are not (bug 6469).
820                 if (params_.fontsRoman == "times")
821                         macros << subst(textgreek_def,
822                                         from_ascii("\\greektext #1"),
823                                         from_ascii("%\n  \\IfFileExists"
824                                                    "{grtm10.tfm}{}{\\fontfamily"
825                                                    "{cmr}}\\greektext #1"))
826                                << '\n';
827                 else
828                         macros << textgreek_def << '\n';
829         }
830
831         if (mustProvide("textcyr"))
832                 macros << textcyr_def << '\n';
833
834         if (mustProvide("lyxmathsym"))
835                 macros << lyxmathsym_def << '\n';
836
837         if (mustProvide("cedilla"))
838                 macros << cedilla_def << '\n';
839
840         if (mustProvide("subring"))
841                 macros << subring_def << '\n';
842
843         if (mustProvide("subdot"))
844                 macros << subdot_def << '\n';
845
846         if (mustProvide("subhat"))
847                 macros << subhat_def << '\n';
848
849         if (mustProvide("subtilde"))
850                 macros << subtilde_def << '\n';
851
852         if (mustProvide("dacute"))
853                 macros << dacute_def << '\n';
854
855         if (mustProvide("tipasymb"))
856                 macros << tipasymb_def << '\n';
857
858         if (mustProvide("dgrave"))
859                 macros << dgrave_def << '\n';
860
861         if (mustProvide("rcap"))
862                 macros << rcap_def << '\n';
863
864         if (mustProvide("ogonek"))
865                 macros << ogonek_def << '\n';
866
867         // quotes.
868         if (mustProvide("quotesinglbase"))
869                 macros << quotesinglbase_def << '\n';
870         if (mustProvide("quotedblbase"))
871                 macros << quotedblbase_def << '\n';
872         if (mustProvide("guilsinglleft"))
873                 macros << guilsinglleft_def << '\n';
874         if (mustProvide("guilsinglright"))
875                 macros << guilsinglright_def << '\n';
876         if (mustProvide("guillemotleft"))
877                 macros << guillemotleft_def << '\n';
878         if (mustProvide("guillemotright"))
879                 macros << guillemotright_def << '\n';
880
881         // Math mode
882         if (mustProvide("binom") && !isRequired("amsmath"))
883                 macros << binom_def << '\n';
884         if (mustProvide("mathcircumflex"))
885                 macros << mathcircumflex_def << '\n';
886
887         // other
888         if (mustProvide("ParagraphLeftIndent"))
889                 macros << paragraphleftindent_def;
890         if (mustProvide("NeedLyXFootnoteCode"))
891                 macros << floatingfootnote_def;
892
893         // some problems with tex->html converters
894         if (mustProvide("NeedTabularnewline"))
895                 macros << tabularnewline_def;
896
897         // greyed-out environment (note inset)
898         // the color is specified in the routine
899         // getColorOptions() to avoid LaTeX-package clashes
900         if (mustProvide("lyxgreyedout"))
901                 macros << lyxgreyedout_def;
902
903         if (mustProvide("lyxdot"))
904                 macros << lyxdot_def << '\n';
905
906         // floats
907         getFloatDefinitions(macros);
908
909         // change tracking
910         if (mustProvide("ct-dvipost"))
911                 macros << changetracking_dvipost_def;
912
913         if (mustProvide("ct-xcolor-ulem")) {
914                 int const prec = macros.precision(2);
915         
916                 RGBColor cadd = rgbFromHexName(lcolor.getX11Name(Color_addedtext));
917                 macros << "\\providecolor{lyxadded}{rgb}{"
918                        << cadd.r / 255.0 << ',' << cadd.g / 255.0 << ',' << cadd.b / 255.0 << "}\n";
919
920                 RGBColor cdel = rgbFromHexName(lcolor.getX11Name(Color_deletedtext));
921                 macros << "\\providecolor{lyxdeleted}{rgb}{"
922                        << cdel.r / 255.0 << ',' << cdel.g / 255.0 << ',' << cdel.b / 255.0 << "}\n";
923
924                 macros.precision(prec);
925                 
926                 if (isRequired("hyperref"))
927                         macros << changetracking_xcolor_ulem_hyperref_def;
928                 else
929                         macros << changetracking_xcolor_ulem_def;
930         }
931
932         if (mustProvide("ct-none"))
933                 macros << changetracking_none_def;
934
935         return macros.str();
936 }
937
938
939 string const LaTeXFeatures::getBabelOptions() const
940 {
941         ostringstream tmp;
942
943         LanguageList::const_iterator it  = UsedLanguages_.begin();
944         LanguageList::const_iterator end =  UsedLanguages_.end();
945         for (; it != end; ++it)
946                 if (!(*it)->latex_options().empty())
947                         tmp << (*it)->latex_options() << '\n';
948         if (!params_.language->latex_options().empty())
949                 tmp << params_.language->latex_options() << '\n';
950
951         return tmp.str();
952 }
953
954
955 docstring const LaTeXFeatures::getTClassPreamble() const
956 {
957         // the text class specific preamble
958         DocumentClass const & tclass = params_.documentClass();
959         odocstringstream tcpreamble;
960
961         tcpreamble << tclass.preamble();
962
963         list<docstring>::const_iterator cit = usedLayouts_.begin();
964         list<docstring>::const_iterator end = usedLayouts_.end();
965         for (; cit != end; ++cit)
966                 tcpreamble << tclass[*cit].preamble();
967
968         cit = usedInsetLayouts_.begin();
969         end = usedInsetLayouts_.end();
970         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
971         for (; cit != end; ++cit) {
972                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
973                 if (it == ils.end())
974                         continue;
975                 tcpreamble << it->second.preamble();
976         }
977
978         return tcpreamble.str();
979 }
980
981
982 docstring const LaTeXFeatures::getTClassHTMLPreamble() const 
983 {
984         DocumentClass const & tclass = params_.documentClass();
985         odocstringstream tcpreamble;
986
987         tcpreamble << tclass.htmlpreamble();
988
989         list<docstring>::const_iterator cit = usedLayouts_.begin();
990         list<docstring>::const_iterator end = usedLayouts_.end();
991         for (; cit != end; ++cit)
992                 tcpreamble << tclass[*cit].htmlpreamble();
993
994         cit = usedInsetLayouts_.begin();
995         end = usedInsetLayouts_.end();
996         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
997         for (; cit != end; ++cit) {
998                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
999                 if (it == ils.end())
1000                         continue;
1001                 tcpreamble << it->second.htmlpreamble();
1002         }
1003
1004         return tcpreamble.str();
1005 }
1006
1007
1008 docstring const LaTeXFeatures::getTClassHTMLStyles() const {
1009         DocumentClass const & tclass = params_.documentClass();
1010         odocstringstream tcpreamble;
1011
1012         list<docstring>::const_iterator cit = usedLayouts_.begin();
1013         list<docstring>::const_iterator end = usedLayouts_.end();
1014         for (; cit != end; ++cit)
1015                 tcpreamble << tclass[*cit].htmlstyle();
1016
1017         cit = usedInsetLayouts_.begin();
1018         end = usedInsetLayouts_.end();
1019         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1020         for (; cit != end; ++cit) {
1021                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1022                 if (it == ils.end())
1023                         continue;
1024                 tcpreamble << it->second.htmlstyle();
1025         }
1026
1027         return tcpreamble.str();
1028 }
1029
1030
1031 namespace {
1032 docstring const getFloatI18nPreamble(docstring const & type, docstring const & name, docstring const & lang)
1033 {
1034         odocstringstream os;
1035         os << "\\addto\\captions" << lang
1036            << "{\\renewcommand{\\" << type << "name}{" << name << "}}\n";
1037         return os.str();
1038 }
1039 }
1040
1041
1042 docstring const LaTeXFeatures::getTClassI18nPreamble(bool use_babel) const
1043 {
1044         DocumentClass const & tclass = params_.documentClass();
1045         // collect preamble snippets in a set to prevent multiple identical
1046         // commands (would happen if e.g. both theorem and theorem* are used)
1047         set<docstring> snippets;
1048         typedef LanguageList::const_iterator lang_it;
1049         lang_it const lbeg = UsedLanguages_.begin();
1050         lang_it const lend =  UsedLanguages_.end();
1051         list<docstring>::const_iterator cit = usedLayouts_.begin();
1052         list<docstring>::const_iterator end = usedLayouts_.end();
1053         for (; cit != end; ++cit) {
1054                 // language dependent commands (once per document)
1055                 snippets.insert(tclass[*cit].langpreamble(buffer().language()));
1056                 // commands for language changing (for multilanguage documents)
1057                 if (use_babel && !UsedLanguages_.empty()) {
1058                         snippets.insert(tclass[*cit].babelpreamble(buffer().language()));
1059                         for (lang_it lit = lbeg; lit != lend; ++lit)
1060                                 snippets.insert(tclass[*cit].babelpreamble(*lit));
1061                 }
1062         }
1063         if (use_babel && !UsedLanguages_.empty()) {
1064                 FloatList const & floats = params_.documentClass().floats();
1065                 UsedFloats::const_iterator fit = usedFloats_.begin();
1066                 UsedFloats::const_iterator fend = usedFloats_.end();
1067                 for (; fit != fend; ++fit) {
1068                         Floating const & fl = floats.getType(fit->first);
1069                         docstring const type = from_ascii(fl.floattype());
1070                         docstring const flname = from_utf8(fl.name());
1071                         docstring name = translateIfPossible(flname,
1072                                 buffer().language()->code());
1073                         snippets.insert(getFloatI18nPreamble(
1074                                 type, name,
1075                                 from_ascii(buffer().language()->babel())));
1076                         for (lang_it lit = lbeg; lit != lend; ++lit) {
1077                                 name = translateIfPossible(flname,
1078                                         (*lit)->code());
1079                                 snippets.insert(getFloatI18nPreamble(
1080                                         type, name,
1081                                         from_ascii((*lit)->babel())));
1082                         }
1083                 }
1084         }
1085
1086         odocstringstream tcpreamble;
1087         set<docstring>::const_iterator const send = snippets.end();
1088         set<docstring>::const_iterator it = snippets.begin();
1089         for (; it != send; ++it)
1090                 tcpreamble << *it;
1091         return tcpreamble.str();
1092 }
1093
1094
1095 docstring const LaTeXFeatures::getLyXSGMLEntities() const
1096 {
1097         // Definition of entities used in the document that are LyX related.
1098         odocstringstream entities;
1099
1100         if (mustProvide("lyxarrow")) {
1101                 entities << "<!ENTITY lyxarrow \"-&gt;\">" << '\n';
1102         }
1103
1104         return entities.str();
1105 }
1106
1107
1108 docstring const LaTeXFeatures::getIncludedFiles(string const & fname) const
1109 {
1110         odocstringstream sgmlpreamble;
1111         // FIXME UNICODE
1112         docstring const basename(from_utf8(onlyPath(fname)));
1113
1114         FileMap::const_iterator end = IncludedFiles_.end();
1115         for (FileMap::const_iterator fi = IncludedFiles_.begin();
1116              fi != end; ++fi)
1117                 // FIXME UNICODE
1118                 sgmlpreamble << "\n<!ENTITY " << fi->first
1119                              << (isSGMLFileName(fi->second) ? " SYSTEM \"" : " \"")
1120                              << makeRelPath(from_utf8(fi->second), basename) << "\">";
1121
1122         return sgmlpreamble.str();
1123 }
1124
1125
1126 void LaTeXFeatures::showStruct() const
1127 {
1128         lyxerr << "LyX needs the following commands when LaTeXing:"
1129                << "\n***** Packages:" << getPackages()
1130                << "\n***** Macros:" << to_utf8(getMacros())
1131                << "\n***** Textclass stuff:" << to_utf8(getTClassPreamble())
1132                << "\n***** done." << endl;
1133 }
1134
1135
1136 Buffer const & LaTeXFeatures::buffer() const
1137 {
1138         return *buffer_;
1139 }
1140
1141
1142 void LaTeXFeatures::setBuffer(Buffer const & buffer)
1143 {
1144         buffer_ = &buffer;
1145 }
1146
1147
1148 BufferParams const & LaTeXFeatures::bufferParams() const
1149 {
1150         return params_;
1151 }
1152
1153
1154 void LaTeXFeatures::getFloatDefinitions(odocstream & os) const
1155 {
1156         FloatList const & floats = params_.documentClass().floats();
1157
1158         // Here we will output the code to create the needed float styles.
1159         // We will try to do this as minimal as possible.
1160         // \floatstyle{ruled}
1161         // \newfloat{algorithm}{htbp}{loa}
1162         // \providecommand{\algorithmname}{Algorithm}
1163         // \floatname{algorithm}{\protect\algorithmname}
1164         UsedFloats::const_iterator cit = usedFloats_.begin();
1165         UsedFloats::const_iterator end = usedFloats_.end();
1166         for (; cit != end; ++cit) {
1167                 Floating const & fl = floats.getType(cit->first);
1168
1169                 // For builtin floats we do nothing.
1170                 if (!fl.needsFloatPkg()) 
1171                         continue;
1172
1173                 // We have to special case "table" and "figure"
1174                 if (fl.floattype() == "tabular" || fl.floattype() == "figure") {
1175                         // Output code to modify "table" or "figure"
1176                         // but only if builtin == false
1177                         // and that have to be true at this point in the
1178                         // function.
1179                         docstring const type = from_ascii(fl.floattype());
1180                         docstring const placement = from_ascii(fl.placement());
1181                         docstring const style = from_ascii(fl.style());
1182                         if (!style.empty()) {
1183                                 os << "\\floatstyle{" << style << "}\n"
1184                                    << "\\restylefloat{" << type << "}\n";
1185                         }
1186                         if (!placement.empty()) {
1187                                 os << "\\floatplacement{" << type << "}{"
1188                                    << placement << "}\n";
1189                         }
1190                 } else {
1191                         // The other non builtin floats.
1192
1193                         docstring const type = from_ascii(fl.floattype());
1194                         docstring const placement = from_ascii(fl.placement());
1195                         docstring const ext = from_ascii(fl.ext());
1196                         docstring const within = from_ascii(fl.within());
1197                         docstring const style = from_ascii(fl.style());
1198                         docstring const name = translateIfPossible(
1199                                         from_utf8(fl.name()),
1200                                         buffer().language()->code());
1201                         os << "\\floatstyle{" << style << "}\n"
1202                            << "\\newfloat{" << type << "}{" << placement
1203                            << "}{" << ext << '}';
1204                         if (!within.empty())
1205                                 os << '[' << within << ']';
1206                         os << '\n'
1207                            << "\\providecommand{\\" << type << "name}{"
1208                            << name << "}\n"
1209                            << "\\floatname{" << type << "}{\\protect\\"
1210                            << type << "name}\n";
1211
1212                         // What missing here is to code to minimalize the code
1213                         // output so that the same floatstyle will not be
1214                         // used several times, when the same style is still in
1215                         // effect. (Lgb)
1216                 }
1217                 if (cit->second)
1218                         os << "\n\\newsubfloat{" << from_ascii(fl.floattype()) << "}\n";
1219         }
1220 }
1221
1222
1223 } // namespace lyx