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