]> git.lyx.org Git - features.git/blob - src/LaTeXFeatures.cpp
Basic UI for math (TeX) fonts
[features.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         "\\newcommand{\\lyxadded}[3]{\\changestart#3\\changeend}\n"
188         "\\newcommand{\\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         "\\newcommand{\\lyxadded}[3]{{\\color{lyxadded}{}#3}}\n"
194         "\\newcommand{\\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         "\\newcommand{\\lyxadded}[3]{{\\texorpdfstring{\\color{lyxadded}{}}{}#3}}\n"
199         "\\newcommand{\\lyxdeleted}[3]{{\\texorpdfstring{\\color{lyxdeleted}\\sout{#3}}{}}}\n");
200
201 static docstring const changetracking_none_def = from_ascii(
202         "\\newcommand{\\lyxadded}[3]{#3}\n"
203         "\\newcommand{\\lyxdeleted}[3]{}\n");
204
205 static docstring const textgreek_def = from_ascii(
206         "\\DeclareRobustCommand{\\greektext}{%\n"
207         "  \\fontencoding{LGR}\\selectfont\\def\\encodingdefault{LGR}}\n"
208         "\\DeclareRobustCommand{\\textgreek}[1]{\\leavevmode{\\greektext #1}}\n"
209         "\\DeclareFontEncoding{LGR}{}{}\n"
210         "\\DeclareTextSymbol{\\~}{LGR}{126}");
211
212 static docstring const textcyr_def = from_ascii(
213         "\\DeclareRobustCommand{\\cyrtext}{%\n"
214         "  \\fontencoding{T2A}\\selectfont\\def\\encodingdefault{T2A}}\n"
215         "\\DeclareRobustCommand{\\textcyr}[1]{\\leavevmode{\\cyrtext #1}}\n"
216         "\\AtBeginDocument{\\DeclareFontEncoding{T2A}{}{}}\n");
217
218 static docstring const lyxmathsym_def = from_ascii(
219         "\\newcommand{\\lyxmathsym}[1]{\\ifmmode\\begingroup\\def\\b@ld{bold}\n"
220         "  \\text{\\ifx\\math@version\\b@ld\\bfseries\\fi#1}\\endgroup\\else#1\\fi}\n");
221
222 static docstring const papersizedvi_def = from_ascii(
223         "\\special{papersize=\\the\\paperwidth,\\the\\paperheight}\n");
224
225 static docstring const papersizepdf_def = from_ascii(
226         "\\pdfpageheight\\paperheight\n"
227         "\\pdfpagewidth\\paperwidth\n");
228
229 static docstring const cedilla_def = from_ascii(
230         "\\newcommand{\\docedilla}[2]{\\underaccent{#1\\mathchar'30}{#2}}\n"
231         "\\newcommand{\\cedilla}[1]{\\mathpalette\\docedilla{#1}}\n");
232
233 static docstring const subring_def = from_ascii(
234         "\\newcommand{\\dosubring}[2]{\\underaccent{#1\\mathchar'27}{#2}}\n"
235         "\\newcommand{\\subring}[1]{\\mathpalette\\dosubring{#1}}\n");
236
237 static docstring const subdot_def = from_ascii(
238         "\\newcommand{\\dosubdot}[2]{\\underaccent{#1.}{#2}}\n"
239         "\\newcommand{\\subdot}[1]{\\mathpalette\\dosubdot{#1}}\n");
240
241 static docstring const subhat_def = from_ascii(
242         "\\newcommand{\\dosubhat}[2]{\\underaccent{#1\\mathchar'136}{#2}}\n"
243         "\\newcommand{\\subhat}[1]{\\mathpalette\\dosubhat{#1}}\n");
244
245 static docstring const subtilde_def = from_ascii(
246         "\\newcommand{\\dosubtilde}[2]{\\underaccent{#1\\mathchar'176}{#2}}\n"
247         "\\newcommand{\\subtilde}[1]{\\mathpalette\\dosubtilde{#1}}\n");
248
249 static docstring const dacute_def = from_ascii(
250         "\\DeclareMathAccent{\\dacute}{\\mathalpha}{operators}{'175}\n");
251
252 static docstring const tipasymb_def = from_ascii(
253         "\\DeclareFontEncoding{T3}{}{}\n"
254         "\\DeclareSymbolFont{tipasymb}{T3}{cmr}{m}{n}\n");
255
256 static docstring const dgrave_def = from_ascii(
257         "\\DeclareMathAccent{\\dgrave}{\\mathord}{tipasymb}{'15}\n");
258
259 static docstring const rcap_def = from_ascii(
260         "\\DeclareMathAccent{\\rcap}{\\mathord}{tipasymb}{'20}\n");
261
262 static docstring const ogonek_def = from_ascii(
263         "\\newcommand{\\doogonek}[2]{\\setbox0=\\hbox{$#1#2$}\\underaccent{#1\\mkern-6mu\n"
264         "  \\ifx#2O\\hskip0.5\\wd0\\else\\ifx#2U\\hskip0.5\\wd0\\else\\hskip\\wd0\\fi\\fi\n"
265         "  \\ifx#2o\\mkern-2mu\\else\\ifx#2e\\mkern-1mu\\fi\\fi\n"
266         "  \\mathchar\"0\\hexnumber@\\symtipasymb0C}{#2}}\n"
267         "\\newcommand{\\ogonek}[1]{\\mathpalette\\doogonek{#1}}\n");
268
269 static docstring const lyxref_def = from_ascii(
270                 "\\RS@ifundefined{subref}\n"
271                 "  {\\def\\RSsubtxt{section~}\\newref{sub}{name = \\RSsubtxt}}\n"
272                 "  {}\n"
273                 "\\RS@ifundefined{thmref}\n"
274                 "  {\\def\\RSthmtxt{theorem~}\\newref{thm}{name = \\RSthmtxt}}\n"
275                 "  {}\n"
276                 "\\RS@ifundefined{lemref}\n"
277                 "  {\\def\\RSlemtxt{lemma~}\\newref{lem}{name = \\RSlemtxt}}\n" 
278                 "  {}\n");
279
280
281 /////////////////////////////////////////////////////////////////////
282 //
283 // LaTeXFeatures
284 //
285 /////////////////////////////////////////////////////////////////////
286
287
288 LaTeXFeatures::LaTeXFeatures(Buffer const & b, BufferParams const & p,
289                              OutputParams const & r)
290         : buffer_(&b), params_(p), runparams_(r), in_float_(false)
291 {}
292
293
294 LaTeXFeatures::LangPackage LaTeXFeatures::langPackage(bool englishbabel) const
295 {
296         string const local_lp = bufferParams().lang_package;
297
298         // Locally, custom is just stored as a string
299         // in bufferParams().lang_package.
300         if (local_lp != "auto"
301             && local_lp != "babel"
302             && local_lp != "default"
303             && local_lp != "none")
304                  return LANG_PACK_CUSTOM;
305
306         if (local_lp == "none")
307                 return LANG_PACK_NONE;
308
309         /* If "auto" is selected, we load polyglossia if required,
310          * else we select babel.
311          * If babel is selected (either directly or via the "auto"
312          * mechanism), we really do only require it if we have
313          * a language that needs it.
314          * English alone normally does not require babel (since it is
315          * the default language of LaTeX). However, in some cases we
316          * need to surpass this exception (see Font::validate).
317          */
318         bool const polyglossia_required =
319                 isRequired("polyglossia")
320                 && isAvailable("polyglossia")
321                 && !isProvided("babel")
322                 && this->hasOnlyPolyglossiaLanguages();
323         bool const babel_required = 
324                 ((englishbabel || bufferParams().language->lang() != "english")
325                  && !bufferParams().language->babel().empty())
326                 || !this->getBabelLanguages().empty();
327
328         if (local_lp == "auto") {
329                 // polyglossia requirement has priority over babel
330                 if (polyglossia_required)
331                         return LANG_PACK_POLYGLOSSIA;
332                 else if (babel_required)
333                         return LANG_PACK_BABEL;
334         }
335
336         if (local_lp == "babel") {
337                 if (babel_required)
338                         return LANG_PACK_BABEL;
339         }
340
341         if (local_lp == "default") {
342                 switch (lyxrc.language_package_selection) {
343                 case LyXRC::LP_AUTO:
344                         // polyglossia requirement has priority over babel
345                         if (polyglossia_required)
346                                 return LANG_PACK_POLYGLOSSIA;
347                         else if (babel_required)
348                                 return LANG_PACK_BABEL;
349                         break;
350                 case LyXRC::LP_BABEL:
351                         if (babel_required)
352                                 return LANG_PACK_BABEL;
353                         break;
354                 case LyXRC::LP_CUSTOM:
355                         return LANG_PACK_CUSTOM;
356                 case LyXRC::LP_NONE:
357                         return LANG_PACK_NONE;
358                 }
359         }
360
361         return LANG_PACK_NONE;
362 }
363
364
365 void LaTeXFeatures::require(string const & name)
366 {
367         features_.insert(name);
368 }
369
370
371 void LaTeXFeatures::require(set<string> const & names)
372 {
373         features_.insert(names.begin(), names.end());
374 }
375
376
377 void LaTeXFeatures::useLayout(docstring const & layoutname)
378 {
379         // Some code to avoid loops in dependency definition
380         static int level = 0;
381         const int maxlevel = 30;
382         if (level > maxlevel) {
383                 lyxerr << "LaTeXFeatures::useLayout: maximum level of "
384                        << "recursion attained by layout "
385                        << to_utf8(layoutname) << endl;
386                 return;
387         }
388
389         DocumentClass const & tclass = params_.documentClass();
390         if (tclass.hasLayout(layoutname)) {
391                 // Is this layout already in usedLayouts?
392                 if (find(usedLayouts_.begin(), usedLayouts_.end(), layoutname)
393                     != usedLayouts_.end())
394                         return;
395
396                 Layout const & layout = tclass[layoutname];
397                 require(layout.requires());
398
399                 if (!layout.depends_on().empty()) {
400                         ++level;
401                         useLayout(layout.depends_on());
402                         --level;
403                 }
404                 usedLayouts_.push_back(layoutname);
405         } else {
406                 lyxerr << "LaTeXFeatures::useLayout: layout `"
407                        << to_utf8(layoutname) << "' does not exist in this class"
408                        << endl;
409         }
410
411         --level;
412 }
413
414
415 void LaTeXFeatures::useInsetLayout(InsetLayout const & lay)
416 {
417         docstring const & lname = lay.name();
418         DocumentClass const & tclass = params_.documentClass();
419
420         // this is a default inset layout, nothing useful here
421         if (!tclass.hasInsetLayout(lname))
422                 return;
423         // Is this layout already in usedInsetLayouts?
424         if (find(usedInsetLayouts_.begin(), usedInsetLayouts_.end(), lname)
425                         != usedInsetLayouts_.end())
426                 return;
427
428         require(lay.requires());
429         usedInsetLayouts_.push_back(lname);
430 }
431
432
433 bool LaTeXFeatures::isRequired(string const & name) const
434 {
435         return features_.find(name) != features_.end();
436 }
437
438
439 bool LaTeXFeatures::isProvided(string const & name) const
440 {
441         bool const ot1 = (params_.font_encoding() == "default"
442                 || params_.font_encoding() == "OT1");
443         bool const complete = (params_.fonts_sans == "default")
444                 && (params_.fonts_typewriter == "default");
445         bool const nomath = (params_.fonts_math == "default");
446         return params_.documentClass().provides(name)
447                 || theLaTeXFonts().getLaTeXFont(
448                         from_ascii(params_.fonts_roman)).provides(name, ot1,
449                                                                   complete,
450                                                                   nomath)
451                 || theLaTeXFonts().getLaTeXFont(
452                         from_ascii(params_.fonts_sans)).provides(name, ot1,
453                                                                  complete,
454                                                                  nomath)
455                 || theLaTeXFonts().getLaTeXFont(
456                         from_ascii(params_.fonts_typewriter)).provides(name, ot1,
457                                                                        complete,
458                                                                        nomath);
459 }
460
461 bool LaTeXFeatures::mustProvide(string const & name) const
462 {
463         return isRequired(name) && !isProvided(name);
464 }
465
466
467 bool LaTeXFeatures::isAvailable(string const & name)
468 {
469         string::size_type const i = name.find("->");
470         if (i != string::npos) {
471                 string const from = name.substr(0,i);
472                 string const to = name.substr(i+2);
473                 //LYXERR0("from=[" << from << "] to=[" << to << "]");
474                 return theConverters().isReachable(from, to);
475         }
476         return LaTeXPackages::isAvailable(name);
477 }
478
479
480 void LaTeXFeatures::addPreambleSnippet(string const & preamble)
481 {
482         SnippetList::const_iterator begin = preamble_snippets_.begin();
483         SnippetList::const_iterator end   = preamble_snippets_.end();
484         if (find(begin, end, preamble) == end)
485                 preamble_snippets_.push_back(preamble);
486 }
487
488
489 void LaTeXFeatures::addCSSSnippet(std::string const & snippet)
490 {
491         SnippetList::const_iterator begin = css_snippets_.begin();
492         SnippetList::const_iterator end   = css_snippets_.end();
493         if (find(begin, end, snippet) == end)
494                 css_snippets_.push_back(snippet);
495 }
496
497
498 void LaTeXFeatures::useFloat(string const & name, bool subfloat)
499 {
500         if (!usedFloats_[name])
501                 usedFloats_[name] = subfloat;
502         if (subfloat)
503                 require("subfig");
504         // We only need float.sty if we use non builtin floats, or if we
505         // use the "H" modifier. This includes modified table and
506         // figure floats. (Lgb)
507         Floating const & fl = params_.documentClass().floats().getType(name);
508         if (!fl.floattype().empty() && fl.usesFloatPkg()) {
509                 require("float");
510         }
511 }
512
513
514 void LaTeXFeatures::useLanguage(Language const * lang)
515 {
516         if (!lang->babel().empty() || !lang->polyglossia().empty())
517                 UsedLanguages_.insert(lang);
518         if (!lang->requires().empty())
519                 require(lang->requires());
520         // CJK languages do not have a babel name.
521         // They use the CJK package
522         if (lang->encoding()->package() == Encoding::CJK)
523                 require("CJK");
524         // japanese package is special
525         if (lang->encoding()->package() == Encoding::japanese)
526                 require("japanese");
527 }
528
529
530 void LaTeXFeatures::includeFile(docstring const & key, string const & name)
531 {
532         IncludedFiles_[key] = name;
533 }
534
535
536 bool LaTeXFeatures::hasLanguages() const
537 {
538         return !UsedLanguages_.empty();
539 }
540
541
542 bool LaTeXFeatures::hasOnlyPolyglossiaLanguages() const
543 {
544         LanguageList::const_iterator const begin = UsedLanguages_.begin();
545         for (LanguageList::const_iterator cit = begin;
546              cit != UsedLanguages_.end();
547              ++cit) {
548                 if ((*cit)->polyglossia().empty())
549                         return false;
550         }
551         return true;
552 }
553
554
555 bool LaTeXFeatures::hasPolyglossiaExclusiveLanguages() const
556 {
557         LanguageList::const_iterator const begin = UsedLanguages_.begin();
558         for (LanguageList::const_iterator cit = begin;
559              cit != UsedLanguages_.end();
560              ++cit) {
561                 if ((*cit)->babel().empty() && !(*cit)->polyglossia().empty() && (*cit)->requires().empty())
562                         return true;
563         }
564         return false;
565 }
566
567
568 string LaTeXFeatures::getBabelLanguages() const
569 {
570         ostringstream languages;
571
572         bool first = true;
573         LanguageList::const_iterator const begin = UsedLanguages_.begin();
574         for (LanguageList::const_iterator cit = begin;
575              cit != UsedLanguages_.end();
576              ++cit) {
577                 if ((*cit)->babel().empty())
578                         continue;
579                 if (!first)
580                         languages << ',';
581                 else
582                         first = false;
583                 languages << (*cit)->babel();
584         }
585         return languages.str();
586 }
587
588
589 std::map<std::string, std::string> LaTeXFeatures::getPolyglossiaLanguages() const
590 {
591         std::map<std::string, std::string> languages;
592
593         LanguageList::const_iterator const begin = UsedLanguages_.begin();
594         for (LanguageList::const_iterator cit = begin;
595              cit != UsedLanguages_.end();
596              ++cit) {
597                 languages[(*cit)->polyglossia()] = (*cit)->polyglossiaOpts();
598         }
599         return languages;
600 }
601
602
603 set<string> LaTeXFeatures::getEncodingSet(string const & doc_encoding) const
604 {
605         // This does only find encodings of languages supported by babel, but
606         // that does not matter since we don't have a language with an
607         // encoding supported by inputenc but without babel support.
608         set<string> encodings;
609         LanguageList::const_iterator it  = UsedLanguages_.begin();
610         LanguageList::const_iterator end = UsedLanguages_.end();
611         for (; it != end; ++it)
612                 if ((*it)->encoding()->latexName() != doc_encoding &&
613                     ((*it)->encoding()->package() == Encoding::inputenc
614                      || (*it)->encoding()->package() == Encoding::japanese))
615                         encodings.insert((*it)->encoding()->latexName());
616         return encodings;
617 }
618
619 namespace {
620
621 char const * simplefeatures[] = {
622 // note that the package order here will be the same in the LaTeX-output
623         "array",
624         "verbatim",
625         "longtable",
626         "rotating",
627         "latexsym",
628         "pifont",
629         // subfig is handled in BufferParams.cpp
630         "varioref",
631         "prettyref",
632         "refstyle",
633         /*For a successful cooperation of the `wrapfig' package with the
634           `float' package you should load the `wrapfig' package *after*
635           the `float' package. See the caption package documentation
636           for explanation.*/
637         "float",
638         "rotfloat",
639         "wrapfig",
640         "booktabs",
641         "dvipost",
642         "fancybox",
643         "calc",
644         "units",
645         "tipa",
646         "tipx",
647         "tone",
648         "framed",
649         "soul",
650         "textcomp",
651         "pmboxdraw",
652         "bbding",
653         "ifsym",
654         "marvosym",
655         "txfonts",
656         "pxfonts",
657         "mathdesign",
658         "mathrsfs",
659         "mathabx",
660         "mathtools",
661         "cancel",
662         "ascii",
663         "url",
664         "covington",
665         "csquotes",
666         "enumitem",
667         "endnotes",
668         "hhline",
669         "ifthen",
670         // listings is handled in BufferParams.cpp
671         "bm",
672         "pdfpages",
673         "amscd",
674         "slashed",
675         "multirow",
676         "tfrupee"
677 };
678
679 int const nb_simplefeatures = sizeof(simplefeatures) / sizeof(char const *);
680
681 }
682
683
684 string const LaTeXFeatures::getColorOptions() const
685 {
686         ostringstream colors;
687
688         // Handling the color packages separately is needed to be able to load them
689         // before babel when hyperref is loaded with the colorlinks option
690         // for more info see Bufferparams.cpp
691
692         // [x]color.sty
693         if (mustProvide("color") || mustProvide("xcolor")) {
694                 string const package =
695                         (mustProvide("xcolor") ? "xcolor" : "color");
696                 if (params_.graphics_driver == "default"
697                         || params_.graphics_driver == "none")
698                         colors << "\\usepackage{" << package << "}\n";
699                 else
700                         colors << "\\usepackage["
701                                  << params_.graphics_driver
702                                  << "]{" << package << "}\n";
703         }
704
705         // pdfcolmk must be loaded after color
706         if (mustProvide("pdfcolmk"))
707                 colors << "\\usepackage{pdfcolmk}\n";
708
709         // the following 3 color commands must be set after color
710         // is loaded and before pdfpages, therefore add the command
711         // here define the set color
712         if (mustProvide("pagecolor")) {
713                 colors << "\\definecolor{page_backgroundcolor}{rgb}{";
714                 colors << outputLaTeXColor(params_.backgroundcolor) << "}\n";
715                 // set the page color
716                 colors << "\\pagecolor{page_backgroundcolor}\n";
717         }
718
719         if (mustProvide("fontcolor")) {
720                 colors << "\\definecolor{document_fontcolor}{rgb}{";
721                 colors << outputLaTeXColor(params_.fontcolor) << "}\n";
722                 // set the color
723                 colors << "\\color{document_fontcolor}\n";
724         }
725
726         if (mustProvide("lyxgreyedout")) {
727                 colors << "\\definecolor{note_fontcolor}{rgb}{";
728                 colors << outputLaTeXColor(params_.notefontcolor) << "}\n";
729                 // the color will be set together with the definition of
730                 // the lyxgreyedout environment (see lyxgreyedout_def)
731         }
732
733         // color for shaded boxes
734         if (isRequired("framed") && mustProvide("color")) {
735                 colors << "\\definecolor{shadecolor}{rgb}{";
736                 colors << outputLaTeXColor(params_.boxbgcolor) << "}\n";
737                 // this color is automatically used by the LaTeX-package "framed"
738         }
739
740         return colors.str();
741 }
742
743
744 string const LaTeXFeatures::getPackages() const
745 {
746         ostringstream packages;
747
748         // FIXME: currently, we can only load packages and macros known
749         // to LyX.
750         // However, with the Require tag of layouts/custom insets,
751         // also unknown packages can be requested. They are silently
752         // swallowed now. We should change this eventually.
753
754         //
755         //  These are all the 'simple' includes.  i.e
756         //  packages which we just \usepackage{package}
757         //
758         for (int i = 0; i < nb_simplefeatures; ++i) {
759                 if (mustProvide(simplefeatures[i]))
760                         packages << "\\usepackage{"
761                                  << simplefeatures[i] << "}\n";
762         }
763
764         //
765         // The rest of these packages are somewhat more complicated
766         // than those above.
767         //
768
769         // if fontspec is used, AMS packages have to be loaded before
770         // fontspec (in BufferParams)
771         string const amsPackages = loadAMSPackages();
772         if (!params_.useNonTeXFonts && !amsPackages.empty())
773                 packages << amsPackages;
774
775         // fixltx2e must be loaded after amsthm, since amsthm produces an error with
776         // the redefined \[ command (bug 7233). Load it as early as possible, since
777         // other packages might profit from it.
778         if (mustProvide("fixltx2e"))
779                 packages << "\\usepackage{fixltx2e}\n";
780
781         // wasysym is a simple feature, but it must be after amsmath if both
782         // are used
783         // wasysym redefines some integrals (e.g. iint) from amsmath. That
784         // leads to inconsistent integrals. We only load this package if
785         // the document does not contain integrals (then isRequired("esint")
786         // is false) or if esint is used, since esint redefines all relevant
787         // integral symbols from wasysym and amsmath.
788         // See http://www.lyx.org/trac/ticket/1942
789         if (mustProvide("wasysym") &&
790             params_.use_package("wasysym") != BufferParams::package_off &&
791             (params_.use_package("esint") != BufferParams::package_off || !isRequired("esint")))
792                 packages << "\\usepackage{wasysym}\n";
793
794         // accents must be loaded after amsmath
795         if (mustProvide("accents") &&
796             params_.use_package("accents") != BufferParams::package_off)
797                 packages << "\\usepackage{accents}\n";
798
799         // mathdots must be loaded after amsmath
800         if (mustProvide("mathdots") &&
801                 params_.use_package("mathdots") != BufferParams::package_off)
802                 packages << "\\usepackage{mathdots}\n";
803
804         // yhmath must be loaded after amsmath
805         if (mustProvide("yhmath") &&
806             params_.use_package("yhmath") != BufferParams::package_off)
807                 packages << "\\usepackage{yhmath}\n";
808
809         if (mustProvide("undertilde") &&
810                 params_.use_package("undertilde") != BufferParams::package_off)
811                 packages << "\\usepackage{undertilde}\n";
812
813         // [x]color and pdfcolmk are handled in getColorOptions() above
814
815         // makeidx.sty
816         if (isRequired("makeidx") || isRequired("splitidx")) {
817                 if (!isProvided("makeidx") && !isRequired("splitidx"))
818                         packages << "\\usepackage{makeidx}\n";
819                 if (mustProvide("splitidx"))
820                         packages << "\\usepackage{splitidx}\n";
821                 packages << "\\makeindex\n";
822         }
823
824         // graphicx.sty
825         if (mustProvide("graphicx") && params_.graphics_driver != "none") {
826                 if (params_.graphics_driver == "default")
827                         packages << "\\usepackage{graphicx}\n";
828                 else
829                         packages << "\\usepackage["
830                                  << params_.graphics_driver
831                                  << "]{graphicx}\n";
832         }
833
834         // lyxskak.sty --- newer chess support based on skak.sty
835         if (mustProvide("chess"))
836                 packages << "\\usepackage[ps,mover]{lyxskak}\n";
837
838         // setspace.sty
839         if (mustProvide("setspace") && !isProvided("SetSpace"))
840                 packages << "\\usepackage{setspace}\n";
841
842         // esint must be after amsmath and wasysym, since it will redeclare
843         // inconsistent integral symbols
844         if (mustProvide("esint") &&
845             params_.use_package("esint") != BufferParams::package_off)
846                 packages << "\\usepackage{esint}\n";
847
848         // natbib.sty
849         // Some classes load natbib themselves, but still allow (or even require)
850         // plain numeric citations (ReVTeX is such a case, see bug 5182).
851         // This special case is indicated by the "natbib-internal" key.
852         if (mustProvide("natbib") && !isProvided("natbib-internal")) {
853                 packages << "\\usepackage[";
854                 if (params_.citeEngineType() == ENGINE_TYPE_NUMERICAL)
855                         packages << "numbers";
856                 else
857                         packages << "authoryear";
858                 packages << "]{natbib}\n";
859         }
860
861         // jurabib -- we need version 0.6 at least.
862         if (mustProvide("jurabib"))
863                 packages << "\\usepackage{jurabib}[2004/01/25]\n";
864
865         // xargs -- we need version 1.09 at least
866         if (mustProvide("xargs"))
867                 packages << "\\usepackage{xargs}[2008/03/08]\n";
868
869         if (mustProvide("xy"))
870                 packages << "\\usepackage[all]{xy}\n";
871
872         if (mustProvide("feyn"))
873                 packages << "\\usepackage{feyn}\n"; //Diagram
874
875         if (mustProvide("ulem"))
876                 packages << "\\PassOptionsToPackage{normalem}{ulem}\n"
877                             "\\usepackage{ulem}\n";
878
879         if (mustProvide("mhchem") &&
880             params_.use_package("mhchem") != BufferParams::package_off)
881                 packages << "\\PassOptionsToPackage{version=3}{mhchem}\n"
882                             "\\usepackage{mhchem}\n";
883
884         if (mustProvide("nomencl")) {
885                 // Make it work with the new and old version of the package,
886                 // but don't use the compatibility option since it is
887                 // incompatible to other packages.
888                 packages << "\\usepackage{nomencl}\n"
889                             "% the following is useful when we have the old nomencl.sty package\n"
890                             "\\providecommand{\\printnomenclature}{\\printglossary}\n"
891                             "\\providecommand{\\makenomenclature}{\\makeglossary}\n"
892                             "\\makenomenclature\n";
893         }
894
895         // fixltx2e provides subscript
896         if (mustProvide("subscript") && !isRequired("fixltx2e"))
897                 packages << "\\usepackage{subscript}\n";
898
899         return packages.str();
900 }
901
902
903 string LaTeXFeatures::getPreambleSnippets() const
904 {
905         ostringstream snip;
906         SnippetList::const_iterator pit  = preamble_snippets_.begin();
907         SnippetList::const_iterator pend = preamble_snippets_.end();
908         for (; pit != pend; ++pit)
909                 snip << *pit << '\n';
910         return snip.str();
911 }
912
913
914 std::string LaTeXFeatures::getCSSSnippets() const
915 {
916         ostringstream snip;
917         SnippetList::const_iterator pit  = css_snippets_.begin();
918         SnippetList::const_iterator pend = css_snippets_.end();
919         for (; pit != pend; ++pit)
920                 snip << *pit << '\n';
921         return snip.str();
922 }
923
924
925 docstring const LaTeXFeatures::getMacros() const
926 {
927         odocstringstream macros;
928
929         if (!preamble_snippets_.empty()) {
930                 macros << '\n';
931                 macros << from_utf8(getPreambleSnippets());
932         }
933
934         if (mustProvide("papersize")) {
935                 if (runparams_.flavor == OutputParams::LATEX)
936                         macros << papersizedvi_def << '\n';
937                 else
938                         macros << papersizepdf_def << '\n';
939         }
940
941         if (mustProvide("LyX")) {
942                 if (isRequired("hyperref"))
943                         macros << lyx_hyperref_def << '\n';
944                 else
945                         macros << lyx_def << '\n';
946         }
947
948         if (mustProvide("noun"))
949                 macros << noun_def << '\n';
950
951         if (mustProvide("lyxarrow"))
952                 macros << lyxarrow_def << '\n';
953
954         if (!usePolyglossia() && mustProvide("textgreek")) {
955                 // Avoid a LaTeX error if times fonts are used and the grtimes
956                 // package is installed but actual fonts are not (bug 6469).
957                 if (params_.fonts_roman == "times")
958                         macros << subst(textgreek_def,
959                                         from_ascii("\\greektext #1"),
960                                         from_ascii("%\n  \\IfFileExists"
961                                                    "{grtm10.tfm}{}{\\fontfamily"
962                                                    "{cmr}}\\greektext #1"))
963                                << '\n';
964                 else
965                         macros << textgreek_def << '\n';
966         }
967
968         if (!usePolyglossia() && mustProvide("textcyr"))
969                 macros << textcyr_def << '\n';
970
971         if (mustProvide("lyxmathsym"))
972                 macros << lyxmathsym_def << '\n';
973
974         if (mustProvide("cedilla"))
975                 macros << cedilla_def << '\n';
976
977         if (mustProvide("subring"))
978                 macros << subring_def << '\n';
979
980         if (mustProvide("subdot"))
981                 macros << subdot_def << '\n';
982
983         if (mustProvide("subhat"))
984                 macros << subhat_def << '\n';
985
986         if (mustProvide("subtilde"))
987                 macros << subtilde_def << '\n';
988
989         if (mustProvide("dacute"))
990                 macros << dacute_def << '\n';
991
992         if (mustProvide("tipasymb"))
993                 macros << tipasymb_def << '\n';
994
995         if (mustProvide("dgrave"))
996                 macros << dgrave_def << '\n';
997
998         if (mustProvide("rcap"))
999                 macros << rcap_def << '\n';
1000
1001         if (mustProvide("ogonek"))
1002                 macros << ogonek_def << '\n';
1003
1004         // quotes.
1005         if (mustProvide("quotesinglbase"))
1006                 macros << quotesinglbase_def << '\n';
1007         if (mustProvide("quotedblbase"))
1008                 macros << quotedblbase_def << '\n';
1009         if (mustProvide("guilsinglleft"))
1010                 macros << guilsinglleft_def << '\n';
1011         if (mustProvide("guilsinglright"))
1012                 macros << guilsinglright_def << '\n';
1013         if (mustProvide("guillemotleft"))
1014                 macros << guillemotleft_def << '\n';
1015         if (mustProvide("guillemotright"))
1016                 macros << guillemotright_def << '\n';
1017
1018         // Math mode
1019         if (mustProvide("binom") && !isRequired("amsmath"))
1020                 macros << binom_def << '\n';
1021         if (mustProvide("mathcircumflex"))
1022                 macros << mathcircumflex_def << '\n';
1023
1024         // other
1025         if (mustProvide("ParagraphLeftIndent"))
1026                 macros << paragraphleftindent_def;
1027         if (mustProvide("NeedLyXFootnoteCode"))
1028                 macros << floatingfootnote_def;
1029
1030         // some problems with tex->html converters
1031         if (mustProvide("NeedTabularnewline"))
1032                 macros << tabularnewline_def;
1033
1034         // greyed-out environment (note inset)
1035         // the color is specified in the routine
1036         // getColorOptions() to avoid LaTeX-package clashes
1037         if (mustProvide("lyxgreyedout"))
1038                 macros << lyxgreyedout_def;
1039
1040         if (mustProvide("lyxdot"))
1041                 macros << lyxdot_def << '\n';
1042
1043         // floats
1044         getFloatDefinitions(macros);
1045
1046         if (mustProvide("refstyle"))
1047                 macros << lyxref_def << '\n';
1048
1049         // change tracking
1050         if (mustProvide("ct-dvipost"))
1051                 macros << changetracking_dvipost_def;
1052
1053         if (mustProvide("ct-xcolor-ulem")) {
1054                 streamsize const prec = macros.precision(2);
1055
1056                 RGBColor cadd = rgbFromHexName(lcolor.getX11Name(Color_addedtext));
1057                 macros << "\\providecolor{lyxadded}{rgb}{"
1058                        << cadd.r / 255.0 << ',' << cadd.g / 255.0 << ',' << cadd.b / 255.0 << "}\n";
1059
1060                 RGBColor cdel = rgbFromHexName(lcolor.getX11Name(Color_deletedtext));
1061                 macros << "\\providecolor{lyxdeleted}{rgb}{"
1062                        << cdel.r / 255.0 << ',' << cdel.g / 255.0 << ',' << cdel.b / 255.0 << "}\n";
1063
1064                 macros.precision(prec);
1065
1066                 if (isRequired("hyperref"))
1067                         macros << changetracking_xcolor_ulem_hyperref_def;
1068                 else
1069                         macros << changetracking_xcolor_ulem_def;
1070         }
1071
1072         if (mustProvide("ct-none"))
1073                 macros << changetracking_none_def;
1074
1075         return macros.str();
1076 }
1077
1078
1079 string const LaTeXFeatures::getBabelPresettings() const
1080 {
1081         ostringstream tmp;
1082
1083         LanguageList::const_iterator it  = UsedLanguages_.begin();
1084         LanguageList::const_iterator end = UsedLanguages_.end();
1085         for (; it != end; ++it)
1086                 if (!(*it)->babel_presettings().empty())
1087                         tmp << (*it)->babel_presettings() << '\n';
1088         if (!params_.language->babel_presettings().empty())
1089                 tmp << params_.language->babel_presettings() << '\n';
1090
1091         if (!contains(tmp.str(), '@'))
1092                 return tmp.str();
1093
1094         return "\\makeatletter\n" + tmp.str() + "\\makeatother\n";
1095 }
1096
1097
1098 string const LaTeXFeatures::getBabelPostsettings() const
1099 {
1100         ostringstream tmp;
1101
1102         LanguageList::const_iterator it  = UsedLanguages_.begin();
1103         LanguageList::const_iterator end = UsedLanguages_.end();
1104         for (; it != end; ++it)
1105                 if (!(*it)->babel_postsettings().empty())
1106                         tmp << (*it)->babel_postsettings() << '\n';
1107         if (!params_.language->babel_postsettings().empty())
1108                 tmp << params_.language->babel_postsettings() << '\n';
1109
1110         if (!contains(tmp.str(), '@'))
1111                 return tmp.str();
1112
1113         return "\\makeatletter\n" + tmp.str() + "\\makeatother\n";
1114 }
1115
1116
1117 bool LaTeXFeatures::needBabelLangOptions() const
1118 {
1119         if (!lyxrc.language_global_options || params_.language->asBabelOptions())
1120                 return true;
1121
1122         LanguageList::const_iterator it  = UsedLanguages_.begin();
1123         LanguageList::const_iterator end = UsedLanguages_.end();
1124         for (; it != end; ++it)
1125                 if ((*it)->asBabelOptions())
1126                         return true;
1127
1128         return false;
1129 }
1130
1131
1132 string const LaTeXFeatures::loadAMSPackages() const
1133 {
1134         ostringstream tmp;
1135         if (mustProvide("amsthm"))
1136                 tmp << "\\usepackage{amsthm}\n";
1137
1138         if (mustProvide("amsmath")
1139             && params_.use_package("amsmath") != BufferParams::package_off) {
1140                 tmp << "\\usepackage{amsmath}\n";
1141         } else {
1142                 // amsbsy and amstext are already provided by amsmath
1143                 if (mustProvide("amsbsy"))
1144                         tmp << "\\usepackage{amsbsy}\n";
1145                 if (mustProvide("amstext"))
1146                         tmp << "\\usepackage{amstext}\n";
1147         }
1148
1149         if (mustProvide("amssymb")
1150             && params_.use_package("amssymb") != BufferParams::package_off)
1151                 tmp << "\\usepackage{amssymb}\n";
1152
1153         return tmp.str();
1154 }
1155
1156
1157 docstring const LaTeXFeatures::getTClassPreamble() const
1158 {
1159         // the text class specific preamble
1160         DocumentClass const & tclass = params_.documentClass();
1161         odocstringstream tcpreamble;
1162
1163         tcpreamble << tclass.preamble();
1164
1165         list<docstring>::const_iterator cit = usedLayouts_.begin();
1166         list<docstring>::const_iterator end = usedLayouts_.end();
1167         for (; cit != end; ++cit)
1168                 tcpreamble << tclass[*cit].preamble();
1169
1170         cit = usedInsetLayouts_.begin();
1171         end = usedInsetLayouts_.end();
1172         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1173         for (; cit != end; ++cit) {
1174                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1175                 if (it == ils.end())
1176                         continue;
1177                 tcpreamble << it->second.preamble();
1178         }
1179
1180         return tcpreamble.str();
1181 }
1182
1183
1184 docstring const LaTeXFeatures::getTClassHTMLPreamble() const
1185 {
1186         DocumentClass const & tclass = params_.documentClass();
1187         odocstringstream tcpreamble;
1188
1189         tcpreamble << tclass.htmlpreamble();
1190
1191         list<docstring>::const_iterator cit = usedLayouts_.begin();
1192         list<docstring>::const_iterator end = usedLayouts_.end();
1193         for (; cit != end; ++cit)
1194                 tcpreamble << tclass[*cit].htmlpreamble();
1195
1196         cit = usedInsetLayouts_.begin();
1197         end = usedInsetLayouts_.end();
1198         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1199         for (; cit != end; ++cit) {
1200                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1201                 if (it == ils.end())
1202                         continue;
1203                 tcpreamble << it->second.htmlpreamble();
1204         }
1205
1206         return tcpreamble.str();
1207 }
1208
1209
1210 docstring const LaTeXFeatures::getTClassHTMLStyles() const
1211 {
1212         DocumentClass const & tclass = params_.documentClass();
1213         odocstringstream tcpreamble;
1214
1215         tcpreamble << tclass.htmlstyles();
1216
1217         list<docstring>::const_iterator cit = usedLayouts_.begin();
1218         list<docstring>::const_iterator end = usedLayouts_.end();
1219         for (; cit != end; ++cit)
1220                 tcpreamble << tclass[*cit].htmlstyle();
1221
1222         cit = usedInsetLayouts_.begin();
1223         end = usedInsetLayouts_.end();
1224         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1225         for (; cit != end; ++cit) {
1226                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1227                 if (it == ils.end())
1228                         continue;
1229                 tcpreamble << it->second.htmlstyle();
1230         }
1231
1232         return tcpreamble.str();
1233 }
1234
1235
1236 namespace {
1237 docstring const getFloatI18nPreamble(docstring const & type,
1238                         docstring const & name, Language const * lang,
1239                         Encoding const & enc, bool const polyglossia)
1240 {
1241         // Check whether name can be encoded in the buffer encoding
1242         bool encodable = true;
1243         for (size_t i = 0; i < name.size(); ++i) {
1244                 if (!enc.encodable(name[i])) {
1245                         encodable = false;
1246                         break;
1247                 }
1248         }
1249
1250         docstring const language = polyglossia ? from_ascii(lang->polyglossia())
1251                                                : from_ascii(lang->babel());
1252         docstring const langenc = from_ascii(lang->encoding()->iconvName());
1253         docstring const texenc = from_ascii(lang->encoding()->latexName());
1254         docstring const bufenc = from_ascii(enc.iconvName());
1255         docstring const s1 = docstring(1, 0xF0000);
1256         docstring const s2 = docstring(1, 0xF0001);
1257         docstring const translated = encodable ? name
1258                 : from_ascii("\\inputencoding{") + texenc + from_ascii("}")
1259                         + s1 + langenc + s2 + name + s1 + bufenc + s2;
1260
1261         odocstringstream os;
1262         os << "\\addto\\captions" << language
1263            << "{\\renewcommand{\\" << type << "name}{" << translated << "}}\n";
1264         return os.str();
1265 }
1266
1267
1268 docstring const i18npreamble(docstring const & templ, Language const * lang,
1269                 Encoding const & enc, bool const polyglossia)
1270 {
1271         if (templ.empty())
1272                 return templ;
1273
1274         string preamble = polyglossia ?
1275                 subst(to_utf8(templ), "$$lang", lang->polyglossia()) :
1276                 subst(to_utf8(templ), "$$lang", lang->babel());
1277
1278         string const langenc = lang->encoding()->iconvName();
1279         string const texenc = lang->encoding()->latexName();
1280         string const bufenc = enc.iconvName();
1281         // First and second character of plane 15 (Private Use Area)
1282         string const s1 = "\xf3\xb0\x80\x80"; // U+F0000
1283         string const s2 = "\xf3\xb0\x80\x81"; // U+F0001
1284         // FIXME UNICODE
1285         // lyx::regex is not unicode-safe.
1286         // Should use QRegExp or (boost::u32regex, but that requires ICU)
1287         static regex const reg("_\\(([^\\)]+)\\)");
1288         smatch sub;
1289         while (regex_search(preamble, sub, reg)) {
1290                 string const key = sub.str(1);
1291                 docstring const name = lang->translateLayout(key);
1292                 // Check whether name can be encoded in the buffer encoding
1293                 bool encodable = true;
1294                 for (size_t i = 0; i < name.size(); ++i) {
1295                         if (!enc.encodable(name[i])) {
1296                                 encodable = false;
1297                                 break;
1298                         }
1299                 }
1300                 string const translated = encodable ? to_utf8(name)
1301                         : "\\inputencoding{" + texenc + "}"
1302                         + s1 + langenc + s2 + to_utf8(name)
1303                         + s1 + bufenc + s2;
1304                 preamble = subst(preamble, sub.str(), translated);
1305         }
1306         return from_utf8(preamble);
1307 }
1308
1309 }
1310
1311
1312 docstring const LaTeXFeatures::getTClassI18nPreamble(bool use_babel, bool use_polyglossia) const
1313 {
1314         DocumentClass const & tclass = params_.documentClass();
1315         // collect preamble snippets in a set to prevent multiple identical
1316         // commands (would happen if e.g. both theorem and theorem* are used)
1317         set<docstring> snippets;
1318         typedef LanguageList::const_iterator lang_it;
1319         lang_it const lbeg = UsedLanguages_.begin();
1320         lang_it const lend =  UsedLanguages_.end();
1321         list<docstring>::const_iterator cit = usedLayouts_.begin();
1322         list<docstring>::const_iterator end = usedLayouts_.end();
1323         for (; cit != end; ++cit) {
1324                 // language dependent commands (once per document)
1325                 snippets.insert(i18npreamble(tclass[*cit].langpreamble(),
1326                                                 buffer().language(),
1327                                                 buffer().params().encoding(),
1328                                                 use_polyglossia));
1329                 // commands for language changing (for multilanguage documents)
1330                 if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1331                         snippets.insert(i18npreamble(
1332                                                 tclass[*cit].babelpreamble(),
1333                                                 buffer().language(),
1334                                                 buffer().params().encoding(),
1335                                                 use_polyglossia));
1336                         for (lang_it lit = lbeg; lit != lend; ++lit)
1337                                 snippets.insert(i18npreamble(
1338                                                 tclass[*cit].babelpreamble(),
1339                                                 *lit,
1340                                                 buffer().params().encoding(),
1341                                                 use_polyglossia));
1342                 }
1343         }
1344         if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1345                 FloatList const & floats = params_.documentClass().floats();
1346                 UsedFloats::const_iterator fit = usedFloats_.begin();
1347                 UsedFloats::const_iterator fend = usedFloats_.end();
1348                 for (; fit != fend; ++fit) {
1349                         Floating const & fl = floats.getType(fit->first);
1350                         // we assume builtin floats are translated
1351                         if (fl.isPredefined())
1352                                 continue;
1353                         docstring const type = from_ascii(fl.floattype());
1354                         docstring const flname = from_utf8(fl.name());
1355                         docstring name = buffer().language()->translateLayout(fl.name());
1356                         // only request translation if we have a real translation
1357                         // (that differs from the source)
1358                         if (flname != name)
1359                                 snippets.insert(getFloatI18nPreamble(
1360                                                 type, name, buffer().language(),
1361                                                 buffer().params().encoding(),
1362                                                 use_polyglossia));
1363                         for (lang_it lit = lbeg; lit != lend; ++lit) {
1364                                 string const code = (*lit)->code();
1365                                 name = (*lit)->translateLayout(fl.name());
1366                                 // we assume we have a suitable translation if
1367                                 // either the language is English (we need to
1368                                 // translate into English if English is a secondary
1369                                 // language) or if translateIfPossible returns
1370                                 // something different to the English source.
1371                                 bool const have_translation =
1372                                         (flname != name || contains(code, "en"));
1373                                 if (have_translation)
1374                                         snippets.insert(getFloatI18nPreamble(
1375                                                 type, name, *lit,
1376                                                 buffer().params().encoding(),
1377                                                 use_polyglossia));
1378                         }
1379                 }
1380         }
1381
1382         cit = usedInsetLayouts_.begin();
1383         end = usedInsetLayouts_.end();
1384         TextClass::InsetLayouts const & ils = tclass.insetLayouts();
1385         for (; cit != end; ++cit) {
1386                 TextClass::InsetLayouts::const_iterator it = ils.find(*cit);
1387                 if (it == ils.end())
1388                         continue;
1389                 // language dependent commands (once per document)
1390                 snippets.insert(i18npreamble(it->second.langpreamble(),
1391                                                 buffer().language(),
1392                                                 buffer().params().encoding(),
1393                                                 use_polyglossia));
1394                 // commands for language changing (for multilanguage documents)
1395                 if ((use_babel || use_polyglossia) && !UsedLanguages_.empty()) {
1396                         snippets.insert(i18npreamble(
1397                                                 it->second.babelpreamble(),
1398                                                 buffer().language(),
1399                                                 buffer().params().encoding(),
1400                                                 use_polyglossia));
1401                         for (lang_it lit = lbeg; lit != lend; ++lit)
1402                                 snippets.insert(i18npreamble(
1403                                                 it->second.babelpreamble(),
1404                                                 *lit,
1405                                                 buffer().params().encoding(),
1406                                                 use_polyglossia));
1407                 }
1408         }
1409
1410         odocstringstream tcpreamble;
1411         set<docstring>::const_iterator const send = snippets.end();
1412         set<docstring>::const_iterator it = snippets.begin();
1413         for (; it != send; ++it)
1414                 tcpreamble << *it;
1415         return tcpreamble.str();
1416 }
1417
1418
1419 docstring const LaTeXFeatures::getLyXSGMLEntities() const
1420 {
1421         // Definition of entities used in the document that are LyX related.
1422         odocstringstream entities;
1423
1424         if (mustProvide("lyxarrow")) {
1425                 entities << "<!ENTITY lyxarrow \"-&gt;\">" << '\n';
1426         }
1427
1428         return entities.str();
1429 }
1430
1431
1432 docstring const LaTeXFeatures::getIncludedFiles(string const & fname) const
1433 {
1434         odocstringstream sgmlpreamble;
1435         // FIXME UNICODE
1436         docstring const basename(from_utf8(onlyPath(fname)));
1437
1438         FileMap::const_iterator end = IncludedFiles_.end();
1439         for (FileMap::const_iterator fi = IncludedFiles_.begin();
1440              fi != end; ++fi)
1441                 // FIXME UNICODE
1442                 sgmlpreamble << "\n<!ENTITY " << fi->first
1443                              << (isSGMLFileName(fi->second) ? " SYSTEM \"" : " \"")
1444                              << makeRelPath(from_utf8(fi->second), basename) << "\">";
1445
1446         return sgmlpreamble.str();
1447 }
1448
1449
1450 void LaTeXFeatures::showStruct() const
1451 {
1452         lyxerr << "LyX needs the following commands when LaTeXing:"
1453                << "\n***** Packages:" << getPackages()
1454                << "\n***** Macros:" << to_utf8(getMacros())
1455                << "\n***** Textclass stuff:" << to_utf8(getTClassPreamble())
1456                << "\n***** done." << endl;
1457 }
1458
1459
1460 Buffer const & LaTeXFeatures::buffer() const
1461 {
1462         return *buffer_;
1463 }
1464
1465
1466 void LaTeXFeatures::setBuffer(Buffer const & buffer)
1467 {
1468         buffer_ = &buffer;
1469 }
1470
1471
1472 BufferParams const & LaTeXFeatures::bufferParams() const
1473 {
1474         return params_;
1475 }
1476
1477
1478 void LaTeXFeatures::getFloatDefinitions(odocstream & os) const
1479 {
1480         FloatList const & floats = params_.documentClass().floats();
1481
1482         // Here we will output the code to create the needed float styles.
1483         // We will try to do this as minimal as possible.
1484         // \floatstyle{ruled}
1485         // \newfloat{algorithm}{htbp}{loa}
1486         // \providecommand{\algorithmname}{Algorithm}
1487         // \floatname{algorithm}{\protect\algorithmname}
1488         UsedFloats::const_iterator cit = usedFloats_.begin();
1489         UsedFloats::const_iterator end = usedFloats_.end();
1490         for (; cit != end; ++cit) {
1491                 Floating const & fl = floats.getType(cit->first);
1492
1493                 // For builtin floats we do nothing.
1494                 if (fl.isPredefined())
1495                         continue;
1496
1497                 // We have to special case "table" and "figure"
1498                 if (fl.floattype() == "tabular" || fl.floattype() == "figure") {
1499                         // Output code to modify "table" or "figure"
1500                         // but only if builtin == false
1501                         // and that have to be true at this point in the
1502                         // function.
1503                         docstring const type = from_ascii(fl.floattype());
1504                         docstring const placement = from_ascii(fl.placement());
1505                         docstring const style = from_ascii(fl.style());
1506                         if (!style.empty()) {
1507                                 os << "\\floatstyle{" << style << "}\n"
1508                                    << "\\restylefloat{" << type << "}\n";
1509                         }
1510                         if (!placement.empty()) {
1511                                 os << "\\floatplacement{" << type << "}{"
1512                                    << placement << "}\n";
1513                         }
1514                 } else {
1515                         // The other non builtin floats.
1516
1517                         docstring const type = from_ascii(fl.floattype());
1518                         docstring const placement = from_ascii(fl.placement());
1519                         docstring const ext = from_ascii(fl.ext());
1520                         docstring const within = from_ascii(fl.within());
1521                         docstring const style = from_ascii(fl.style());
1522                         docstring const name =
1523                                 buffer().language()->translateLayout(fl.name());
1524                         os << "\\floatstyle{" << style << "}\n"
1525                            << "\\newfloat{" << type << "}{" << placement
1526                            << "}{" << ext << '}';
1527                         if (!within.empty())
1528                                 os << '[' << within << ']';
1529                         os << '\n'
1530                            << "\\providecommand{\\" << type << "name}{"
1531                            << name << "}\n"
1532                            << "\\floatname{" << type << "}{\\protect\\"
1533                            << type << "name}\n";
1534
1535                         // What missing here is to code to minimalize the code
1536                         // output so that the same floatstyle will not be
1537                         // used several times, when the same style is still in
1538                         // effect. (Lgb)
1539                 }
1540                 if (cit->second)
1541                         os << "\n\\newsubfloat{" << from_ascii(fl.floattype()) << "}\n";
1542         }
1543 }
1544
1545
1546 void LaTeXFeatures::resolveAlternatives()
1547 {
1548         for (Features::iterator it = features_.begin(); it != features_.end();) {
1549                 if (contains(*it, '|')) {
1550                         vector<string> const alternatives = getVectorFromString(*it, "|");
1551                         vector<string>::const_iterator const end = alternatives.end();
1552                         vector<string>::const_iterator ita = alternatives.begin();
1553                         for (; ita != end; ++ita) {
1554                                 if (isRequired(*ita))
1555                                         break;
1556                         }
1557                         if (ita == end)
1558                                 require(alternatives.front());
1559                         features_.erase(it);
1560                         it = features_.begin();
1561                 } else
1562                         ++it;
1563         }
1564 }
1565
1566
1567 } // namespace lyx