]> git.lyx.org Git - lyx.git/blob - src/LaTeXFeatures.cpp
Make sure a pointer is valid before using it
[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_LGR_def = from_ascii(
206         "\\DeclareFontEncoding{LGR}{}{}\n");
207 static docstring const textgreek_def = from_ascii(
208         "\\DeclareRobustCommand{\\greektext}{%\n"
209         "  \\fontencoding{LGR}\\selectfont\\def\\encodingdefault{LGR}}\n"
210         "\\DeclareRobustCommand{\\textgreek}[1]{\\leavevmode{\\greektext #1}}\n"
211         "\\ProvideTextCommand{\\~}{LGR}[1]{\\char126#1}\n");
212
213 static docstring const textcyr_T2A_def = from_ascii(
214         "\\InputIfFileExists{t2aenc.def}{}{%\n"
215         "  \\errmessage{File `t2aenc.def' not found: Cyrillic script not supported}}\n");
216 static docstring const textcyr_def = from_ascii(
217         "\\DeclareRobustCommand{\\cyrtext}{%\n"
218         "  \\fontencoding{T2A}\\selectfont\\def\\encodingdefault{T2A}}\n"
219         "\\DeclareRobustCommand{\\textcyr}[1]{\\leavevmode{\\cyrtext #1}}\n");
220
221 static docstring const lyxmathsym_def = from_ascii(
222         "\\newcommand{\\lyxmathsym}[1]{\\ifmmode\\begingroup\\def\\b@ld{bold}\n"
223         "  \\text{\\ifx\\math@version\\b@ld\\bfseries\\fi#1}\\endgroup\\else#1\\fi}\n");
224
225 static docstring const papersizedvi_def = from_ascii(
226         "\\special{papersize=\\the\\paperwidth,\\the\\paperheight}\n");
227
228 static docstring const papersizepdf_def = from_ascii(
229         "\\pdfpageheight\\paperheight\n"
230         "\\pdfpagewidth\\paperwidth\n");
231
232 static docstring const papersizepdflua_def = from_ascii(
233         "% Backwards compatibility for LuaTeX < 0.90\n"
234         "\\@ifundefined{pageheight}{\\let\\pageheight\\pdfpageheight}{}\n"
235         "\\@ifundefined{pagewidth}{\\let\\pagewidth\\pdfpagewidth}{}\n"
236         "\\pageheight\\paperheight\n"
237         "\\pagewidth\\paperwidth\n");
238
239 static docstring const cedilla_def = from_ascii(
240         "\\newcommand{\\docedilla}[2]{\\underaccent{#1\\mathchar'30}{#2}}\n"
241         "\\newcommand{\\cedilla}[1]{\\mathpalette\\docedilla{#1}}\n");
242
243 static docstring const subring_def = from_ascii(
244         "\\newcommand{\\dosubring}[2]{\\underaccent{#1\\mathchar'27}{#2}}\n"
245         "\\newcommand{\\subring}[1]{\\mathpalette\\dosubring{#1}}\n");
246
247 static docstring const subdot_def = from_ascii(
248         "\\newcommand{\\dosubdot}[2]{\\underaccent{#1.}{#2}}\n"
249         "\\newcommand{\\subdot}[1]{\\mathpalette\\dosubdot{#1}}\n");
250
251 static docstring const subhat_def = from_ascii(
252         "\\newcommand{\\dosubhat}[2]{\\underaccent{#1\\mathchar'136}{#2}}\n"
253         "\\newcommand{\\subhat}[1]{\\mathpalette\\dosubhat{#1}}\n");
254
255 static docstring const subtilde_def = from_ascii(
256         "\\newcommand{\\dosubtilde}[2]{\\underaccent{#1\\mathchar'176}{#2}}\n"
257         "\\newcommand{\\subtilde}[1]{\\mathpalette\\dosubtilde{#1}}\n");
258
259 static docstring const dacute_def = from_ascii(
260         "\\DeclareMathAccent{\\dacute}{\\mathalpha}{operators}{'175}\n");
261
262 static docstring const tipasymb_def = from_ascii(
263         "\\DeclareFontEncoding{T3}{}{}\n"
264         "\\DeclareSymbolFont{tipasymb}{T3}{cmr}{m}{n}\n");
265
266 static docstring const dgrave_def = from_ascii(
267         "\\DeclareMathAccent{\\dgrave}{\\mathord}{tipasymb}{'15}\n");
268
269 static docstring const rcap_def = from_ascii(
270         "\\DeclareMathAccent{\\rcap}{\\mathord}{tipasymb}{'20}\n");
271
272 static docstring const ogonek_def = from_ascii(
273         "\\newcommand{\\doogonek}[2]{\\setbox0=\\hbox{$#1#2$}\\underaccent{#1\\mkern-6mu\n"
274         "  \\ifx#2O\\hskip0.5\\wd0\\else\\ifx#2U\\hskip0.5\\wd0\\else\\hskip\\wd0\\fi\\fi\n"
275         "  \\ifx#2o\\mkern-2mu\\else\\ifx#2e\\mkern-1mu\\fi\\fi\n"
276         "  \\mathchar\"0\\hexnumber@\\symtipasymb0C}{#2}}\n"
277         "\\newcommand{\\ogonek}[1]{\\mathpalette\\doogonek{#1}}\n");
278
279 static docstring const lyxaccent_def = from_ascii(
280         "%% custom text accent \\LyxTextAccent[<rise value (length)>]{<accent>}{<base>}\n"
281         "\\newcommand*{\\LyxTextAccent}[3][0ex]{%\n"
282         "  \\hmode@bgroup\\ooalign{\\null#3\\crcr\\hidewidth\n"
283         "  \\raise#1\\hbox{#2}\\hidewidth}\\egroup}\n"
284         "%% select a font size smaller than the current font size:\n"
285         "\\newcommand{\\LyxAccentSize}[1][\\sf@size]{%\n"
286         "  \\check@mathfonts\\fontsize#1\\z@\\math@fontsfalse\\selectfont\n"
287         "}\n");
288
289 static docstring const textcommabelow_def = from_ascii(
290         "\\ProvideTextCommandDefault{\\textcommabelow}[1]{%%\n"
291         "  \\LyxTextAccent[-.31ex]{\\LyxAccentSize,}{#1}}\n");
292
293 static docstring const textcommaabove_def = from_ascii(
294         "\\ProvideTextCommandDefault{\\textcommaabove}[1]{%%\n"
295         "  \\LyxTextAccent[.5ex]{\\LyxAccentSize`}{#1}}\n");
296
297 static docstring const textcommaaboveright_def = from_ascii(
298         "\\ProvideTextCommandDefault{\\textcommaaboveright}[1]{%%\n"
299         "  \\LyxTextAccent[.5ex]{\\LyxAccentSize\\ '}{#1}}\n");
300
301 // Baltic languages use a comma-accent instead of a cedilla
302 static docstring const textbaltic_def = from_ascii(
303         "%% use comma accent instead of cedilla for these characters:\n"
304         "\\DeclareTextCompositeCommand{\\c}{T1}{g}{\\textcommaabove{g}}\n"
305         "\\DeclareTextCompositeCommand{\\c}{T1}{G}{\\textcommabelow{G}}\n"
306         "\\DeclareTextCompositeCommand{\\c}{T1}{k}{\\textcommabelow{k}}\n"
307         "\\DeclareTextCompositeCommand{\\c}{T1}{K}{\\textcommabelow{K}}\n"
308         "\\DeclareTextCompositeCommand{\\c}{T1}{l}{\\textcommabelow{l}}\n"
309         "\\DeclareTextCompositeCommand{\\c}{T1}{L}{\\textcommabelow{L}}\n"
310         "\\DeclareTextCompositeCommand{\\c}{T1}{n}{\\textcommabelow{n}}\n"
311         "\\DeclareTextCompositeCommand{\\c}{T1}{N}{\\textcommabelow{N}}\n"
312         "\\DeclareTextCompositeCommand{\\c}{T1}{r}{\\textcommabelow{r}}\n"
313         "\\DeclareTextCompositeCommand{\\c}{T1}{R}{\\textcommabelow{R}}\n");
314
315 static docstring const lyxref_def = from_ascii(
316                 "\\RS@ifundefined{subsecref}\n"
317                 "  {\\newref{subsec}{name = \\RSsectxt}}\n"
318                 "  {}\n"
319                 "\\RS@ifundefined{thmref}\n"
320                 "  {\\def\\RSthmtxt{theorem~}\\newref{thm}{name = \\RSthmtxt}}\n"
321                 "  {}\n"
322                 "\\RS@ifundefined{lemref}\n"
323                 "  {\\def\\RSlemtxt{lemma~}\\newref{lem}{name = \\RSlemtxt}}\n"
324                 "  {}\n");
325
326 // Make sure the columns are also outputed as rtl
327 static docstring const rtloutputdblcol_def = from_ascii(
328         "\\def\\@outputdblcol{%\n"
329         "  \\if@firstcolumn\n"
330         "    \\global \\@firstcolumnfalse\n"
331         "    \\global \\setbox\\@leftcolumn \\box\\@outputbox\n"
332         "  \\else\n"
333         "    \\global \\@firstcolumntrue\n"
334         "    \\setbox\\@outputbox \\vbox {%\n"
335         "      \\hb@xt@\\textwidth {%\n"
336         "      \\kern\\textwidth \\kern-\\columnwidth %**\n"
337         "      \\hb@xt@\\columnwidth {%\n"
338         "         \\box\\@leftcolumn \\hss}%\n"
339         "      \\kern-\\textwidth %**\n"
340         "      \\hfil\n"
341         "      {\\normalcolor\\vrule \\@width\\columnseprule}%\n"
342         "      \\hfil\n"
343         "      \\kern-\\textwidth  %**\n"
344         "      \\hb@xt@\\columnwidth {%\n"
345         "         \\box\\@outputbox \\hss}%\n"
346         "      \\kern-\\columnwidth \\kern\\textwidth %**\n"
347         "    }%\n"
348         "  }%\n"
349         "  \\@combinedblfloats\n"
350         "  \\@outputpage\n"
351         "  \\begingroup\n"
352         "  \\@dblfloatplacement\n"
353         "  \\@startdblcolumn\n"
354         "  \\@whilesw\\if@fcolmade \\fi\n"
355         "  {\\@outputpage\n"
356         "    \\@startdblcolumn}%\n"
357         "  \\endgroup\n"
358         "  \\fi\n"
359         "}\n"
360         "\\@mparswitchtrue\n");
361
362
363 /////////////////////////////////////////////////////////////////////
364 //
365 // LyXHTML strings
366 //
367 /////////////////////////////////////////////////////////////////////
368
369 static docstring const lyxnoun_style = from_ascii(
370         "dfn.lyxnoun {\n"
371         "  font-variant: small-caps;\n"
372         "}\n");
373
374
375 // this is how it normally renders, but it might not always do so.
376 static docstring const lyxstrikeout_style = from_ascii(
377         "del.strikeout {\n"
378         "  text-decoration: line-through;\n"
379         "}\n");
380
381
382 /////////////////////////////////////////////////////////////////////
383 //
384 // LaTeXFeatures
385 //
386 /////////////////////////////////////////////////////////////////////
387
388
389 LaTeXFeatures::LaTeXFeatures(Buffer const & b, BufferParams const & p,
390                              OutputParams const & r)
391         : buffer_(&b), params_(p), runparams_(r), in_float_(false)
392 {}
393
394
395 LaTeXFeatures::LangPackage LaTeXFeatures::langPackage() const
396 {
397         string const local_lp = bufferParams().lang_package;
398
399         // Locally, custom is just stored as a string
400         // in bufferParams().lang_package.
401         if (local_lp != "auto"
402             && local_lp != "babel"
403             && local_lp != "default"
404             && local_lp != "none")
405                  return LANG_PACK_CUSTOM;
406
407         if (local_lp == "none")
408                 return LANG_PACK_NONE;
409
410         /* If "auto" is selected, we load polyglossia with non-TeX fonts,
411          * else we select babel.
412          * If babel is selected (either directly or via the "auto"
413          * mechanism), we really do only require it if we have
414          * a language that needs it.
415          */
416         bool const polyglossia_required =
417                 params_.useNonTeXFonts
418                 && isAvailable("polyglossia")
419                 && !isProvided("babel")
420                 && this->hasOnlyPolyglossiaLanguages();
421         bool const babel_required =
422                 !bufferParams().language->babel().empty()
423                 || !this->getBabelLanguages().empty();
424
425         if (local_lp == "auto") {
426                 // polyglossia requirement has priority over babel
427                 if (polyglossia_required)
428                         return LANG_PACK_POLYGLOSSIA;
429                 else if (babel_required)
430                         return LANG_PACK_BABEL;
431         }
432
433         if (local_lp == "babel") {
434                 if (babel_required)
435                         return LANG_PACK_BABEL;
436         }
437
438         if (local_lp == "default") {
439                 switch (lyxrc.language_package_selection) {
440                 case LyXRC::LP_AUTO:
441                         // polyglossia requirement has priority over babel
442                         if (polyglossia_required)
443                                 return LANG_PACK_POLYGLOSSIA;
444                         else if (babel_required)
445                                 return LANG_PACK_BABEL;
446                         break;
447                 case LyXRC::LP_BABEL:
448                         if (babel_required)
449                                 return LANG_PACK_BABEL;
450                         break;
451                 case LyXRC::LP_CUSTOM:
452                         return LANG_PACK_CUSTOM;
453                 case LyXRC::LP_NONE:
454                         return LANG_PACK_NONE;
455                 }
456         }
457
458         return LANG_PACK_NONE;
459 }
460
461
462 void LaTeXFeatures::require(string const & name)
463 {
464         features_.insert(name);
465 }
466
467
468 void LaTeXFeatures::require(set<string> const & names)
469 {
470         features_.insert(names.begin(), names.end());
471 }
472
473
474 void LaTeXFeatures::useLayout(docstring const & layoutname)
475 {
476         useLayout(layoutname, 0);
477 }
478
479
480 void LaTeXFeatures::useLayout(docstring const & layoutname, int level)
481 {
482         // Some code to avoid loops in dependency definition
483         const int maxlevel = 30;
484         if (level > maxlevel) {
485                 lyxerr << "LaTeXFeatures::useLayout: maximum level of "
486                        << "recursion attained by layout "
487                        << to_utf8(layoutname) << endl;
488                 return;
489         }
490
491         DocumentClass const & tclass = params_.documentClass();
492         if (tclass.hasLayout(layoutname)) {
493                 // Is this layout already in usedLayouts?
494                 if (find(usedLayouts_.begin(), usedLayouts_.end(), layoutname)
495                     != usedLayouts_.end())
496                         return;
497
498                 Layout const & layout = tclass[layoutname];
499                 require(layout.requires());
500
501                 if (!layout.depends_on().empty()) {
502                         useLayout(layout.depends_on(), level + 1);
503                 }
504                 usedLayouts_.push_back(layoutname);
505         } else {
506                 lyxerr << "LaTeXFeatures::useLayout: layout `"
507                        << to_utf8(layoutname) << "' does not exist in this class"
508                        << endl;
509         }
510 }
511
512
513 void LaTeXFeatures::useInsetLayout(InsetLayout const & lay)
514 {
515         docstring const & lname = lay.name();
516         DocumentClass const & tclass = params_.documentClass();
517
518         // this is a default inset layout, nothing useful here
519         if (!tclass.hasInsetLayout(lname))
520                 return;
521         // Is this layout already in usedInsetLayouts?
522         if (find(usedInsetLayouts_.begin(), usedInsetLayouts_.end(), lname)
523                         != usedInsetLayouts_.end())
524                 return;
525
526         require(lay.requires());
527         usedInsetLayouts_.push_back(lname);
528 }
529
530
531 bool LaTeXFeatures::isRequired(string const & name) const
532 {
533         return features_.find(name) != features_.end();
534 }
535
536
537 bool LaTeXFeatures::isProvided(string const & name) const
538 {
539         if (params_.useNonTeXFonts)
540                 return params_.documentClass().provides(name);
541
542         bool const ot1 = (params_.font_encoding() == "default"
543                 || params_.font_encoding() == "OT1");
544         bool const complete = (params_.fontsSans() == "default"
545                 && params_.fontsTypewriter() == "default");
546         bool const nomath = (params_.fontsMath() == "default");
547         return params_.documentClass().provides(name)
548                 || theLaTeXFonts().getLaTeXFont(
549                         from_ascii(params_.fontsRoman())).provides(name, ot1,
550                                                                   complete,
551                                                                   nomath)
552                 || theLaTeXFonts().getLaTeXFont(
553                         from_ascii(params_.fontsSans())).provides(name, ot1,
554                                                                  complete,
555                                                                  nomath)
556                 || theLaTeXFonts().getLaTeXFont(
557                         from_ascii(params_.fontsTypewriter())).provides(name, ot1,
558                                                                        complete,
559                                                                        nomath)
560                 || theLaTeXFonts().getLaTeXFont(
561                         from_ascii(params_.fontsMath())).provides(name, ot1,
562                                                                        complete,
563                                                                        nomath);
564         // TODO: "textbaltic" provided, if the font-encoding is "L7x"
565         //       "textgreek" provided, if a language with font-encoding LGR is used in the document
566         //       "textcyr" provided, if a language with font-encoding T2A is used in the document
567 }
568
569
570 bool LaTeXFeatures::mustProvide(string const & name) const
571 {
572         return isRequired(name) && !isProvided(name);
573 }
574
575
576 bool LaTeXFeatures::isAvailable(string const & name)
577 {
578         string::size_type const i = name.find("->");
579         if (i != string::npos) {
580                 string const from = name.substr(0,i);
581                 string const to = name.substr(i+2);
582                 //LYXERR0("from=[" << from << "] to=[" << to << "]");
583                 return theConverters().isReachable(from, to);
584         }
585         return LaTeXPackages::isAvailable(name);
586 }
587
588
589 void LaTeXFeatures::addPreambleSnippet(string const & preamble,
590                 bool allowdupes)
591 {
592         SnippetList::const_iterator begin = preamble_snippets_.begin();
593         SnippetList::const_iterator end   = preamble_snippets_.end();
594         if (allowdupes || find(begin, end, preamble) == end)
595                 preamble_snippets_.push_back(preamble);
596 }
597
598
599 void LaTeXFeatures::addCSSSnippet(std::string const & snippet)
600 {
601         SnippetList::const_iterator begin = css_snippets_.begin();
602         SnippetList::const_iterator end   = css_snippets_.end();
603         if (find(begin, end, snippet) == end)
604                 css_snippets_.push_back(snippet);
605 }
606
607
608 void LaTeXFeatures::useFloat(string const & name, bool subfloat)
609 {
610         if (!usedFloats_[name])
611                 usedFloats_[name] = subfloat;
612         if (subfloat)
613                 require("subfig");
614         // We only need float.sty if we use non builtin floats, or if we
615         // use the "H" modifier. This includes modified table and
616         // figure floats. (Lgb)
617         Floating const & fl = params_.documentClass().floats().getType(name);
618         if (!fl.floattype().empty() && fl.usesFloatPkg()) {
619                 require("float");
620         }
621 }
622
623
624 void LaTeXFeatures::useLanguage(Language const * lang)
625 {
626         if (!lang->babel().empty() || !lang->polyglossia().empty())
627                 UsedLanguages_.insert(lang);
628         if (!lang->requires().empty())
629                 require(lang->requires());
630         // CJK languages do not have a babel name.
631         // They use the CJK package
632         if (lang->encoding()->package() == Encoding::CJK)
633                 require("CJK");
634         // japanese package is special
635         if (lang->encoding()->package() == Encoding::japanese)
636                 require("japanese");
637 }
638
639
640 void LaTeXFeatures::includeFile(docstring const & key, string const & name)
641 {
642         IncludedFiles_[key] = name;
643 }
644
645
646 bool LaTeXFeatures::hasLanguages() const
647 {
648         return !UsedLanguages_.empty();
649 }
650
651
652 bool LaTeXFeatures::hasOnlyPolyglossiaLanguages() const
653 {
654         // first the main language
655         if (params_.language->polyglossia().empty())
656                 return false;
657         // now the secondary languages
658         LanguageList::const_iterator const begin = UsedLanguages_.begin();
659         for (LanguageList::const_iterator cit = begin;
660              cit != UsedLanguages_.end();
661              ++cit) {
662                 if ((*cit)->polyglossia().empty())
663                         return false;
664         }
665         return true;
666 }
667
668
669 bool LaTeXFeatures::hasPolyglossiaExclusiveLanguages() const
670 {
671         // first the main language
672         if (params_.language->isPolyglossiaExclusive())
673                 return true;
674         // now the secondary languages
675         LanguageList::const_iterator const begin = UsedLanguages_.begin();
676         for (LanguageList::const_iterator cit = begin;
677              cit != UsedLanguages_.end();
678              ++cit) {
679                 if ((*cit)->isPolyglossiaExclusive())
680                         return true;
681         }
682         return false;
683 }
684
685
686 string LaTeXFeatures::getBabelLanguages() const
687 {
688         ostringstream languages;
689
690         bool first = true;
691         LanguageList::const_iterator const begin = UsedLanguages_.begin();
692         for (LanguageList::const_iterator cit = begin;
693              cit != UsedLanguages_.end();
694              ++cit) {
695                 if ((*cit)->babel().empty())
696                         continue;
697                 if (!first)
698                         languages << ',';
699                 else
700                         first = false;
701                 languages << (*cit)->babel();
702         }
703         return languages.str();
704 }
705
706
707 std::map<std::string, std::string> LaTeXFeatures::getPolyglossiaLanguages() const
708 {
709         std::map<std::string, std::string> languages;
710
711         LanguageList::const_iterator const begin = UsedLanguages_.begin();
712         for (LanguageList::const_iterator cit = begin;
713              cit != UsedLanguages_.end();
714              ++cit) {
715                 languages[(*cit)->polyglossia()] = (*cit)->polyglossiaOpts();
716         }
717         return languages;
718 }
719
720
721 set<string> LaTeXFeatures::getEncodingSet(string const & doc_encoding) const
722 {
723         // This does only find encodings of languages supported by babel, but
724         // that does not matter since we don't have a language with an
725         // encoding supported by inputenc but without babel support.
726         set<string> encodings;
727         LanguageList::const_iterator it  = UsedLanguages_.begin();
728         LanguageList::const_iterator end = UsedLanguages_.end();
729         for (; it != end; ++it)
730                 if ((*it)->encoding()->latexName() != doc_encoding &&
731                     ((*it)->encoding()->package() == Encoding::inputenc
732                      || (*it)->encoding()->package() == Encoding::japanese))
733                         encodings.insert((*it)->encoding()->latexName());
734         return encodings;
735 }
736
737
738 void LaTeXFeatures::getFontEncodings(vector<string> & encodings) const
739 {
740         // these must be loaded if glyphs of this script are used
741         // unless a language providing them is used in the document
742         // FIXME: currently the option is written twice in this case
743         if (mustProvide("textgreek"))
744                 encodings.insert(encodings.begin(), "LGR");
745         if (mustProvide("textcyr"))
746                 encodings.insert(encodings.begin(), "T2A");
747
748         LanguageList::const_iterator it  = UsedLanguages_.begin();
749         LanguageList::const_iterator end = UsedLanguages_.end();
750         for (; it != end; ++it)
751                 if (!(*it)->fontenc().empty()
752                     && ascii_lowercase((*it)->fontenc()) != "none") {
753                         vector<string> extraencs = getVectorFromString((*it)->fontenc());
754                         vector<string>::const_iterator fit = extraencs.begin();
755                         for (; fit != extraencs.end(); ++fit) {
756                                 if (find(encodings.begin(), encodings.end(), *fit) == encodings.end())
757                                         encodings.insert(encodings.begin(), *fit);
758                         }
759                 }
760 }
761
762 namespace {
763
764 char const * simplefeatures[] = {
765 // note that the package order here will be the same in the LaTeX-output
766         "array",
767         "verbatim",
768         "longtable",
769         "rotating",
770         "latexsym",
771         "pifont",
772         // subfig is handled in BufferParams.cpp
773         "varioref",
774         "prettyref",
775         "refstyle",
776         /*For a successful cooperation of the `wrapfig' package with the
777           `float' package you should load the `wrapfig' package *after*
778           the `float' package. See the caption package documentation
779           for explanation.*/
780         "float",
781         "rotfloat",
782         "wrapfig",
783         "booktabs",
784         "dvipost",
785         "fancybox",
786         "calc",
787         "units",
788         "framed",
789         "soul",
790         "textcomp",
791         "pmboxdraw",
792         "bbding",
793         "ifsym",
794         "txfonts",
795         "pxfonts",
796         "mathdesign",
797         "mathrsfs",
798         "mathabx",
799         "mathtools",
800         // "cancel",
801         "ascii",
802         "url",
803         "covington",
804         "csquotes",
805         "enumitem",
806         "endnotes",
807         "hhline",
808         "ifthen",
809         // listings is handled in BufferParams.cpp
810         "bm",
811         "pdfpages",
812         "amscd",
813         "slashed",
814         "multicol",
815         "multirow",
816         "tfrupee",
817         "shapepar",
818         "rsphrase",
819         "hpstatement",
820         "algorithm2e",
821         "sectionbox",
822         "tcolorbox",
823         "pdfcomment",
824         "fixme",
825         "todonotes",
826         "forest",
827         "varwidth"
828 };
829
830 char const * bibliofeatures[] = {
831         // Known bibliography packages (will be loaded before natbib)
832         "achicago",
833         "apacite",
834         "apalike",
835         "astron",
836         "authordate1-4",
837         "babelbib",
838         "bibgerm",
839         "chicago",
840         "chscite",
841         "harvard",
842         "mslapa",
843         "named"
844 };
845
846 int const nb_bibliofeatures = sizeof(bibliofeatures) / sizeof(char const *);
847
848 int const nb_simplefeatures = sizeof(simplefeatures) / sizeof(char const *);
849
850 }
851
852
853 string const LaTeXFeatures::getColorOptions() const
854 {
855         ostringstream colors;
856
857         // Handling the color packages separately is needed to be able to load them
858         // before babel when hyperref is loaded with the colorlinks option
859         // for more info see Bufferparams.cpp
860
861         // [x]color.sty
862         if (mustProvide("color") || mustProvide("xcolor")) {
863                 string const package =
864                         (mustProvide("xcolor") ? "xcolor" : "color");
865                 if (params_.graphics_driver == "default"
866                         || params_.graphics_driver == "none")
867                         colors << "\\usepackage{" << package << "}\n";
868                 else
869                         colors << "\\usepackage["
870                                  << params_.graphics_driver
871                                  << "]{" << package << "}\n";
872         }
873
874         // pdfcolmk must be loaded after color
875         if (mustProvide("pdfcolmk"))
876                 colors << "\\usepackage{pdfcolmk}\n";
877
878         // the following 3 color commands must be set after color
879         // is loaded and before pdfpages, therefore add the command
880         // here define the set color
881         if (mustProvide("pagecolor")) {
882                 colors << "\\definecolor{page_backgroundcolor}{rgb}{";
883                 colors << outputLaTeXColor(params_.backgroundcolor) << "}\n";
884                 // set the page color
885                 colors << "\\pagecolor{page_backgroundcolor}\n";
886         }
887
888         if (mustProvide("fontcolor")) {
889                 colors << "\\definecolor{document_fontcolor}{rgb}{";
890                 colors << outputLaTeXColor(params_.fontcolor) << "}\n";
891                 // set the color
892                 colors << "\\color{document_fontcolor}\n";
893         }
894
895         if (mustProvide("lyxgreyedout")) {
896                 colors << "\\definecolor{note_fontcolor}{rgb}{";
897                 colors << outputLaTeXColor(params_.notefontcolor) << "}\n";
898                 // the color will be set together with the definition of
899                 // the lyxgreyedout environment (see lyxgreyedout_def)
900         }
901
902         // color for shaded boxes
903         if (isRequired("framed") && mustProvide("color")) {
904                 colors << "\\definecolor{shadecolor}{rgb}{";
905                 colors << outputLaTeXColor(params_.boxbgcolor) << "}\n";
906                 // this color is automatically used by the LaTeX-package "framed"
907         }
908
909         return colors.str();
910 }
911
912
913 string const LaTeXFeatures::getPackageOptions() const
914 {
915         ostringstream packageopts;
916         // Output all the package option stuff we have been asked to do.
917         map<string, string>::const_iterator it =
918                 params_.documentClass().packageOptions().begin();
919         map<string, string>::const_iterator en =
920                 params_.documentClass().packageOptions().end();
921         for (; it != en; ++it)
922                 if (mustProvide(it->first))
923                         packageopts << "\\PassOptionsToPackage{" << it->second << "}"
924                                  << "{" << it->first << "}\n";
925         return packageopts.str();
926 }
927
928
929 string const LaTeXFeatures::getPackages() const
930 {
931         ostringstream packages;
932
933         // FIXME: currently, we can only load packages and macros known
934         // to LyX.
935         // However, with the Require tag of layouts/custom insets,
936         // also unknown packages can be requested. They are silently
937         // swallowed now. We should change this eventually.
938
939         //  These are all the 'simple' includes.  i.e
940         //  packages which we just \usepackage{package}
941         for (int i = 0; i < nb_simplefeatures; ++i) {
942                 if (mustProvide(simplefeatures[i]))
943                         packages << "\\usepackage{" << simplefeatures[i] << "}\n";
944         }
945
946         // The rest of these packages are somewhat more complicated
947         // than those above.
948
949         // The tipa package and its extensions (tipx, tone) must not
950         // be loaded with non-TeX fonts, since fontspec includes the
951         // respective macros
952         if (mustProvide("tipa") && !params_.useNonTeXFonts)
953                 packages << "\\usepackage{tipa}\n";
954         if (mustProvide("tipx") && !params_.useNonTeXFonts)
955                 packages << "\\usepackage{tipx}\n";
956         if (mustProvide("extraipa") && !params_.useNonTeXFonts)
957                 packages << "\\usepackage{extraipa}\n";
958         if (mustProvide("tone") && !params_.useNonTeXFonts)
959                 packages << "\\usepackage{tone}\n";
960
961         // if fontspec or newtxmath is used, AMS packages have to be loaded
962         // before fontspec (in BufferParams)
963         string const amsPackages = loadAMSPackages();
964         bool const ot1 = (params_.font_encoding() == "default" || params_.font_encoding() == "OT1");
965         bool const use_newtxmath =
966                 theLaTeXFonts().getLaTeXFont(from_ascii(params_.fontsMath())).getUsedPackage(
967                         ot1, false, false) == "newtxmath";
968
969         if (!params_.useNonTeXFonts && !use_newtxmath && !amsPackages.empty())
970                 packages << amsPackages;
971
972         if (mustProvide("cancel") &&
973             params_.use_package("cancel") != BufferParams::package_off)
974                 packages << "\\usepackage{cancel}\n";
975
976         // marvosym and bbding both define the \Cross macro
977         if (mustProvide("marvosym")) {
978             if (mustProvide("bbding"))
979                 packages << "\\let\\Cross\\relax\n";
980             packages << "\\usepackage{marvosym}\n";
981         }
982
983         // accents must be loaded after amsmath
984         if (mustProvide("accents") &&
985             params_.use_package("accents") != BufferParams::package_off)
986                 packages << "\\usepackage{accents}\n";
987
988         // mathdots must be loaded after amsmath
989         if (mustProvide("mathdots") &&
990                 params_.use_package("mathdots") != BufferParams::package_off)
991                 packages << "\\usepackage{mathdots}\n";
992
993         // yhmath must be loaded after amsmath
994         if (mustProvide("yhmath") &&
995             params_.use_package("yhmath") != BufferParams::package_off)
996                 packages << "\\usepackage{yhmath}\n";
997
998         // stmaryrd must be loaded after amsmath
999         if (mustProvide("stmaryrd") &&
1000             params_.use_package("stmaryrd") != BufferParams::package_off)
1001                 packages << "\\usepackage{stmaryrd}\n";
1002
1003         if (mustProvide("stackrel") &&
1004             params_.use_package("stackrel") != BufferParams::package_off)
1005                 packages << "\\usepackage{stackrel}\n";
1006
1007         if (mustProvide("undertilde") &&
1008                 params_.use_package("undertilde") != BufferParams::package_off)
1009                 packages << "\\usepackage{undertilde}\n";
1010
1011         // [x]color and pdfcolmk are handled in getColorOptions() above
1012
1013         // makeidx.sty
1014         if (isRequired("makeidx") || isRequired("splitidx")) {
1015                 if (!isProvided("makeidx") && !isRequired("splitidx"))
1016                         packages << "\\usepackage{makeidx}\n";
1017                 if (mustProvide("splitidx"))
1018                         packages << "\\usepackage{splitidx}\n";
1019                 packages << "\\makeindex\n";
1020         }
1021
1022         // graphicx.sty
1023         if (mustProvide("graphicx") && params_.graphics_driver != "none") {
1024                 if (params_.graphics_driver == "default")
1025                         packages << "\\usepackage{graphicx}\n";
1026                 else
1027                         packages << "\\usepackage["
1028                                  << params_.graphics_driver
1029                                  << "]{graphicx}\n";
1030         }
1031
1032         // lyxskak.sty --- newer chess support based on skak.sty
1033         if (mustProvide("chess"))
1034                 packages << "\\usepackage[ps,mover]{lyxskak}\n";
1035
1036         // setspace.sty
1037         if (mustProvide("setspace") && !isProvided("SetSpace"))
1038                 packages << "\\usepackage{setspace}\n";
1039
1040         // we need to assure that mhchem is loaded before esint and every other
1041         // package that redefines command of amsmath because mhchem loads amlatex
1042         // (this info is from the author of mhchem from June 2013)
1043         if (mustProvide("mhchem") &&
1044             params_.use_package("mhchem") != BufferParams::package_off)
1045                 packages << "\\PassOptionsToPackage{version=3}{mhchem}\n"
1046                             "\\usepackage{mhchem}\n";
1047
1048         // wasysym is a simple feature, but it must be after amsmath if both
1049         // are used
1050         // wasysym redefines some integrals (e.g. iint) from amsmath. That
1051         // leads to inconsistent integrals. We only load this package if
1052         // the document does not contain integrals (then isRequired("esint")
1053         // is false) or if esint is used, since esint redefines all relevant
1054         // integral symbols from wasysym and amsmath.
1055         // See http://www.lyx.org/trac/ticket/1942
1056         if (mustProvide("wasysym") &&
1057             params_.use_package("wasysym") != BufferParams::package_off &&
1058             (params_.use_package("esint") != BufferParams::package_off || !isRequired("esint")))
1059                 packages << "\\usepackage{wasysym}\n";
1060
1061         // esint must be after amsmath (and packages requiring amsmath, like mhchem)
1062         // and wasysym, since it will redeclare inconsistent integral symbols
1063         if (mustProvide("esint") &&
1064             params_.use_package("esint") != BufferParams::package_off)
1065                 packages << "\\usepackage{esint}\n";
1066
1067         // Known bibliography packages (simple \usepackage{package})
1068         for (int i = 0; i < nb_bibliofeatures; ++i) {
1069                 if (mustProvide(bibliofeatures[i]))
1070                         packages << "\\usepackage{"
1071                                  << bibliofeatures[i] << "}\n";
1072         }
1073
1074         // Compatibility between achicago and natbib
1075         if (mustProvide("achicago") && mustProvide("natbib"))
1076                 packages << "\\let\\achicagobib\\thebibliography\n";
1077
1078         // natbib.sty
1079         // Some classes load natbib themselves, but still allow (or even require)
1080         // plain numeric citations (ReVTeX is such a case, see bug 5182).
1081         // This special case is indicated by the "natbib-internal" key.
1082         if (mustProvide("natbib") && !isProvided("natbib-internal")) {
1083                 packages << "\\usepackage[";
1084                 if (params_.citeEngineType() == ENGINE_TYPE_NUMERICAL)
1085                         packages << "numbers";
1086                 else
1087                         packages << "authoryear";
1088                 packages << "]{natbib}\n";
1089         }
1090
1091         // Compatibility between achicago and natbib
1092         if (mustProvide("achicago") && mustProvide("natbib")) {
1093                 packages << "\\let\\thebibliography\\achicagobib\n";
1094                 packages << "\\let\\SCcite\\astroncite\n";
1095                 packages << "\\let\\UnexpandableProtect\\protect\n";
1096         }
1097
1098         // jurabib -- we need version 0.6 at least.
1099         if (mustProvide("jurabib"))
1100                 packages << "\\usepackage{jurabib}[2004/01/25]\n";
1101
1102         // opcit -- we pass custombst as we output \bibliographystyle ourselves
1103         if (mustProvide("opcit")) {
1104                 if (isRequired("hyperref"))
1105                         packages << "\\usepackage[custombst,hyperref]{opcit}\n";
1106                 else
1107                         packages << "\\usepackage[custombst]{opcit}\n";
1108         }
1109
1110         // xargs -- we need version 1.09 at least
1111         if (mustProvide("xargs"))
1112                 packages << "\\usepackage{xargs}[2008/03/08]\n";
1113
1114         if (mustProvide("xy"))
1115                 packages << "\\usepackage[all]{xy}\n";
1116
1117         if (mustProvide("feyn"))
1118                 packages << "\\usepackage{feyn}\n"; //Diagram
1119
1120         if (mustProvide("ulem"))
1121                 packages << "\\PassOptionsToPackage{normalem}{ulem}\n"
1122                             "\\usepackage{ulem}\n";
1123
1124         if (mustProvide("nomencl")) {
1125                 // Make it work with the new and old version of the package,
1126                 // but don't use the compatibility option since it is
1127                 // incompatible to other packages.
1128                 packages << "\\usepackage{nomencl}\n"
1129                             "% the following is useful when we have the old nomencl.sty package\n"
1130                             "\\providecommand{\\printnomenclature}{\\printglossary}\n"
1131                             "\\providecommand{\\makenomenclature}{\\makeglossary}\n"
1132                             "\\makenomenclature\n";
1133         }
1134
1135         // fixltx2e provides subscript
1136         if (mustProvide("subscript") && !isRequired("fixltx2e"))
1137                 packages << "\\usepackage{subscript}\n";
1138
1139         // footmisc must be loaded after setspace
1140         // Set options here, load the package after the user preamble to
1141         // avoid problems with manual loaded footmisc.
1142         if (mustProvide("footmisc"))
1143                 packages << "\\PassOptionsToPackage{stable}{footmisc}\n";
1144
1145         if (mustProvide("microtype")){
1146                 packages << "\\usepackage{microtype}\n";
1147         }
1148
1149         return packages.str();
1150 }
1151
1152
1153 string LaTeXFeatures::getPreambleSnippets() const
1154 {
1155         ostringstream snip;
1156         SnippetList::const_iterator pit  = preamble_snippets_.begin();
1157         SnippetList::const_iterator pend = preamble_snippets_.end();
1158         for (; pit != pend; ++pit)
1159                 snip << *pit << '\n';
1160         return snip.str();
1161 }
1162
1163
1164 std::string LaTeXFeatures::getCSSSnippets() const
1165 {
1166         ostringstream snip;
1167         SnippetList::const_iterator pit  = css_snippets_.begin();
1168         SnippetList::const_iterator pend = css_snippets_.end();
1169         for (; pit != pend; ++pit)
1170                 snip << *pit << '\n';
1171         return snip.str();
1172 }
1173
1174
1175 docstring const LaTeXFeatures::getMacros() const
1176 {
1177         odocstringstream macros;
1178
1179         if (!preamble_snippets_.empty()) {
1180                 macros << '\n';
1181                 macros << from_utf8(getPreambleSnippets());
1182         }
1183
1184         if (mustProvide("papersize")) {
1185                 if (runparams_.flavor == OutputParams::LATEX
1186                     || runparams_.flavor == OutputParams::DVILUATEX)
1187                         macros << papersizedvi_def << '\n';
1188                 else if  (runparams_.flavor == OutputParams::LUATEX)
1189                         macros << papersizepdflua_def << '\n';
1190                 else
1191                         macros << papersizepdf_def << '\n';
1192         }
1193
1194         if (mustProvide("LyX")) {
1195                 if (isRequired("hyperref"))
1196                         macros << lyx_hyperref_def << '\n';
1197                 else
1198                         macros << lyx_def << '\n';
1199         }
1200
1201         if (mustProvide("noun"))
1202                 macros << noun_def << '\n';
1203
1204         if (mustProvide("lyxarrow"))
1205                 macros << lyxarrow_def << '\n';
1206
1207         if (!usePolyglossia() && mustProvide("textgreek")) {
1208                 // ensure LGR font encoding is defined also if fontenc is not loaded by LyX
1209                 if (params_.font_encoding() == "default")
1210                         macros << textgreek_LGR_def;
1211                 macros << textgreek_def << '\n';
1212         }
1213
1214         if (!usePolyglossia() && mustProvide("textcyr")) {
1215                 // ensure T2A font encoding is set up also if fontenc is not loaded by LyX
1216                 if (params_.font_encoding() == "default")
1217                         macros << textcyr_T2A_def;
1218                 macros << textcyr_def << '\n';
1219         }
1220
1221         // non-standard text accents:
1222         if (mustProvide("textcommaabove") || mustProvide("textcommaaboveright") ||
1223             mustProvide("textcommabelow") || mustProvide("textbaltic"))
1224                 macros << lyxaccent_def;
1225
1226         if (mustProvide("textcommabelow") || mustProvide("textbaltic"))
1227                 macros << textcommabelow_def << '\n';
1228
1229         if (mustProvide("textcommaabove") || mustProvide("textbaltic"))
1230                 macros << textcommaabove_def << '\n';
1231
1232         if (mustProvide("textcommaaboveright"))
1233                 macros << textcommaaboveright_def << '\n';
1234
1235         if (mustProvide("textbaltic"))
1236                 macros << textbaltic_def << '\n';
1237
1238         if (mustProvide("lyxmathsym"))
1239                 macros << lyxmathsym_def << '\n';
1240
1241         if (mustProvide("cedilla"))
1242                 macros << cedilla_def << '\n';
1243
1244         if (mustProvide("subring"))
1245                 macros << subring_def << '\n';
1246
1247         if (mustProvide("subdot"))
1248                 macros << subdot_def << '\n';
1249
1250         if (mustProvide("subhat"))
1251                 macros << subhat_def << '\n';
1252
1253         if (mustProvide("subtilde"))
1254                 macros << subtilde_def << '\n';
1255
1256         if (mustProvide("dacute"))
1257                 macros << dacute_def << '\n';
1258
1259         if (mustProvide("tipasymb"))
1260                 macros << tipasymb_def << '\n';
1261
1262         if (mustProvide("dgrave"))
1263                 macros << dgrave_def << '\n';
1264
1265         if (mustProvide("rcap"))
1266                 macros << rcap_def << '\n';
1267
1268         if (mustProvide("ogonek"))
1269                 macros << ogonek_def << '\n';
1270
1271         // quotes.
1272         if (mustProvide("quotesinglbase"))
1273                 macros << quotesinglbase_def << '\n';
1274         if (mustProvide("quotedblbase"))
1275                 macros << quotedblbase_def << '\n';
1276         if (mustProvide("guilsinglleft"))
1277                 macros << guilsinglleft_def << '\n';
1278         if (mustProvide("guilsinglright"))
1279                 macros << guilsinglright_def << '\n';
1280         if (mustProvide("guillemotleft"))
1281                 macros << guillemotleft_def << '\n';
1282         if (mustProvide("guillemotright"))
1283                 macros << guillemotright_def << '\n';
1284
1285         // Math mode
1286         if (mustProvide("binom") && !isRequired("amsmath"))
1287                 macros << binom_def << '\n';
1288         if (mustProvide("mathcircumflex"))
1289                 macros << mathcircumflex_def << '\n';
1290
1291         // other
1292         if (mustProvide("ParagraphLeftIndent"))
1293                 macros << paragraphleftindent_def;
1294         if (mustProvide("NeedLyXFootnoteCode"))
1295                 macros << floatingfootnote_def;
1296
1297         // some problems with tex->html converters
1298         if (mustProvide("NeedTabularnewline"))
1299                 macros << tabularnewline_def;
1300
1301         // greyed-out environment (note inset)
1302         // the color is specified in the routine
1303         // getColorOptions() to avoid LaTeX-package clashes
1304         if (mustProvide("lyxgreyedout"))
1305                 macros << lyxgreyedout_def;
1306
1307         if (mustProvide("lyxdot"))
1308                 macros << lyxdot_def << '\n';
1309
1310         // floats
1311         getFloatDefinitions(macros);
1312
1313         if (mustProvide("refstyle"))
1314                 macros << lyxref_def << '\n';
1315
1316         // change tracking
1317         if (mustProvide("ct-dvipost"))
1318                 macros << changetracking_dvipost_def;
1319
1320         if (mustProvide("ct-xcolor-ulem")) {
1321                 streamsize const prec = macros.precision(2);
1322
1323                 RGBColor cadd = rgbFromHexName(lcolor.getX11Name(Color_addedtext));
1324                 macros << "\\providecolor{lyxadded}{rgb}{"
1325                        << cadd.r / 255.0 << ',' << cadd.g / 255.0 << ',' << cadd.b / 255.0 << "}\n";
1326
1327                 RGBColor cdel = rgbFromHexName(lcolor.getX11Name(Color_deletedtext));
1328                 macros << "\\providecolor{lyxdeleted}{rgb}{"
1329                        << cdel.r / 255.0 << ',' << cdel.g / 255.0 << ',' << cdel.b / 255.0 << "}\n";
1330
1331                 macros.precision(prec);
1332
1333                 if (isRequired("hyperref"))
1334                         macros << changetracking_xcolor_ulem_hyperref_def;
1335                 else
1336                         macros << changetracking_xcolor_ulem_def;
1337         }
1338
1339         if (mustProvide("ct-none"))
1340                 macros << changetracking_none_def;
1341
1342         if (mustProvide("rtloutputdblcol"))
1343                 macros << rtloutputdblcol_def;
1344
1345         return macros.str();
1346 }
1347
1348
1349 string const LaTeXFeatures::getBabelPresettings() const
1350 {
1351         ostringstream tmp;
1352
1353         LanguageList::const_iterator it  = UsedLanguages_.begin();
1354         LanguageList::const_iterator end = UsedLanguages_.end();
1355         for (; it != end; ++it)
1356                 if (!(*it)->babel_presettings().empty())
1357                         tmp << (*it)->babel_presettings() << '\n';
1358         if (!params_.language->babel_presettings().empty())
1359                 tmp << params_.language->babel_presettings() << '\n';
1360
1361         if (!contains(tmp.str(), '@'))
1362                 return tmp.str();
1363
1364         return "\\makeatletter\n" + tmp.str() + "\\makeatother\n";
1365 }
1366
1367
1368 string const LaTeXFeatures::getBabelPostsettings() const
1369 {
1370         ostringstream tmp;
1371
1372         LanguageList::const_iterator it  = UsedLanguages_.begin();
1373         LanguageList::const_iterator end = UsedLanguages_.end();
1374         for (; it != end; ++it)
1375                 if (!(*it)->babel_postsettings().empty())
1376                         tmp << (*it)->babel_postsettings() << '\n';
1377         if (!params_.language->babel_postsettings().empty())
1378                 tmp << params_.language->babel_postsettings() << '\n';
1379
1380         if (!contains(tmp.str(), '@'))
1381                 return tmp.str();
1382
1383         return "\\makeatletter\n" + tmp.str() + "\\makeatother\n";
1384 }
1385
1386
1387 bool LaTeXFeatures::needBabelLangOptions() const
1388 {
1389         if (!lyxrc.language_global_options || params_.language->asBabelOptions())
1390                 return true;
1391
1392         LanguageList::const_iterator it  = UsedLanguages_.begin();
1393         LanguageList::const_iterator end = UsedLanguages_.end();
1394         for (; it != end; ++it)
1395                 if ((*it)->asBabelOptions())
1396                         return true;
1397
1398         return false;
1399 }
1400
1401
1402 string const LaTeXFeatures::loadAMSPackages() const
1403 {
1404         ostringstream tmp;
1405
1406         if (mustProvide("amsmath")
1407             && params_.use_package("amsmath") != BufferParams::package_off) {
1408                 tmp << "\\usepackage{amsmath}\n";
1409         } else {
1410                 // amsbsy and amstext are already provided by amsmath
1411                 if (mustProvide("amsbsy"))
1412                         tmp << "\\usepackage{amsbsy}\n";
1413                 if (mustProvide("amstext"))
1414                         tmp << "\\usepackage{amstext}\n";
1415         }
1416
1417         if (mustProvide("amsthm"))
1418                 tmp << "\\usepackage{amsthm}\n";
1419
1420         if (mustProvide("amssymb")
1421             && params_.use_package("amssymb") != BufferParams::package_off)
1422                 tmp << "\\usepackage{amssymb}\n";
1423
1424         return tmp.str();
1425 }
1426
1427
1428 docstring const LaTeXFeatures::getTClassPreamble() const
1429 {
1430         // the text class specific preamble
1431         DocumentClass const & tclass = params_.documentClass();
1432         odocstringstream tcpreamble;
1433
1434         tcpreamble << tclass.preamble();
1435
1436         list<docstring>::const_iterator cit = usedLayouts_.begin();
1437         list<docstring>::const_iterator end = usedLayouts_.end();
1438         for (; cit != end; ++cit)
1439                 tcpreamble << tclass[*cit].preamble();
1440
1441         cit = usedInsetLayouts_.begin();
1442         end = usedInsetLayouts_.end();
1443         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1444         for (; cit != end; ++cit) {
1445                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1446                 if (it == ils.end())
1447                         continue;
1448                 tcpreamble << it->second.preamble();
1449         }
1450
1451         return tcpreamble.str();
1452 }
1453
1454
1455 docstring const LaTeXFeatures::getTClassHTMLPreamble() const
1456 {
1457         DocumentClass const & tclass = params_.documentClass();
1458         odocstringstream tcpreamble;
1459
1460         tcpreamble << tclass.htmlpreamble();
1461
1462         list<docstring>::const_iterator cit = usedLayouts_.begin();
1463         list<docstring>::const_iterator end = usedLayouts_.end();
1464         for (; cit != end; ++cit)
1465                 tcpreamble << tclass[*cit].htmlpreamble();
1466
1467         cit = usedInsetLayouts_.begin();
1468         end = usedInsetLayouts_.end();
1469         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1470         for (; cit != end; ++cit) {
1471                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1472                 if (it == ils.end())
1473                         continue;
1474                 tcpreamble << it->second.htmlpreamble();
1475         }
1476
1477         return tcpreamble.str();
1478 }
1479
1480
1481 docstring const LaTeXFeatures::getTClassHTMLStyles() const
1482 {
1483         DocumentClass const & tclass = params_.documentClass();
1484         odocstringstream tcpreamble;
1485
1486         if (mustProvide("noun"))
1487                 tcpreamble << lyxnoun_style;
1488         // this isn't exact, but it won't hurt that much if it
1489         // wasn't for this.
1490         if (mustProvide("ulem"))
1491                 tcpreamble << lyxstrikeout_style;
1492
1493         tcpreamble << tclass.htmlstyles();
1494
1495         list<docstring>::const_iterator cit = usedLayouts_.begin();
1496         list<docstring>::const_iterator end = usedLayouts_.end();
1497         for (; cit != end; ++cit)
1498                 tcpreamble << tclass[*cit].htmlstyle();
1499
1500         cit = usedInsetLayouts_.begin();
1501         end = usedInsetLayouts_.end();
1502         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1503         for (; cit != end; ++cit) {
1504                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1505                 if (it == ils.end())
1506                         continue;
1507                 tcpreamble << it->second.htmlstyle();
1508         }
1509
1510         return tcpreamble.str();
1511 }
1512
1513
1514 namespace {
1515
1516 docstring const getFloatI18nPreamble(docstring const & type,
1517                         docstring const & name, Language const * lang,
1518                         Encoding const & enc, bool const polyglossia)
1519 {
1520         // Check whether name can be encoded in the buffer encoding
1521         bool encodable = true;
1522         for (size_t i = 0; i < name.size(); ++i) {
1523                 if (!enc.encodable(name[i])) {
1524                         encodable = false;
1525                         break;
1526                 }
1527         }
1528
1529         docstring const language = polyglossia ? from_ascii(lang->polyglossia())
1530                                                : from_ascii(lang->babel());
1531         docstring const langenc = from_ascii(lang->encoding()->iconvName());
1532         docstring const texenc = from_ascii(lang->encoding()->latexName());
1533         docstring const bufenc = from_ascii(enc.iconvName());
1534         docstring const s1 = docstring(1, 0xF0000);
1535         docstring const s2 = docstring(1, 0xF0001);
1536         docstring const translated = encodable ? name
1537                 : from_ascii("\\inputencoding{") + texenc + from_ascii("}")
1538                         + s1 + langenc + s2 + name + s1 + bufenc + s2;
1539
1540         odocstringstream os;
1541         os << "\\addto\\captions" << language
1542            << "{\\renewcommand{\\" << type << "name}{" << translated << "}}\n";
1543         return os.str();
1544 }
1545
1546
1547 docstring const i18npreamble(docstring const & templ, Language const * lang,
1548                              Encoding const & enc, bool const polyglossia,
1549                              bool const need_fixedwidth)
1550 {
1551         if (templ.empty())
1552                 return templ;
1553
1554         string preamble = polyglossia ?
1555                 subst(to_utf8(templ), "$$lang", lang->polyglossia()) :
1556                 subst(to_utf8(templ), "$$lang", lang->babel());
1557
1558         string const langenc = lang->encoding()->iconvName();
1559         string const texenc = lang->encoding()->latexName();
1560         string const bufenc = enc.iconvName();
1561         Encoding const * testenc(&enc);
1562         bool lang_fallback = false;
1563         bool ascii_fallback = false;
1564         if (need_fixedwidth && !enc.hasFixedWidth()) {
1565                 if (lang->encoding()->hasFixedWidth()) {
1566                         testenc = lang->encoding();
1567                         lang_fallback = true;
1568                 } else {
1569                         // We need a fixed width encoding, but both the buffer
1570                         // encoding and the language encoding are variable
1571                         // width. As a last fallback, try to convert to pure
1572                         // ASCII using the LaTeX commands defined in unicodesymbols.
1573                         testenc = encodings.fromLyXName("ascii");
1574                         if (!testenc)
1575                                 return docstring();
1576                         ascii_fallback = true;
1577                 }
1578         }
1579         // First and second character of plane 15 (Private Use Area)
1580         string const s1 = "\xf3\xb0\x80\x80"; // U+F0000
1581         string const s2 = "\xf3\xb0\x80\x81"; // U+F0001
1582         // FIXME UNICODE
1583         // lyx::regex is not unicode-safe.
1584         // Should use QRegExp or (boost::u32regex, but that requires ICU)
1585         static regex const reg("_\\(([^\\)]+)\\)");
1586         smatch sub;
1587         while (regex_search(preamble, sub, reg)) {
1588                 string const key = sub.str(1);
1589                 docstring const name = lang->translateLayout(key);
1590                 // Check whether name can be encoded in the buffer encoding
1591                 bool encodable = true;
1592                 for (size_t i = 0; i < name.size() && encodable; ++i)
1593                         if (!testenc->encodable(name[i]))
1594                                 encodable = false;
1595                 string translated;
1596                 if (encodable && !lang_fallback)
1597                         translated = to_utf8(name);
1598                 else if (ascii_fallback)
1599                         translated = to_ascii(testenc->latexString(name).first);
1600                 else
1601                         translated = "\\inputencoding{" + texenc + "}"
1602                                 + s1 + langenc + s2 + to_utf8(name)
1603                                 + s1 + bufenc + s2;
1604                 preamble = subst(preamble, sub.str(), translated);
1605         }
1606         return from_utf8(preamble);
1607 }
1608
1609 }
1610
1611
1612 docstring const LaTeXFeatures::getTClassI18nPreamble(bool use_babel, bool use_polyglossia) const
1613 {
1614         DocumentClass const & tclass = params_.documentClass();
1615         // collect preamble snippets in a set to prevent multiple identical
1616         // commands (would happen if e.g. both theorem and theorem* are used)
1617         set<docstring> snippets;
1618         typedef LanguageList::const_iterator lang_it;
1619         lang_it const lbeg = UsedLanguages_.begin();
1620         lang_it const lend =  UsedLanguages_.end();
1621         list<docstring>::const_iterator cit = usedLayouts_.begin();
1622         list<docstring>::const_iterator end = usedLayouts_.end();
1623         for (; cit != end; ++cit) {
1624                 // language dependent commands (once per document)
1625                 snippets.insert(i18npreamble(tclass[*cit].langpreamble(),
1626                                                 buffer().language(),
1627                                                 buffer().params().encoding(),
1628                                                 use_polyglossia, false));
1629                 // commands for language changing (for multilanguage documents)
1630                 if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1631                         snippets.insert(i18npreamble(
1632                                                 tclass[*cit].babelpreamble(),
1633                                                 buffer().language(),
1634                                                 buffer().params().encoding(),
1635                                                 use_polyglossia, false));
1636                         for (lang_it lit = lbeg; lit != lend; ++lit)
1637                                 snippets.insert(i18npreamble(
1638                                                 tclass[*cit].babelpreamble(),
1639                                                 *lit,
1640                                                 buffer().params().encoding(),
1641                                                 use_polyglossia, false));
1642                 }
1643         }
1644         if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1645                 FloatList const & floats = params_.documentClass().floats();
1646                 UsedFloats::const_iterator fit = usedFloats_.begin();
1647                 UsedFloats::const_iterator fend = usedFloats_.end();
1648                 for (; fit != fend; ++fit) {
1649                         Floating const & fl = floats.getType(fit->first);
1650                         // we assume builtin floats are translated
1651                         if (fl.isPredefined())
1652                                 continue;
1653                         docstring const type = from_ascii(fl.floattype());
1654                         docstring const flname = from_utf8(fl.name());
1655                         docstring name = buffer().language()->translateLayout(fl.name());
1656                         // only request translation if we have a real translation
1657                         // (that differs from the source)
1658                         if (flname != name)
1659                                 snippets.insert(getFloatI18nPreamble(
1660                                                 type, name, buffer().language(),
1661                                                 buffer().params().encoding(),
1662                                                 use_polyglossia));
1663                         for (lang_it lit = lbeg; lit != lend; ++lit) {
1664                                 string const code = (*lit)->code();
1665                                 name = (*lit)->translateLayout(fl.name());
1666                                 // we assume we have a suitable translation if
1667                                 // either the language is English (we need to
1668                                 // translate into English if English is a secondary
1669                                 // language) or if translateIfPossible returns
1670                                 // something different to the English source.
1671                                 bool const have_translation =
1672                                         (flname != name || contains(code, "en"));
1673                                 if (have_translation)
1674                                         snippets.insert(getFloatI18nPreamble(
1675                                                 type, name, *lit,
1676                                                 buffer().params().encoding(),
1677                                                 use_polyglossia));
1678                         }
1679                 }
1680         }
1681
1682         cit = usedInsetLayouts_.begin();
1683         end = usedInsetLayouts_.end();
1684         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1685         for (; cit != end; ++cit) {
1686                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1687                 if (it == ils.end())
1688                         continue;
1689                 // The listings package does not work with variable width
1690                 // encodings, only with fixed width encodings. Therefore we
1691                 // need to force a fixed width encoding for
1692                 // \lstlistlistingname and \lstlistingname (bug 9382).
1693                 // This needs to be consistent with InsetListings::latex().
1694                 bool const need_fixedwidth = !runparams_.isFullUnicode() &&
1695                                 it->second.fixedwidthpreambleencoding();
1696                 // language dependent commands (once per document)
1697                 snippets.insert(i18npreamble(it->second.langpreamble(),
1698                                                 buffer().language(),
1699                                                 buffer().params().encoding(),
1700                                                 use_polyglossia, need_fixedwidth));
1701                 // commands for language changing (for multilanguage documents)
1702                 if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1703                         snippets.insert(i18npreamble(
1704                                                 it->second.babelpreamble(),
1705                                                 buffer().language(),
1706                                                 buffer().params().encoding(),
1707                                                 use_polyglossia, need_fixedwidth));
1708                         for (lang_it lit = lbeg; lit != lend; ++lit)
1709                                 snippets.insert(i18npreamble(
1710                                                 it->second.babelpreamble(),
1711                                                 *lit,
1712                                                 buffer().params().encoding(),
1713                                                 use_polyglossia, need_fixedwidth));
1714                 }
1715         }
1716
1717         odocstringstream tcpreamble;
1718         set<docstring>::const_iterator const send = snippets.end();
1719         set<docstring>::const_iterator it = snippets.begin();
1720         for (; it != send; ++it)
1721                 tcpreamble << *it;
1722         return tcpreamble.str();
1723 }
1724
1725
1726 docstring const LaTeXFeatures::getLyXSGMLEntities() const
1727 {
1728         // Definition of entities used in the document that are LyX related.
1729         odocstringstream entities;
1730
1731         if (mustProvide("lyxarrow")) {
1732                 entities << "<!ENTITY lyxarrow \"-&gt;\">" << '\n';
1733         }
1734
1735         return entities.str();
1736 }
1737
1738
1739 docstring const LaTeXFeatures::getIncludedFiles(string const & fname) const
1740 {
1741         odocstringstream sgmlpreamble;
1742         // FIXME UNICODE
1743         docstring const basename(from_utf8(onlyPath(fname)));
1744
1745         FileMap::const_iterator end = IncludedFiles_.end();
1746         for (FileMap::const_iterator fi = IncludedFiles_.begin();
1747              fi != end; ++fi)
1748                 // FIXME UNICODE
1749                 sgmlpreamble << "\n<!ENTITY " << fi->first
1750                              << (isSGMLFileName(fi->second) ? " SYSTEM \"" : " \"")
1751                              << makeRelPath(from_utf8(fi->second), basename) << "\">";
1752
1753         return sgmlpreamble.str();
1754 }
1755
1756
1757 void LaTeXFeatures::showStruct() const
1758 {
1759         lyxerr << "LyX needs the following commands when LaTeXing:"
1760                << "\n***** Packages:" << getPackages()
1761                << "\n***** Macros:" << to_utf8(getMacros())
1762                << "\n***** Textclass stuff:" << to_utf8(getTClassPreamble())
1763                << "\n***** done." << endl;
1764 }
1765
1766
1767 Buffer const & LaTeXFeatures::buffer() const
1768 {
1769         return *buffer_;
1770 }
1771
1772
1773 void LaTeXFeatures::setBuffer(Buffer const & buffer)
1774 {
1775         buffer_ = &buffer;
1776 }
1777
1778
1779 BufferParams const & LaTeXFeatures::bufferParams() const
1780 {
1781         return params_;
1782 }
1783
1784
1785 void LaTeXFeatures::getFloatDefinitions(odocstream & os) const
1786 {
1787         FloatList const & floats = params_.documentClass().floats();
1788
1789         // Here we will output the code to create the needed float styles.
1790         // We will try to do this as minimal as possible.
1791         // \floatstyle{ruled}
1792         // \newfloat{algorithm}{htbp}{loa}
1793         // \providecommand{\algorithmname}{Algorithm}
1794         // \floatname{algorithm}{\protect\algorithmname}
1795         UsedFloats::const_iterator cit = usedFloats_.begin();
1796         UsedFloats::const_iterator end = usedFloats_.end();
1797         for (; cit != end; ++cit) {
1798                 Floating const & fl = floats.getType(cit->first);
1799
1800                 // For builtin floats we do nothing.
1801                 if (fl.isPredefined())
1802                         continue;
1803
1804                 // We have to special case "table" and "figure"
1805                 if (fl.floattype() == "tabular" || fl.floattype() == "figure") {
1806                         // Output code to modify "table" or "figure"
1807                         // but only if builtin == false
1808                         // and that have to be true at this point in the
1809                         // function.
1810                         docstring const type = from_ascii(fl.floattype());
1811                         docstring const placement = from_ascii(fl.placement());
1812                         docstring const style = from_ascii(fl.style());
1813                         if (!style.empty()) {
1814                                 os << "\\floatstyle{" << style << "}\n"
1815                                    << "\\restylefloat{" << type << "}\n";
1816                         }
1817                         if (!placement.empty()) {
1818                                 os << "\\floatplacement{" << type << "}{"
1819                                    << placement << "}\n";
1820                         }
1821                 } else {
1822                         // The other non builtin floats.
1823
1824                         docstring const type = from_ascii(fl.floattype());
1825                         docstring const placement = from_ascii(fl.placement());
1826                         docstring const ext = from_ascii(fl.ext());
1827                         docstring const within = from_ascii(fl.within());
1828                         docstring const style = from_ascii(fl.style());
1829                         docstring const name =
1830                                 buffer().language()->translateLayout(fl.name());
1831                         os << "\\floatstyle{" << style << "}\n"
1832                            << "\\newfloat{" << type << "}{" << placement
1833                            << "}{" << ext << '}';
1834                         if (!within.empty())
1835                                 os << '[' << within << ']';
1836                         os << '\n'
1837                            << "\\providecommand{\\" << type << "name}{"
1838                            << name << "}\n"
1839                            << "\\floatname{" << type << "}{\\protect\\"
1840                            << type << "name}\n";
1841
1842                         // What missing here is to code to minimalize the code
1843                         // output so that the same floatstyle will not be
1844                         // used several times, when the same style is still in
1845                         // effect. (Lgb)
1846                 }
1847                 if (cit->second)
1848                         // The subfig package is loaded later
1849                         os << "\n\\AtBeginDocument{\\newsubfloat{" << from_ascii(fl.floattype()) << "}}\n";
1850         }
1851 }
1852
1853
1854 void LaTeXFeatures::resolveAlternatives()
1855 {
1856         for (Features::iterator it = features_.begin(); it != features_.end();) {
1857                 if (contains(*it, '|')) {
1858                         vector<string> const alternatives = getVectorFromString(*it, "|");
1859                         vector<string>::const_iterator const end = alternatives.end();
1860                         vector<string>::const_iterator ita = alternatives.begin();
1861                         // Is any alternative already required? => use that
1862                         for (; ita != end; ++ita) {
1863                                 if (isRequired(*ita))
1864                                         break;
1865                         }
1866                         // Is any alternative available? => use the first one
1867                         // (bug 9498)
1868                         if (ita == end) {
1869                                 for (ita = alternatives.begin(); ita != end; ++ita) {
1870                                         if (isAvailable(*ita)) {
1871                                                 require(*ita);
1872                                                 break;
1873                                         }
1874                                 }
1875                         }
1876                         // This will not work, but not requiring something
1877                         // would be more confusing
1878                         if (ita == end)
1879                                 require(alternatives.front());
1880                         features_.erase(it);
1881                         it = features_.begin();
1882                 } else
1883                         ++it;
1884         }
1885 }
1886
1887
1888 void LaTeXFeatures::expandMultiples()
1889 {
1890         for (Features::iterator it = features_.begin(); it != features_.end();) {
1891                 if (contains(*it, ',')) {
1892                         vector<string> const multiples = getVectorFromString(*it, ",");
1893                         vector<string>::const_iterator const end = multiples.end();
1894                         vector<string>::const_iterator itm = multiples.begin();
1895                         // Do nothing if any multiple is already required
1896                         for (; itm != end; ++itm) {
1897                                 if (!isRequired(*itm))
1898                                         require(*itm);
1899                         }
1900                         features_.erase(it);
1901                         it = features_.begin();
1902                 } else
1903                         ++it;
1904         }
1905 }
1906
1907
1908 } // namespace lyx