]> git.lyx.org Git - lyx.git/blob - src/LaTeXFeatures.cpp
Fix thinko in loop detection
[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 "LaTeXFonts.h"
28 #include "LaTeXPackages.h"
29 #include "Layout.h"
30 #include "Lexer.h"
31 #include "LyXRC.h"
32 #include "TextClass.h"
33
34 #include "insets/InsetLayout.h"
35
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/FileName.h"
39 #include "support/filetools.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42 #include "support/regex.h"
43
44 #include <algorithm>
45
46
47 using namespace std;
48 using namespace lyx::support;
49
50
51 namespace lyx {
52
53 /////////////////////////////////////////////////////////////////////
54 //
55 // Strings
56 //
57 /////////////////////////////////////////////////////////////////////
58
59 //\NeedsTeXFormat{LaTeX2e}
60 //\ProvidesPackage{lyx}[1996/01/11 LLE v0.2 (LyX LaTeX Extensions)]
61 //\message{LyX LaTeX Extensions (LLE v0.2) of 11-Jan-1996.}
62
63 static docstring const lyx_def = from_ascii(
64         "\\providecommand{\\LyX}{L\\kern-.1667em\\lower.25em\\hbox{Y}\\kern-.125emX\\@}");
65
66 static docstring const lyx_hyperref_def = from_ascii(
67         "\\providecommand{\\LyX}{\\texorpdfstring%\n"
68         "  {L\\kern-.1667em\\lower.25em\\hbox{Y}\\kern-.125emX\\@}\n"
69         "  {LyX}}");
70
71 static docstring const noun_def = from_ascii(
72         "\\newcommand{\\noun}[1]{\\textsc{#1}}");
73
74 static docstring const lyxarrow_def = from_ascii(
75         "\\DeclareRobustCommand*{\\lyxarrow}{%\n"
76         "\\@ifstar\n"
77         "{\\leavevmode\\,$\\triangleleft$\\,\\allowbreak}\n"
78         "{\\leavevmode\\,$\\triangleright$\\,\\allowbreak}}");
79
80 // for quotes without babel. This does not give perfect results, but
81 // anybody serious about non-english quotes should use babel (JMarc).
82
83 static docstring const quotedblbase_def = from_ascii(
84         "\\ProvideTextCommandDefault{\\quotedblbase}{%\n"
85         "  \\raisebox{-1.4ex}[1ex][.5ex]{\\textquotedblright}%\n"
86         "  \\penalty10000\\hskip0em\\relax%\n"
87         "}");
88
89 static docstring const quotesinglbase_def = from_ascii(
90         "\\ProvideTextCommandDefault{\\quotesinglbase}{%\n"
91         "  \\raisebox{-1.4ex}[1ex][.5ex]{\\textquoteright}%\n"
92         "  \\penalty10000\\hskip0em\\relax%\n"
93         "}");
94
95 static docstring const guillemotleft_def = from_ascii(
96         "\\ProvideTextCommandDefault{\\guillemotleft}{%\n"
97         "  {\\usefont{U}{lasy}{m}{n}\\char'50\\kern-.15em\\char'50}%\n"
98         "\\penalty10000\\hskip0pt\\relax%\n"
99         "}");
100
101 static docstring const guillemotright_def = from_ascii(
102         "\\ProvideTextCommandDefault{\\guillemotright}{%\n"
103         "  \\penalty10000\\hskip0pt%\n"
104         "  {\\usefont{U}{lasy}{m}{n}\\char'51\\kern-.15em\\char'51}%\n"
105         "}");
106
107 static docstring const guilsinglleft_def = from_ascii(
108         "\\ProvideTextCommandDefault{\\guilsinglleft}{%\n"
109         "  {\\usefont{U}{lasy}{m}{n}\\char'50}%\n"
110         "  \\penalty10000\\hskip0pt\\relax%\n"
111         "}");
112
113 static docstring const guilsinglright_def = from_ascii(
114         "\\ProvideTextCommandDefault{\\guilsinglright}{%\n"
115         "  \\penalty10000\\hskip0pt%\n"
116         "  {\\usefont{U}{lasy}{m}{n}\\char'51}%\n"
117         "}");
118
119 static docstring const paragraphleftindent_def = from_ascii(
120         "\\newenvironment{LyXParagraphLeftIndent}[1]%\n"
121         "{\n"
122         "  \\begin{list}{}{%\n"
123         "    \\setlength{\\topsep}{0pt}%\n"
124         "    \\addtolength{\\leftmargin}{#1}\n"
125 // ho hum, yet more things commented out with no hint as to why they
126 // weren't just removed
127 //      "%%    \\addtolength{\\leftmargin}{#1\\textwidth}\n"
128 //      "%%    \\setlength{\\textwidth}{#2\\textwidth}\n"
129 //      "%%    \\setlength\\listparindent\\parindent%\n"
130 //      "%%    \\setlength\\itemindent\\parindent%\n"
131         "    \\setlength{\\parsep}{0pt plus 1pt}%\n"
132         "  }\n"
133         "  \\item[]\n"
134         "}\n"
135         "{\\end{list}}\n");
136
137 static docstring const floatingfootnote_def = from_ascii(
138         "%% Special footnote code from the package 'stblftnt.sty'\n"
139         "%% Author: Robin Fairbairns -- Last revised Dec 13 1996\n"
140         "\\let\\SF@@footnote\\footnote\n"
141         "\\def\\footnote{\\ifx\\protect\\@typeset@protect\n"
142         "    \\expandafter\\SF@@footnote\n"
143         "  \\else\n"
144         "    \\expandafter\\SF@gobble@opt\n"
145         "  \\fi\n"
146         "}\n"
147         "\\expandafter\\def\\csname SF@gobble@opt \\endcsname{\\@ifnextchar[%]\n"
148         "  \\SF@gobble@twobracket\n"
149         "  \\@gobble\n"
150         "}\n"
151         "\\edef\\SF@gobble@opt{\\noexpand\\protect\n"
152         "  \\expandafter\\noexpand\\csname SF@gobble@opt \\endcsname}\n"
153         "\\def\\SF@gobble@twobracket[#1]#2{}\n");
154
155 static docstring const binom_def = from_ascii(
156         "%% Binom macro for standard LaTeX users\n"
157         "\\newcommand{\\binom}[2]{{#1 \\choose #2}}\n");
158
159 static docstring const mathcircumflex_def = from_ascii(
160         "%% For printing a cirumflex inside a formula\n"
161         "\\newcommand{\\mathcircumflex}[0]{\\mbox{\\^{}}}\n");
162
163 static docstring const tabularnewline_def = from_ascii(
164         "%% Because html converters don't know tabularnewline\n"
165         "\\providecommand{\\tabularnewline}{\\\\}\n");
166
167 static docstring const lyxgreyedout_def = from_ascii(
168         "%% The greyedout annotation environment\n"
169         "\\newenvironment{lyxgreyedout}\n"
170         "  {\\textcolor{note_fontcolor}\\bgroup\\ignorespaces}\n"
171         "  {\\ignorespacesafterend\\egroup}\n");
172
173 // We want to omit the file extension for includegraphics, but this does not
174 // work when the filename contains other dots.
175 // Idea from http://www.tex.ac.uk/cgi-bin/texfaq2html?label=unkgrfextn
176 static docstring const lyxdot_def = from_ascii(
177         "%% A simple dot to overcome graphicx limitations\n"
178         "\\newcommand{\\lyxdot}{.}\n");
179
180 static docstring const changetracking_dvipost_def = from_ascii(
181         "%% Change tracking with dvipost\n"
182         "\\dvipostlayout\n"
183         "\\dvipost{osstart color push Red}\n"
184         "\\dvipost{osend color pop}\n"
185         "\\dvipost{cbstart color push Blue}\n"
186         "\\dvipost{cbend color pop}\n"
187         "\\DeclareRobustCommand{\\lyxadded}[3]{\\changestart#3\\changeend}\n"
188         "\\DeclareRobustCommand{\\lyxdeleted}[3]{%\n"
189         "\\changestart\\overstrikeon#3\\overstrikeoff\\changeend}\n");
190
191 static docstring const changetracking_xcolor_ulem_def = from_ascii(
192         "%% Change tracking with ulem\n"
193         "\\DeclareRobustCommand{\\lyxadded}[3]{{\\color{lyxadded}{}#3}}\n"
194         "\\DeclareRobustCommand{\\lyxdeleted}[3]{{\\color{lyxdeleted}\\sout{#3}}}\n");
195
196 static docstring const changetracking_xcolor_ulem_hyperref_def = from_ascii(
197         "%% Change tracking with ulem\n"
198         "\\DeclareRobustCommand{\\lyxadded}[3]{{\\texorpdfstring{\\color{lyxadded}{}}{}#3}}\n"
199         "\\DeclareRobustCommand{\\lyxdeleted}[3]{{\\texorpdfstring{\\color{lyxdeleted}\\sout{#3}}{}}}\n");
200
201 static docstring const changetracking_none_def = from_ascii(
202         "\\newcommand{\\lyxadded}[3]{#3}\n"
203         "\\newcommand{\\lyxdeleted}[3]{}\n");
204
205 static docstring const textgreek_def = from_ascii(
206         "\\DeclareRobustCommand{\\greektext}{%\n"
207         "  \\fontencoding{LGR}\\selectfont\\def\\encodingdefault{LGR}}\n"
208         "\\DeclareRobustCommand{\\textgreek}[1]{\\leavevmode{\\greektext #1}}\n"
209         "\\DeclareFontEncoding{LGR}{}{}\n"
210         "\\DeclareTextSymbol{\\~}{LGR}{126}");
211
212 static docstring const textcyr_def = from_ascii(
213         "\\DeclareRobustCommand{\\cyrtext}{%\n"
214         "  \\fontencoding{T2A}\\selectfont\\def\\encodingdefault{T2A}}\n"
215         "\\DeclareRobustCommand{\\textcyr}[1]{\\leavevmode{\\cyrtext #1}}\n"
216         "\\AtBeginDocument{\\DeclareFontEncoding{T2A}{}{}}\n");
217
218 static docstring const lyxmathsym_def = from_ascii(
219         "\\newcommand{\\lyxmathsym}[1]{\\ifmmode\\begingroup\\def\\b@ld{bold}\n"
220         "  \\text{\\ifx\\math@version\\b@ld\\bfseries\\fi#1}\\endgroup\\else#1\\fi}\n");
221
222 static docstring const papersizedvi_def = from_ascii(
223         "\\special{papersize=\\the\\paperwidth,\\the\\paperheight}\n");
224
225 static docstring const papersizepdf_def = from_ascii(
226         "\\pdfpageheight\\paperheight\n"
227         "\\pdfpagewidth\\paperwidth\n");
228
229 static docstring const cedilla_def = from_ascii(
230         "\\newcommand{\\docedilla}[2]{\\underaccent{#1\\mathchar'30}{#2}}\n"
231         "\\newcommand{\\cedilla}[1]{\\mathpalette\\docedilla{#1}}\n");
232
233 static docstring const subring_def = from_ascii(
234         "\\newcommand{\\dosubring}[2]{\\underaccent{#1\\mathchar'27}{#2}}\n"
235         "\\newcommand{\\subring}[1]{\\mathpalette\\dosubring{#1}}\n");
236
237 static docstring const subdot_def = from_ascii(
238         "\\newcommand{\\dosubdot}[2]{\\underaccent{#1.}{#2}}\n"
239         "\\newcommand{\\subdot}[1]{\\mathpalette\\dosubdot{#1}}\n");
240
241 static docstring const subhat_def = from_ascii(
242         "\\newcommand{\\dosubhat}[2]{\\underaccent{#1\\mathchar'136}{#2}}\n"
243         "\\newcommand{\\subhat}[1]{\\mathpalette\\dosubhat{#1}}\n");
244
245 static docstring const subtilde_def = from_ascii(
246         "\\newcommand{\\dosubtilde}[2]{\\underaccent{#1\\mathchar'176}{#2}}\n"
247         "\\newcommand{\\subtilde}[1]{\\mathpalette\\dosubtilde{#1}}\n");
248
249 static docstring const dacute_def = from_ascii(
250         "\\DeclareMathAccent{\\dacute}{\\mathalpha}{operators}{'175}\n");
251
252 static docstring const tipasymb_def = from_ascii(
253         "\\DeclareFontEncoding{T3}{}{}\n"
254         "\\DeclareSymbolFont{tipasymb}{T3}{cmr}{m}{n}\n");
255
256 static docstring const dgrave_def = from_ascii(
257         "\\DeclareMathAccent{\\dgrave}{\\mathord}{tipasymb}{'15}\n");
258
259 static docstring const rcap_def = from_ascii(
260         "\\DeclareMathAccent{\\rcap}{\\mathord}{tipasymb}{'20}\n");
261
262 static docstring const ogonek_def = from_ascii(
263         "\\newcommand{\\doogonek}[2]{\\setbox0=\\hbox{$#1#2$}\\underaccent{#1\\mkern-6mu\n"
264         "  \\ifx#2O\\hskip0.5\\wd0\\else\\ifx#2U\\hskip0.5\\wd0\\else\\hskip\\wd0\\fi\\fi\n"
265         "  \\ifx#2o\\mkern-2mu\\else\\ifx#2e\\mkern-1mu\\fi\\fi\n"
266         "  \\mathchar\"0\\hexnumber@\\symtipasymb0C}{#2}}\n"
267         "\\newcommand{\\ogonek}[1]{\\mathpalette\\doogonek{#1}}\n");
268
269 static docstring const lyxref_def = from_ascii(
270                 "\\RS@ifundefined{subref}\n"
271                 "  {\\def\\RSsubtxt{section~}\\newref{sub}{name = \\RSsubtxt}}\n"
272                 "  {}\n"
273                 "\\RS@ifundefined{thmref}\n"
274                 "  {\\def\\RSthmtxt{theorem~}\\newref{thm}{name = \\RSthmtxt}}\n"
275                 "  {}\n"
276                 "\\RS@ifundefined{lemref}\n"
277                 "  {\\def\\RSlemtxt{lemma~}\\newref{lem}{name = \\RSlemtxt}}\n" 
278                 "  {}\n");
279
280 // Make sure the columns are also outputed as rtl
281 static docstring const rtloutputdblcol_def = from_ascii(
282         "\\def\\@outputdblcol{%\n"
283         "  \\if@firstcolumn\n"
284         "    \\global \\@firstcolumnfalse\n"
285         "    \\global \\setbox\\@leftcolumn \\box\\@outputbox\n"
286         "  \\else\n"
287         "    \\global \\@firstcolumntrue\n"
288         "    \\setbox\\@outputbox \\vbox {%\n"
289         "      \\hb@xt@\\textwidth {%\n"
290         "      \\kern\\textwidth \\kern-\\columnwidth %**\n"
291         "      \\hb@xt@\\columnwidth {%\n"
292         "         \\box\\@leftcolumn \\hss}%\n"
293         "      \\kern-\\textwidth %**\n"
294         "      \\hfil\n"
295         "      {\\normalcolor\\vrule \\@width\\columnseprule}%\n"
296         "      \\hfil\n"
297         "      \\kern-\\textwidth  %**\n"
298         "      \\hb@xt@\\columnwidth {%\n"
299         "         \\box\\@outputbox \\hss}%\n"
300         "      \\kern-\\columnwidth \\kern\\textwidth %**\n"
301         "    }%\n"
302         "  }%\n"
303         "  \\@combinedblfloats\n"
304         "  \\@outputpage\n"
305         "  \\begingroup\n"
306         "  \\@dblfloatplacement\n"
307         "  \\@startdblcolumn\n"
308         "  \\@whilesw\\if@fcolmade \\fi\n"
309         "  {\\@outputpage\n"
310         "    \\@startdblcolumn}%\n"
311         "  \\endgroup\n"
312         "  \\fi\n"
313         "}\n"
314         "\\@mparswitchtrue\n");
315
316
317 /////////////////////////////////////////////////////////////////////
318 //
319 // LyXHTML strings
320 //
321 /////////////////////////////////////////////////////////////////////
322
323 static docstring const lyxnoun_style = from_ascii(
324         "dfn.lyxnoun {\n"
325   "  font-variant: small-caps;\n"
326   "}\n");
327
328
329 // this is how it normally renders, but it might not always do so.
330 static docstring const lyxstrikeout_style = from_ascii(
331         "del.strikeout {\n"
332   "  text-decoration: line-through;\n"
333   "}\n");
334
335
336 /////////////////////////////////////////////////////////////////////
337 //
338 // LaTeXFeatures
339 //
340 /////////////////////////////////////////////////////////////////////
341
342
343 LaTeXFeatures::LaTeXFeatures(Buffer const & b, BufferParams const & p,
344                              OutputParams const & r)
345         : buffer_(&b), params_(p), runparams_(r), in_float_(false)
346 {}
347
348
349 LaTeXFeatures::LangPackage LaTeXFeatures::langPackage() const
350 {
351         string const local_lp = bufferParams().lang_package;
352
353         // Locally, custom is just stored as a string
354         // in bufferParams().lang_package.
355         if (local_lp != "auto"
356             && local_lp != "babel"
357             && local_lp != "default"
358             && local_lp != "none")
359                  return LANG_PACK_CUSTOM;
360
361         if (local_lp == "none")
362                 return LANG_PACK_NONE;
363
364         /* If "auto" is selected, we load polyglossia if required,
365          * else we select babel.
366          * If babel is selected (either directly or via the "auto"
367          * mechanism), we really do only require it if we have
368          * a language that needs it.
369          */
370         bool const polyglossia_required =
371                 isRequired("polyglossia")
372                 && isAvailable("polyglossia")
373                 && !isProvided("babel")
374                 && this->hasOnlyPolyglossiaLanguages();
375         bool const babel_required = 
376                 !bufferParams().language->babel().empty()
377                 || !this->getBabelLanguages().empty();
378
379         if (local_lp == "auto") {
380                 // polyglossia requirement has priority over babel
381                 if (polyglossia_required)
382                         return LANG_PACK_POLYGLOSSIA;
383                 else if (babel_required)
384                         return LANG_PACK_BABEL;
385         }
386
387         if (local_lp == "babel") {
388                 if (babel_required)
389                         return LANG_PACK_BABEL;
390         }
391
392         if (local_lp == "default") {
393                 switch (lyxrc.language_package_selection) {
394                 case LyXRC::LP_AUTO:
395                         // polyglossia requirement has priority over babel
396                         if (polyglossia_required)
397                                 return LANG_PACK_POLYGLOSSIA;
398                         else if (babel_required)
399                                 return LANG_PACK_BABEL;
400                         break;
401                 case LyXRC::LP_BABEL:
402                         if (babel_required)
403                                 return LANG_PACK_BABEL;
404                         break;
405                 case LyXRC::LP_CUSTOM:
406                         return LANG_PACK_CUSTOM;
407                 case LyXRC::LP_NONE:
408                         return LANG_PACK_NONE;
409                 }
410         }
411
412         return LANG_PACK_NONE;
413 }
414
415
416 void LaTeXFeatures::require(string const & name)
417 {
418         features_.insert(name);
419 }
420
421
422 void LaTeXFeatures::require(set<string> const & names)
423 {
424         features_.insert(names.begin(), names.end());
425 }
426
427
428 void LaTeXFeatures::useLayout(docstring const & layoutname)
429 {
430         // Some code to avoid loops in dependency definition
431         // FIXME THREAD
432         static int level = 0;
433         const int maxlevel = 30;
434         if (level > maxlevel) {
435                 lyxerr << "LaTeXFeatures::useLayout: maximum level of "
436                        << "recursion attained by layout "
437                        << to_utf8(layoutname) << endl;
438                 return;
439         }
440
441         DocumentClass const & tclass = params_.documentClass();
442         if (tclass.hasLayout(layoutname)) {
443                 // Is this layout already in usedLayouts?
444                 if (find(usedLayouts_.begin(), usedLayouts_.end(), layoutname)
445                     != usedLayouts_.end())
446                         return;
447
448                 Layout const & layout = tclass[layoutname];
449                 require(layout.requires());
450
451                 if (!layout.depends_on().empty()) {
452                         ++level;
453                         useLayout(layout.depends_on());
454                         --level;
455                 }
456                 usedLayouts_.push_back(layoutname);
457         } else {
458                 lyxerr << "LaTeXFeatures::useLayout: layout `"
459                        << to_utf8(layoutname) << "' does not exist in this class"
460                        << endl;
461         }
462
463         --level;
464 }
465
466
467 void LaTeXFeatures::useInsetLayout(InsetLayout const & lay)
468 {
469         docstring const & lname = lay.name();
470         DocumentClass const & tclass = params_.documentClass();
471
472         // this is a default inset layout, nothing useful here
473         if (!tclass.hasInsetLayout(lname))
474                 return;
475         // Is this layout already in usedInsetLayouts?
476         if (find(usedInsetLayouts_.begin(), usedInsetLayouts_.end(), lname)
477                         != usedInsetLayouts_.end())
478                 return;
479
480         require(lay.requires());
481         usedInsetLayouts_.push_back(lname);
482 }
483
484
485 bool LaTeXFeatures::isRequired(string const & name) const
486 {
487         return features_.find(name) != features_.end();
488 }
489
490
491 bool LaTeXFeatures::isProvided(string const & name) const
492 {
493         if (params_.useNonTeXFonts)
494                 return params_.documentClass().provides(name);
495
496         bool const ot1 = (params_.font_encoding() == "default"
497                 || params_.font_encoding() == "OT1");
498         bool const complete = (params_.fonts_sans == "default")
499                 && (params_.fonts_typewriter == "default");
500         bool const nomath = (params_.fonts_math == "default");
501         return params_.documentClass().provides(name)
502                 || theLaTeXFonts().getLaTeXFont(
503                         from_ascii(params_.fonts_roman)).provides(name, ot1,
504                                                                   complete,
505                                                                   nomath)
506                 || theLaTeXFonts().getLaTeXFont(
507                         from_ascii(params_.fonts_sans)).provides(name, ot1,
508                                                                  complete,
509                                                                  nomath)
510                 || theLaTeXFonts().getLaTeXFont(
511                         from_ascii(params_.fonts_typewriter)).provides(name, ot1,
512                                                                        complete,
513                                                                        nomath)
514                 || theLaTeXFonts().getLaTeXFont(
515                         from_ascii(params_.fonts_math)).provides(name, ot1,
516                                                                        complete,
517                                                                        nomath);
518 }
519
520
521 bool LaTeXFeatures::mustProvide(string const & name) const
522 {
523         return isRequired(name) && !isProvided(name);
524 }
525
526
527 bool LaTeXFeatures::isAvailable(string const & name)
528 {
529         string::size_type const i = name.find("->");
530         if (i != string::npos) {
531                 string const from = name.substr(0,i);
532                 string const to = name.substr(i+2);
533                 //LYXERR0("from=[" << from << "] to=[" << to << "]");
534                 return theConverters().isReachable(from, to);
535         }
536         return LaTeXPackages::isAvailable(name);
537 }
538
539
540 void LaTeXFeatures::addPreambleSnippet(string const & preamble)
541 {
542         SnippetList::const_iterator begin = preamble_snippets_.begin();
543         SnippetList::const_iterator end   = preamble_snippets_.end();
544         if (find(begin, end, preamble) == end)
545                 preamble_snippets_.push_back(preamble);
546 }
547
548
549 void LaTeXFeatures::addCSSSnippet(std::string const & snippet)
550 {
551         SnippetList::const_iterator begin = css_snippets_.begin();
552         SnippetList::const_iterator end   = css_snippets_.end();
553         if (find(begin, end, snippet) == end)
554                 css_snippets_.push_back(snippet);
555 }
556
557
558 void LaTeXFeatures::useFloat(string const & name, bool subfloat)
559 {
560         if (!usedFloats_[name])
561                 usedFloats_[name] = subfloat;
562         if (subfloat)
563                 require("subfig");
564         // We only need float.sty if we use non builtin floats, or if we
565         // use the "H" modifier. This includes modified table and
566         // figure floats. (Lgb)
567         Floating const & fl = params_.documentClass().floats().getType(name);
568         if (!fl.floattype().empty() && fl.usesFloatPkg()) {
569                 require("float");
570         }
571 }
572
573
574 void LaTeXFeatures::useLanguage(Language const * lang)
575 {
576         if (!lang->babel().empty() || !lang->polyglossia().empty())
577                 UsedLanguages_.insert(lang);
578         if (!lang->requires().empty())
579                 require(lang->requires());
580         // CJK languages do not have a babel name.
581         // They use the CJK package
582         if (lang->encoding()->package() == Encoding::CJK)
583                 require("CJK");
584         // japanese package is special
585         if (lang->encoding()->package() == Encoding::japanese)
586                 require("japanese");
587 }
588
589
590 void LaTeXFeatures::includeFile(docstring const & key, string const & name)
591 {
592         IncludedFiles_[key] = name;
593 }
594
595
596 bool LaTeXFeatures::hasLanguages() const
597 {
598         return !UsedLanguages_.empty();
599 }
600
601
602 bool LaTeXFeatures::hasOnlyPolyglossiaLanguages() const
603 {
604         // first the main language
605         if (params_.language->polyglossia().empty())
606                 return false;
607         // now the secondary languages
608         LanguageList::const_iterator const begin = UsedLanguages_.begin();
609         for (LanguageList::const_iterator cit = begin;
610              cit != UsedLanguages_.end();
611              ++cit) {
612                 if ((*cit)->polyglossia().empty())
613                         return false;
614         }
615         return true;
616 }
617
618
619 bool LaTeXFeatures::hasPolyglossiaExclusiveLanguages() const
620 {
621         // first the main language
622         if (params_.language->isPolyglossiaExclusive())
623                 return true;
624         // now the secondary languages
625         LanguageList::const_iterator const begin = UsedLanguages_.begin();
626         for (LanguageList::const_iterator cit = begin;
627              cit != UsedLanguages_.end();
628              ++cit) {
629                 if ((*cit)->isPolyglossiaExclusive())
630                         return true;
631         }
632         return false;
633 }
634
635
636 string LaTeXFeatures::getBabelLanguages() const
637 {
638         ostringstream languages;
639
640         bool first = true;
641         LanguageList::const_iterator const begin = UsedLanguages_.begin();
642         for (LanguageList::const_iterator cit = begin;
643              cit != UsedLanguages_.end();
644              ++cit) {
645                 if ((*cit)->babel().empty())
646                         continue;
647                 if (!first)
648                         languages << ',';
649                 else
650                         first = false;
651                 languages << (*cit)->babel();
652         }
653         return languages.str();
654 }
655
656
657 std::map<std::string, std::string> LaTeXFeatures::getPolyglossiaLanguages() const
658 {
659         std::map<std::string, std::string> languages;
660
661         LanguageList::const_iterator const begin = UsedLanguages_.begin();
662         for (LanguageList::const_iterator cit = begin;
663              cit != UsedLanguages_.end();
664              ++cit) {
665                 languages[(*cit)->polyglossia()] = (*cit)->polyglossiaOpts();
666         }
667         return languages;
668 }
669
670
671 set<string> LaTeXFeatures::getEncodingSet(string const & doc_encoding) const
672 {
673         // This does only find encodings of languages supported by babel, but
674         // that does not matter since we don't have a language with an
675         // encoding supported by inputenc but without babel support.
676         set<string> encodings;
677         LanguageList::const_iterator it  = UsedLanguages_.begin();
678         LanguageList::const_iterator end = UsedLanguages_.end();
679         for (; it != end; ++it)
680                 if ((*it)->encoding()->latexName() != doc_encoding &&
681                     ((*it)->encoding()->package() == Encoding::inputenc
682                      || (*it)->encoding()->package() == Encoding::japanese))
683                         encodings.insert((*it)->encoding()->latexName());
684         return encodings;
685 }
686
687 namespace {
688
689 char const * simplefeatures[] = {
690 // note that the package order here will be the same in the LaTeX-output
691         "array",
692         "verbatim",
693         "longtable",
694         "rotating",
695         "latexsym",
696         "pifont",
697         // subfig is handled in BufferParams.cpp
698         "varioref",
699         "prettyref",
700         "refstyle",
701         /*For a successful cooperation of the `wrapfig' package with the
702           `float' package you should load the `wrapfig' package *after*
703           the `float' package. See the caption package documentation
704           for explanation.*/
705         "float",
706         "rotfloat",
707         "wrapfig",
708         "booktabs",
709         "dvipost",
710         "fancybox",
711         "calc",
712         "units",
713         "framed",
714         "soul",
715         "textcomp",
716         "pmboxdraw",
717         "bbding",
718         "ifsym",
719         "marvosym",
720         "txfonts",
721         "pxfonts",
722         "mathdesign",
723         "mathrsfs",
724         "mathabx",
725         "mathtools",
726         // "cancel",
727         "ascii",
728         "url",
729         "covington",
730         "csquotes",
731         "enumitem",
732         "endnotes",
733         "hhline",
734         "ifthen",
735         // listings is handled in BufferParams.cpp
736         "bm",
737         "pdfpages",
738         "amscd",
739         "slashed",
740         "multicol",
741         "multirow",
742         "tfrupee",
743         "shapepar",
744         "rsphrase",
745         "algorithm2e"
746 };
747
748 char const * bibliofeatures[] = {
749         // Known bibliography packages (will be loaded before natbib)
750         "achicago",
751         "apacite",
752         "apalike",
753         "astron",
754         "authordate1-4",
755         "babelbib",
756         "bibgerm",
757         "chicago",
758         "chscite",
759         "harvard",
760         "mslapa",
761         "named"
762 };
763
764 int const nb_bibliofeatures = sizeof(bibliofeatures) / sizeof(char const *);
765
766 int const nb_simplefeatures = sizeof(simplefeatures) / sizeof(char const *);
767
768 }
769
770
771 string const LaTeXFeatures::getColorOptions() const
772 {
773         ostringstream colors;
774
775         // Handling the color packages separately is needed to be able to load them
776         // before babel when hyperref is loaded with the colorlinks option
777         // for more info see Bufferparams.cpp
778
779         // [x]color.sty
780         if (mustProvide("color") || mustProvide("xcolor")) {
781                 string const package =
782                         (mustProvide("xcolor") ? "xcolor" : "color");
783                 if (params_.graphics_driver == "default"
784                         || params_.graphics_driver == "none")
785                         colors << "\\usepackage{" << package << "}\n";
786                 else
787                         colors << "\\usepackage["
788                                  << params_.graphics_driver
789                                  << "]{" << package << "}\n";
790         }
791
792         // pdfcolmk must be loaded after color
793         if (mustProvide("pdfcolmk"))
794                 colors << "\\usepackage{pdfcolmk}\n";
795
796         // the following 3 color commands must be set after color
797         // is loaded and before pdfpages, therefore add the command
798         // here define the set color
799         if (mustProvide("pagecolor")) {
800                 colors << "\\definecolor{page_backgroundcolor}{rgb}{";
801                 colors << outputLaTeXColor(params_.backgroundcolor) << "}\n";
802                 // set the page color
803                 colors << "\\pagecolor{page_backgroundcolor}\n";
804         }
805
806         if (mustProvide("fontcolor")) {
807                 colors << "\\definecolor{document_fontcolor}{rgb}{";
808                 colors << outputLaTeXColor(params_.fontcolor) << "}\n";
809                 // set the color
810                 colors << "\\color{document_fontcolor}\n";
811         }
812
813         if (mustProvide("lyxgreyedout")) {
814                 colors << "\\definecolor{note_fontcolor}{rgb}{";
815                 colors << outputLaTeXColor(params_.notefontcolor) << "}\n";
816                 // the color will be set together with the definition of
817                 // the lyxgreyedout environment (see lyxgreyedout_def)
818         }
819
820         // color for shaded boxes
821         if (isRequired("framed") && mustProvide("color")) {
822                 colors << "\\definecolor{shadecolor}{rgb}{";
823                 colors << outputLaTeXColor(params_.boxbgcolor) << "}\n";
824                 // this color is automatically used by the LaTeX-package "framed"
825         }
826
827         return colors.str();
828 }
829
830
831 string const LaTeXFeatures::getPackages() const
832 {
833         ostringstream packages;
834
835         // FIXME: currently, we can only load packages and macros known
836         // to LyX.
837         // However, with the Require tag of layouts/custom insets,
838         // also unknown packages can be requested. They are silently
839         // swallowed now. We should change this eventually.
840
841         // Output all the package option stuff we have been asked to do.
842         map<string, string>::const_iterator it =
843             params_.documentClass().packageOptions().begin();
844         map<string, string>::const_iterator en =
845             params_.documentClass().packageOptions().end();
846         for (; it != en; ++it)
847                 if (mustProvide(it->first))
848                         packages << "\\PassOptionsToPackage{" << it->second << "}"
849                                  << "{" << it->first << "}\n";
850
851         //  These are all the 'simple' includes.  i.e
852         //  packages which we just \usepackage{package}
853         for (int i = 0; i < nb_simplefeatures; ++i) {
854                 if (mustProvide(simplefeatures[i]))
855                         packages << "\\usepackage{" << simplefeatures[i] << "}\n";
856         }
857
858         // The rest of these packages are somewhat more complicated
859         // than those above.
860
861         // The tipa package and its extensions (tipx, tone) must not
862         // be loaded with non-TeX fonts, since fontspec includes the
863         // respective macros
864         if (mustProvide("tipa") && !params_.useNonTeXFonts)
865                 packages << "\\usepackage{tipa}\n";
866         if (mustProvide("tipx") && !params_.useNonTeXFonts)
867                 packages << "\\usepackage{tipx}\n";
868         if (mustProvide("tone") && !params_.useNonTeXFonts)
869                 packages << "\\usepackage{tone}\n";
870
871         // if fontspec or newtxmath is used, AMS packages have to be loaded
872         // before fontspec (in BufferParams)
873         string const amsPackages = loadAMSPackages();
874         bool const ot1 = (params_.font_encoding() == "default" || params_.font_encoding() == "OT1");
875         bool const use_newtxmath =
876                 theLaTeXFonts().getLaTeXFont(from_ascii(params_.fonts_math)).getUsedPackage(
877                         ot1, false, false) == "newtxmath";
878         
879         if (!params_.useNonTeXFonts && !use_newtxmath && !amsPackages.empty())
880                 packages << amsPackages;
881
882         // fixltx2e must be loaded after amsthm, since amsthm produces an error with
883         // the redefined \[ command (bug 7233). Load it as early as possible, since
884         // other packages might profit from it.
885         if (mustProvide("fixltx2e"))
886                 packages << "\\usepackage{fixltx2e}\n";
887
888         if (mustProvide("cancel") &&
889             params_.use_package("cancel") != BufferParams::package_off)
890                 packages << "\\usepackage{cancel}\n";
891         // wasysym is a simple feature, but it must be after amsmath if both
892         // are used
893         // wasysym redefines some integrals (e.g. iint) from amsmath. That
894         // leads to inconsistent integrals. We only load this package if
895         // the document does not contain integrals (then isRequired("esint")
896         // is false) or if esint is used, since esint redefines all relevant
897         // integral symbols from wasysym and amsmath.
898         // See http://www.lyx.org/trac/ticket/1942
899         if (mustProvide("wasysym") &&
900             params_.use_package("wasysym") != BufferParams::package_off &&
901             (params_.use_package("esint") != BufferParams::package_off || !isRequired("esint")))
902                 packages << "\\usepackage{wasysym}\n";
903
904         // accents must be loaded after amsmath
905         if (mustProvide("accents") &&
906             params_.use_package("accents") != BufferParams::package_off)
907                 packages << "\\usepackage{accents}\n";
908
909         // mathdots must be loaded after amsmath
910         if (mustProvide("mathdots") &&
911                 params_.use_package("mathdots") != BufferParams::package_off)
912                 packages << "\\usepackage{mathdots}\n";
913
914         // yhmath must be loaded after amsmath
915         if (mustProvide("yhmath") &&
916             params_.use_package("yhmath") != BufferParams::package_off)
917                 packages << "\\usepackage{yhmath}\n";
918
919         // stmaryrd must be loaded after amsmath
920         if (mustProvide("stmaryrd") &&
921             params_.use_package("stmaryrd") != BufferParams::package_off)
922                 packages << "\\usepackage{stmaryrd}\n";
923
924         if (mustProvide("stackrel") &&
925             params_.use_package("stackrel") != BufferParams::package_off)
926                 packages << "\\usepackage{stackrel}\n";
927
928         if (mustProvide("undertilde") &&
929                 params_.use_package("undertilde") != BufferParams::package_off)
930                 packages << "\\usepackage{undertilde}\n";
931
932         // [x]color and pdfcolmk are handled in getColorOptions() above
933
934         // makeidx.sty
935         if (isRequired("makeidx") || isRequired("splitidx")) {
936                 if (!isProvided("makeidx") && !isRequired("splitidx"))
937                         packages << "\\usepackage{makeidx}\n";
938                 if (mustProvide("splitidx"))
939                         packages << "\\usepackage{splitidx}\n";
940                 packages << "\\makeindex\n";
941         }
942
943         // graphicx.sty
944         if (mustProvide("graphicx") && params_.graphics_driver != "none") {
945                 if (params_.graphics_driver == "default")
946                         packages << "\\usepackage{graphicx}\n";
947                 else
948                         packages << "\\usepackage["
949                                  << params_.graphics_driver
950                                  << "]{graphicx}\n";
951         }
952
953         // lyxskak.sty --- newer chess support based on skak.sty
954         if (mustProvide("chess"))
955                 packages << "\\usepackage[ps,mover]{lyxskak}\n";
956
957         // setspace.sty
958         if (mustProvide("setspace") && !isProvided("SetSpace"))
959                 packages << "\\usepackage{setspace}\n";
960
961         // we need to assure that mhchem is loaded before esint
962         // because esint must be loaded AFTER amslatex and mhchem loads amlatex
963         // (this info is from the author of mhchem from June 2013)
964         if (mustProvide("mhchem") &&
965             params_.use_package("mhchem") != BufferParams::package_off)
966                 packages << "\\PassOptionsToPackage{version=3}{mhchem}\n"
967                             "\\usepackage{mhchem}\n";
968
969         // esint must be after amsmath (and packages requiring amsmath, like mhchem)
970         // and wasysym, since it will redeclare inconsistent integral symbols
971         if (mustProvide("esint") &&
972             params_.use_package("esint") != BufferParams::package_off)
973                 packages << "\\usepackage{esint}\n";
974
975         // Known bibliography packages (simple \usepackage{package})
976         for (int i = 0; i < nb_bibliofeatures; ++i) {
977                 if (mustProvide(bibliofeatures[i]))
978                         packages << "\\usepackage{"
979                                  << bibliofeatures[i] << "}\n";
980         }
981
982         // Compatibility between achicago and natbib
983         if (mustProvide("achicago") && mustProvide("natbib"))
984                 packages << "\\let\\achicagobib\\thebibliography\n";
985
986         // natbib.sty
987         // Some classes load natbib themselves, but still allow (or even require)
988         // plain numeric citations (ReVTeX is such a case, see bug 5182).
989         // This special case is indicated by the "natbib-internal" key.
990         if (mustProvide("natbib") && !isProvided("natbib-internal")) {
991                 packages << "\\usepackage[";
992                 if (params_.citeEngineType() == ENGINE_TYPE_NUMERICAL)
993                         packages << "numbers";
994                 else
995                         packages << "authoryear";
996                 packages << "]{natbib}\n";
997         }
998
999         // Compatibility between achicago and natbib
1000         if (mustProvide("achicago") && mustProvide("natbib")) {
1001                 packages << "\\let\\thebibliography\\achicagobib\n";
1002                 packages << "\\let\\SCcite\\astroncite\n";
1003                 packages << "\\let\\UnexpandableProtect\\protect\n";
1004         }
1005
1006         // jurabib -- we need version 0.6 at least.
1007         if (mustProvide("jurabib"))
1008                 packages << "\\usepackage{jurabib}[2004/01/25]\n";
1009
1010         // opcit -- we pass custombst as we output \bibliographystyle ourselves
1011         if (mustProvide("opcit")) {
1012                 if (isRequired("hyperref"))
1013                         packages << "\\usepackage[custombst,hyperref]{opcit}\n";
1014                 else
1015                         packages << "\\usepackage[custombst]{opcit}\n";
1016         }
1017
1018         // xargs -- we need version 1.09 at least
1019         if (mustProvide("xargs"))
1020                 packages << "\\usepackage{xargs}[2008/03/08]\n";
1021
1022         if (mustProvide("xy"))
1023                 packages << "\\usepackage[all]{xy}\n";
1024
1025         if (mustProvide("feyn"))
1026                 packages << "\\usepackage{feyn}\n"; //Diagram
1027
1028         if (mustProvide("ulem"))
1029                 packages << "\\PassOptionsToPackage{normalem}{ulem}\n"
1030                             "\\usepackage{ulem}\n";
1031
1032         if (mustProvide("nomencl")) {
1033                 // Make it work with the new and old version of the package,
1034                 // but don't use the compatibility option since it is
1035                 // incompatible to other packages.
1036                 packages << "\\usepackage{nomencl}\n"
1037                             "% the following is useful when we have the old nomencl.sty package\n"
1038                             "\\providecommand{\\printnomenclature}{\\printglossary}\n"
1039                             "\\providecommand{\\makenomenclature}{\\makeglossary}\n"
1040                             "\\makenomenclature\n";
1041         }
1042
1043         // fixltx2e provides subscript
1044         if (mustProvide("subscript") && !isRequired("fixltx2e"))
1045                 packages << "\\usepackage{subscript}\n";
1046
1047         return packages.str();
1048 }
1049
1050
1051 string LaTeXFeatures::getPreambleSnippets() const
1052 {
1053         ostringstream snip;
1054         SnippetList::const_iterator pit  = preamble_snippets_.begin();
1055         SnippetList::const_iterator pend = preamble_snippets_.end();
1056         for (; pit != pend; ++pit)
1057                 snip << *pit << '\n';
1058         return snip.str();
1059 }
1060
1061
1062 std::string LaTeXFeatures::getCSSSnippets() const
1063 {
1064         ostringstream snip;
1065         SnippetList::const_iterator pit  = css_snippets_.begin();
1066         SnippetList::const_iterator pend = css_snippets_.end();
1067         for (; pit != pend; ++pit)
1068                 snip << *pit << '\n';
1069         return snip.str();
1070 }
1071
1072
1073 docstring const LaTeXFeatures::getMacros() const
1074 {
1075         odocstringstream macros;
1076
1077         if (!preamble_snippets_.empty()) {
1078                 macros << '\n';
1079                 macros << from_utf8(getPreambleSnippets());
1080         }
1081
1082         if (mustProvide("papersize")) {
1083                 if (runparams_.flavor == OutputParams::LATEX)
1084                         macros << papersizedvi_def << '\n';
1085                 else
1086                         macros << papersizepdf_def << '\n';
1087         }
1088
1089         if (mustProvide("LyX")) {
1090                 if (isRequired("hyperref"))
1091                         macros << lyx_hyperref_def << '\n';
1092                 else
1093                         macros << lyx_def << '\n';
1094         }
1095
1096         if (mustProvide("noun"))
1097                 macros << noun_def << '\n';
1098
1099         if (mustProvide("lyxarrow"))
1100                 macros << lyxarrow_def << '\n';
1101
1102         if (!usePolyglossia() && mustProvide("textgreek")) {
1103                 // Avoid a LaTeX error if times fonts are used and the grtimes
1104                 // package is installed but actual fonts are not (bug 6469).
1105                 if (params_.fonts_roman == "times")
1106                         macros << subst(textgreek_def,
1107                                         from_ascii("\\greektext #1"),
1108                                         from_ascii("%\n  \\IfFileExists"
1109                                                    "{grtm10.tfm}{}{\\fontfamily"
1110                                                    "{cmr}}\\greektext #1"))
1111                                << '\n';
1112                 else
1113                         macros << textgreek_def << '\n';
1114         }
1115
1116         if (!usePolyglossia() && mustProvide("textcyr"))
1117                 macros << textcyr_def << '\n';
1118
1119         if (mustProvide("lyxmathsym"))
1120                 macros << lyxmathsym_def << '\n';
1121
1122         if (mustProvide("cedilla"))
1123                 macros << cedilla_def << '\n';
1124
1125         if (mustProvide("subring"))
1126                 macros << subring_def << '\n';
1127
1128         if (mustProvide("subdot"))
1129                 macros << subdot_def << '\n';
1130
1131         if (mustProvide("subhat"))
1132                 macros << subhat_def << '\n';
1133
1134         if (mustProvide("subtilde"))
1135                 macros << subtilde_def << '\n';
1136
1137         if (mustProvide("dacute"))
1138                 macros << dacute_def << '\n';
1139
1140         if (mustProvide("tipasymb"))
1141                 macros << tipasymb_def << '\n';
1142
1143         if (mustProvide("dgrave"))
1144                 macros << dgrave_def << '\n';
1145
1146         if (mustProvide("rcap"))
1147                 macros << rcap_def << '\n';
1148
1149         if (mustProvide("ogonek"))
1150                 macros << ogonek_def << '\n';
1151
1152         // quotes.
1153         if (mustProvide("quotesinglbase"))
1154                 macros << quotesinglbase_def << '\n';
1155         if (mustProvide("quotedblbase"))
1156                 macros << quotedblbase_def << '\n';
1157         if (mustProvide("guilsinglleft"))
1158                 macros << guilsinglleft_def << '\n';
1159         if (mustProvide("guilsinglright"))
1160                 macros << guilsinglright_def << '\n';
1161         if (mustProvide("guillemotleft"))
1162                 macros << guillemotleft_def << '\n';
1163         if (mustProvide("guillemotright"))
1164                 macros << guillemotright_def << '\n';
1165
1166         // Math mode
1167         if (mustProvide("binom") && !isRequired("amsmath"))
1168                 macros << binom_def << '\n';
1169         if (mustProvide("mathcircumflex"))
1170                 macros << mathcircumflex_def << '\n';
1171
1172         // other
1173         if (mustProvide("ParagraphLeftIndent"))
1174                 macros << paragraphleftindent_def;
1175         if (mustProvide("NeedLyXFootnoteCode"))
1176                 macros << floatingfootnote_def;
1177
1178         // some problems with tex->html converters
1179         if (mustProvide("NeedTabularnewline"))
1180                 macros << tabularnewline_def;
1181
1182         // greyed-out environment (note inset)
1183         // the color is specified in the routine
1184         // getColorOptions() to avoid LaTeX-package clashes
1185         if (mustProvide("lyxgreyedout"))
1186                 macros << lyxgreyedout_def;
1187
1188         if (mustProvide("lyxdot"))
1189                 macros << lyxdot_def << '\n';
1190
1191         // floats
1192         getFloatDefinitions(macros);
1193
1194         if (mustProvide("refstyle"))
1195                 macros << lyxref_def << '\n';
1196
1197         // change tracking
1198         if (mustProvide("ct-dvipost"))
1199                 macros << changetracking_dvipost_def;
1200
1201         if (mustProvide("ct-xcolor-ulem")) {
1202                 streamsize const prec = macros.precision(2);
1203
1204                 RGBColor cadd = rgbFromHexName(lcolor.getX11Name(Color_addedtext));
1205                 macros << "\\providecolor{lyxadded}{rgb}{"
1206                        << cadd.r / 255.0 << ',' << cadd.g / 255.0 << ',' << cadd.b / 255.0 << "}\n";
1207
1208                 RGBColor cdel = rgbFromHexName(lcolor.getX11Name(Color_deletedtext));
1209                 macros << "\\providecolor{lyxdeleted}{rgb}{"
1210                        << cdel.r / 255.0 << ',' << cdel.g / 255.0 << ',' << cdel.b / 255.0 << "}\n";
1211
1212                 macros.precision(prec);
1213
1214                 if (isRequired("hyperref"))
1215                         macros << changetracking_xcolor_ulem_hyperref_def;
1216                 else
1217                         macros << changetracking_xcolor_ulem_def;
1218         }
1219
1220         if (mustProvide("ct-none"))
1221                 macros << changetracking_none_def;
1222
1223         if (mustProvide("rtloutputdblcol"))
1224                 macros << rtloutputdblcol_def;
1225
1226         return macros.str();
1227 }
1228
1229
1230 string const LaTeXFeatures::getBabelPresettings() const
1231 {
1232         ostringstream tmp;
1233
1234         LanguageList::const_iterator it  = UsedLanguages_.begin();
1235         LanguageList::const_iterator end = UsedLanguages_.end();
1236         for (; it != end; ++it)
1237                 if (!(*it)->babel_presettings().empty())
1238                         tmp << (*it)->babel_presettings() << '\n';
1239         if (!params_.language->babel_presettings().empty())
1240                 tmp << params_.language->babel_presettings() << '\n';
1241
1242         if (!contains(tmp.str(), '@'))
1243                 return tmp.str();
1244
1245         return "\\makeatletter\n" + tmp.str() + "\\makeatother\n";
1246 }
1247
1248
1249 string const LaTeXFeatures::getBabelPostsettings() const
1250 {
1251         ostringstream tmp;
1252
1253         LanguageList::const_iterator it  = UsedLanguages_.begin();
1254         LanguageList::const_iterator end = UsedLanguages_.end();
1255         for (; it != end; ++it)
1256                 if (!(*it)->babel_postsettings().empty())
1257                         tmp << (*it)->babel_postsettings() << '\n';
1258         if (!params_.language->babel_postsettings().empty())
1259                 tmp << params_.language->babel_postsettings() << '\n';
1260
1261         if (!contains(tmp.str(), '@'))
1262                 return tmp.str();
1263
1264         return "\\makeatletter\n" + tmp.str() + "\\makeatother\n";
1265 }
1266
1267
1268 bool LaTeXFeatures::needBabelLangOptions() const
1269 {
1270         if (!lyxrc.language_global_options || params_.language->asBabelOptions())
1271                 return true;
1272
1273         LanguageList::const_iterator it  = UsedLanguages_.begin();
1274         LanguageList::const_iterator end = UsedLanguages_.end();
1275         for (; it != end; ++it)
1276                 if ((*it)->asBabelOptions())
1277                         return true;
1278
1279         return false;
1280 }
1281
1282
1283 string const LaTeXFeatures::loadAMSPackages() const
1284 {
1285         ostringstream tmp;
1286         if (mustProvide("amsthm"))
1287                 tmp << "\\usepackage{amsthm}\n";
1288
1289         if (mustProvide("amsmath")
1290             && params_.use_package("amsmath") != BufferParams::package_off) {
1291                 tmp << "\\usepackage{amsmath}\n";
1292         } else {
1293                 // amsbsy and amstext are already provided by amsmath
1294                 if (mustProvide("amsbsy"))
1295                         tmp << "\\usepackage{amsbsy}\n";
1296                 if (mustProvide("amstext"))
1297                         tmp << "\\usepackage{amstext}\n";
1298         }
1299
1300         if (mustProvide("amssymb")
1301             && params_.use_package("amssymb") != BufferParams::package_off)
1302                 tmp << "\\usepackage{amssymb}\n";
1303
1304         return tmp.str();
1305 }
1306
1307
1308 docstring const LaTeXFeatures::getTClassPreamble() const
1309 {
1310         // the text class specific preamble
1311         DocumentClass const & tclass = params_.documentClass();
1312         odocstringstream tcpreamble;
1313
1314         tcpreamble << tclass.preamble();
1315
1316         list<docstring>::const_iterator cit = usedLayouts_.begin();
1317         list<docstring>::const_iterator end = usedLayouts_.end();
1318         for (; cit != end; ++cit)
1319                 tcpreamble << tclass[*cit].preamble();
1320
1321         cit = usedInsetLayouts_.begin();
1322         end = usedInsetLayouts_.end();
1323         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1324         for (; cit != end; ++cit) {
1325                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1326                 if (it == ils.end())
1327                         continue;
1328                 tcpreamble << it->second.preamble();
1329         }
1330
1331         return tcpreamble.str();
1332 }
1333
1334
1335 docstring const LaTeXFeatures::getTClassHTMLPreamble() const
1336 {
1337         DocumentClass const & tclass = params_.documentClass();
1338         odocstringstream tcpreamble;
1339
1340         tcpreamble << tclass.htmlpreamble();
1341
1342         list<docstring>::const_iterator cit = usedLayouts_.begin();
1343         list<docstring>::const_iterator end = usedLayouts_.end();
1344         for (; cit != end; ++cit)
1345                 tcpreamble << tclass[*cit].htmlpreamble();
1346
1347         cit = usedInsetLayouts_.begin();
1348         end = usedInsetLayouts_.end();
1349         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1350         for (; cit != end; ++cit) {
1351                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1352                 if (it == ils.end())
1353                         continue;
1354                 tcpreamble << it->second.htmlpreamble();
1355         }
1356
1357         return tcpreamble.str();
1358 }
1359
1360
1361 docstring const LaTeXFeatures::getTClassHTMLStyles() const
1362 {
1363         DocumentClass const & tclass = params_.documentClass();
1364         odocstringstream tcpreamble;
1365
1366         if (mustProvide("noun"))
1367                 tcpreamble << lyxnoun_style;
1368         // this isn't exact, but it won't hurt that much if it
1369         // wasn't for this.
1370         if (mustProvide("ulem"))
1371                 tcpreamble << lyxstrikeout_style;
1372
1373         tcpreamble << tclass.htmlstyles();
1374
1375         list<docstring>::const_iterator cit = usedLayouts_.begin();
1376         list<docstring>::const_iterator end = usedLayouts_.end();
1377         for (; cit != end; ++cit)
1378                 tcpreamble << tclass[*cit].htmlstyle();
1379
1380         cit = usedInsetLayouts_.begin();
1381         end = usedInsetLayouts_.end();
1382         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1383         for (; cit != end; ++cit) {
1384                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1385                 if (it == ils.end())
1386                         continue;
1387                 tcpreamble << it->second.htmlstyle();
1388         }
1389
1390         return tcpreamble.str();
1391 }
1392
1393
1394 namespace {
1395
1396 docstring const getFloatI18nPreamble(docstring const & type,
1397                         docstring const & name, Language const * lang,
1398                         Encoding const & enc, bool const polyglossia)
1399 {
1400         // Check whether name can be encoded in the buffer encoding
1401         bool encodable = true;
1402         for (size_t i = 0; i < name.size(); ++i) {
1403                 if (!enc.encodable(name[i])) {
1404                         encodable = false;
1405                         break;
1406                 }
1407         }
1408
1409         docstring const language = polyglossia ? from_ascii(lang->polyglossia())
1410                                                : from_ascii(lang->babel());
1411         docstring const langenc = from_ascii(lang->encoding()->iconvName());
1412         docstring const texenc = from_ascii(lang->encoding()->latexName());
1413         docstring const bufenc = from_ascii(enc.iconvName());
1414         docstring const s1 = docstring(1, 0xF0000);
1415         docstring const s2 = docstring(1, 0xF0001);
1416         docstring const translated = encodable ? name
1417                 : from_ascii("\\inputencoding{") + texenc + from_ascii("}")
1418                         + s1 + langenc + s2 + name + s1 + bufenc + s2;
1419
1420         odocstringstream os;
1421         os << "\\addto\\captions" << language
1422            << "{\\renewcommand{\\" << type << "name}{" << translated << "}}\n";
1423         return os.str();
1424 }
1425
1426
1427 docstring const i18npreamble(docstring const & templ, Language const * lang,
1428                 Encoding const & enc, bool const polyglossia)
1429 {
1430         if (templ.empty())
1431                 return templ;
1432
1433         string preamble = polyglossia ?
1434                 subst(to_utf8(templ), "$$lang", lang->polyglossia()) :
1435                 subst(to_utf8(templ), "$$lang", lang->babel());
1436
1437         string const langenc = lang->encoding()->iconvName();
1438         string const texenc = lang->encoding()->latexName();
1439         string const bufenc = enc.iconvName();
1440         // First and second character of plane 15 (Private Use Area)
1441         string const s1 = "\xf3\xb0\x80\x80"; // U+F0000
1442         string const s2 = "\xf3\xb0\x80\x81"; // U+F0001
1443         // FIXME UNICODE
1444         // lyx::regex is not unicode-safe.
1445         // Should use QRegExp or (boost::u32regex, but that requires ICU)
1446         static regex const reg("_\\(([^\\)]+)\\)");
1447         smatch sub;
1448         while (regex_search(preamble, sub, reg)) {
1449                 string const key = sub.str(1);
1450                 docstring const name = lang->translateLayout(key);
1451                 // Check whether name can be encoded in the buffer encoding
1452                 bool encodable = true;
1453                 for (size_t i = 0; i < name.size(); ++i) {
1454                         if (!enc.encodable(name[i])) {
1455                                 encodable = false;
1456                                 break;
1457                         }
1458                 }
1459                 string const translated = encodable ? to_utf8(name)
1460                         : "\\inputencoding{" + texenc + "}"
1461                         + s1 + langenc + s2 + to_utf8(name)
1462                         + s1 + bufenc + s2;
1463                 preamble = subst(preamble, sub.str(), translated);
1464         }
1465         return from_utf8(preamble);
1466 }
1467
1468 }
1469
1470
1471 docstring const LaTeXFeatures::getTClassI18nPreamble(bool use_babel, bool use_polyglossia) const
1472 {
1473         DocumentClass const & tclass = params_.documentClass();
1474         // collect preamble snippets in a set to prevent multiple identical
1475         // commands (would happen if e.g. both theorem and theorem* are used)
1476         set<docstring> snippets;
1477         typedef LanguageList::const_iterator lang_it;
1478         lang_it const lbeg = UsedLanguages_.begin();
1479         lang_it const lend =  UsedLanguages_.end();
1480         list<docstring>::const_iterator cit = usedLayouts_.begin();
1481         list<docstring>::const_iterator end = usedLayouts_.end();
1482         for (; cit != end; ++cit) {
1483                 // language dependent commands (once per document)
1484                 snippets.insert(i18npreamble(tclass[*cit].langpreamble(),
1485                                                 buffer().language(),
1486                                                 buffer().params().encoding(),
1487                                                 use_polyglossia));
1488                 // commands for language changing (for multilanguage documents)
1489                 if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1490                         snippets.insert(i18npreamble(
1491                                                 tclass[*cit].babelpreamble(),
1492                                                 buffer().language(),
1493                                                 buffer().params().encoding(),
1494                                                 use_polyglossia));
1495                         for (lang_it lit = lbeg; lit != lend; ++lit)
1496                                 snippets.insert(i18npreamble(
1497                                                 tclass[*cit].babelpreamble(),
1498                                                 *lit,
1499                                                 buffer().params().encoding(),
1500                                                 use_polyglossia));
1501                 }
1502         }
1503         if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1504                 FloatList const & floats = params_.documentClass().floats();
1505                 UsedFloats::const_iterator fit = usedFloats_.begin();
1506                 UsedFloats::const_iterator fend = usedFloats_.end();
1507                 for (; fit != fend; ++fit) {
1508                         Floating const & fl = floats.getType(fit->first);
1509                         // we assume builtin floats are translated
1510                         if (fl.isPredefined())
1511                                 continue;
1512                         docstring const type = from_ascii(fl.floattype());
1513                         docstring const flname = from_utf8(fl.name());
1514                         docstring name = buffer().language()->translateLayout(fl.name());
1515                         // only request translation if we have a real translation
1516                         // (that differs from the source)
1517                         if (flname != name)
1518                                 snippets.insert(getFloatI18nPreamble(
1519                                                 type, name, buffer().language(),
1520                                                 buffer().params().encoding(),
1521                                                 use_polyglossia));
1522                         for (lang_it lit = lbeg; lit != lend; ++lit) {
1523                                 string const code = (*lit)->code();
1524                                 name = (*lit)->translateLayout(fl.name());
1525                                 // we assume we have a suitable translation if
1526                                 // either the language is English (we need to
1527                                 // translate into English if English is a secondary
1528                                 // language) or if translateIfPossible returns
1529                                 // something different to the English source.
1530                                 bool const have_translation =
1531                                         (flname != name || contains(code, "en"));
1532                                 if (have_translation)
1533                                         snippets.insert(getFloatI18nPreamble(
1534                                                 type, name, *lit,
1535                                                 buffer().params().encoding(),
1536                                                 use_polyglossia));
1537                         }
1538                 }
1539         }
1540
1541         cit = usedInsetLayouts_.begin();
1542         end = usedInsetLayouts_.end();
1543         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1544         for (; cit != end; ++cit) {
1545                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1546                 if (it == ils.end())
1547                         continue;
1548                 // language dependent commands (once per document)
1549                 snippets.insert(i18npreamble(it->second.langpreamble(),
1550                                                 buffer().language(),
1551                                                 buffer().params().encoding(),
1552                                                 use_polyglossia));
1553                 // commands for language changing (for multilanguage documents)
1554                 if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1555                         snippets.insert(i18npreamble(
1556                                                 it->second.babelpreamble(),
1557                                                 buffer().language(),
1558                                                 buffer().params().encoding(),
1559                                                 use_polyglossia));
1560                         for (lang_it lit = lbeg; lit != lend; ++lit)
1561                                 snippets.insert(i18npreamble(
1562                                                 it->second.babelpreamble(),
1563                                                 *lit,
1564                                                 buffer().params().encoding(),
1565                                                 use_polyglossia));
1566                 }
1567         }
1568
1569         odocstringstream tcpreamble;
1570         set<docstring>::const_iterator const send = snippets.end();
1571         set<docstring>::const_iterator it = snippets.begin();
1572         for (; it != send; ++it)
1573                 tcpreamble << *it;
1574         return tcpreamble.str();
1575 }
1576
1577
1578 docstring const LaTeXFeatures::getLyXSGMLEntities() const
1579 {
1580         // Definition of entities used in the document that are LyX related.
1581         odocstringstream entities;
1582
1583         if (mustProvide("lyxarrow")) {
1584                 entities << "<!ENTITY lyxarrow \"-&gt;\">" << '\n';
1585         }
1586
1587         return entities.str();
1588 }
1589
1590
1591 docstring const LaTeXFeatures::getIncludedFiles(string const & fname) const
1592 {
1593         odocstringstream sgmlpreamble;
1594         // FIXME UNICODE
1595         docstring const basename(from_utf8(onlyPath(fname)));
1596
1597         FileMap::const_iterator end = IncludedFiles_.end();
1598         for (FileMap::const_iterator fi = IncludedFiles_.begin();
1599              fi != end; ++fi)
1600                 // FIXME UNICODE
1601                 sgmlpreamble << "\n<!ENTITY " << fi->first
1602                              << (isSGMLFileName(fi->second) ? " SYSTEM \"" : " \"")
1603                              << makeRelPath(from_utf8(fi->second), basename) << "\">";
1604
1605         return sgmlpreamble.str();
1606 }
1607
1608
1609 void LaTeXFeatures::showStruct() const
1610 {
1611         lyxerr << "LyX needs the following commands when LaTeXing:"
1612                << "\n***** Packages:" << getPackages()
1613                << "\n***** Macros:" << to_utf8(getMacros())
1614                << "\n***** Textclass stuff:" << to_utf8(getTClassPreamble())
1615                << "\n***** done." << endl;
1616 }
1617
1618
1619 Buffer const & LaTeXFeatures::buffer() const
1620 {
1621         return *buffer_;
1622 }
1623
1624
1625 void LaTeXFeatures::setBuffer(Buffer const & buffer)
1626 {
1627         buffer_ = &buffer;
1628 }
1629
1630
1631 BufferParams const & LaTeXFeatures::bufferParams() const
1632 {
1633         return params_;
1634 }
1635
1636
1637 void LaTeXFeatures::getFloatDefinitions(odocstream & os) const
1638 {
1639         FloatList const & floats = params_.documentClass().floats();
1640
1641         // Here we will output the code to create the needed float styles.
1642         // We will try to do this as minimal as possible.
1643         // \floatstyle{ruled}
1644         // \newfloat{algorithm}{htbp}{loa}
1645         // \providecommand{\algorithmname}{Algorithm}
1646         // \floatname{algorithm}{\protect\algorithmname}
1647         UsedFloats::const_iterator cit = usedFloats_.begin();
1648         UsedFloats::const_iterator end = usedFloats_.end();
1649         for (; cit != end; ++cit) {
1650                 Floating const & fl = floats.getType(cit->first);
1651
1652                 // For builtin floats we do nothing.
1653                 if (fl.isPredefined())
1654                         continue;
1655
1656                 // We have to special case "table" and "figure"
1657                 if (fl.floattype() == "tabular" || fl.floattype() == "figure") {
1658                         // Output code to modify "table" or "figure"
1659                         // but only if builtin == false
1660                         // and that have to be true at this point in the
1661                         // function.
1662                         docstring const type = from_ascii(fl.floattype());
1663                         docstring const placement = from_ascii(fl.placement());
1664                         docstring const style = from_ascii(fl.style());
1665                         if (!style.empty()) {
1666                                 os << "\\floatstyle{" << style << "}\n"
1667                                    << "\\restylefloat{" << type << "}\n";
1668                         }
1669                         if (!placement.empty()) {
1670                                 os << "\\floatplacement{" << type << "}{"
1671                                    << placement << "}\n";
1672                         }
1673                 } else {
1674                         // The other non builtin floats.
1675
1676                         docstring const type = from_ascii(fl.floattype());
1677                         docstring const placement = from_ascii(fl.placement());
1678                         docstring const ext = from_ascii(fl.ext());
1679                         docstring const within = from_ascii(fl.within());
1680                         docstring const style = from_ascii(fl.style());
1681                         docstring const name =
1682                                 buffer().language()->translateLayout(fl.name());
1683                         os << "\\floatstyle{" << style << "}\n"
1684                            << "\\newfloat{" << type << "}{" << placement
1685                            << "}{" << ext << '}';
1686                         if (!within.empty())
1687                                 os << '[' << within << ']';
1688                         os << '\n'
1689                            << "\\providecommand{\\" << type << "name}{"
1690                            << name << "}\n"
1691                            << "\\floatname{" << type << "}{\\protect\\"
1692                            << type << "name}\n";
1693
1694                         // What missing here is to code to minimalize the code
1695                         // output so that the same floatstyle will not be
1696                         // used several times, when the same style is still in
1697                         // effect. (Lgb)
1698                 }
1699                 if (cit->second)
1700                         // The subfig package is loaded later
1701                         os << "\n\\AtBeginDocument{\\newsubfloat{" << from_ascii(fl.floattype()) << "}}\n";
1702         }
1703 }
1704
1705
1706 void LaTeXFeatures::resolveAlternatives()
1707 {
1708         for (Features::iterator it = features_.begin(); it != features_.end();) {
1709                 if (contains(*it, '|')) {
1710                         vector<string> const alternatives = getVectorFromString(*it, "|");
1711                         vector<string>::const_iterator const end = alternatives.end();
1712                         vector<string>::const_iterator ita = alternatives.begin();
1713                         for (; ita != end; ++ita) {
1714                                 if (isRequired(*ita))
1715                                         break;
1716                         }
1717                         if (ita == end)
1718                                 require(alternatives.front());
1719                         features_.erase(it);
1720                         it = features_.begin();
1721                 } else
1722                         ++it;
1723         }
1724 }
1725
1726
1727 } // namespace lyx