]> git.lyx.org Git - lyx.git/blob - src/BufferParams.cpp
2c96da3c06311e2384fdd9081811f0483bb13a7b
[lyx.git] / src / BufferParams.cpp
1 /**
2  * \file BufferParams.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Martin Vermeer
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "BufferParams.h"
19
20 #include "Author.h"
21 #include "LayoutFile.h"
22 #include "BranchList.h"
23 #include "buffer_funcs.h"
24 #include "Bullet.h"
25 #include "Color.h"
26 #include "ColorSet.h"
27 #include "Converter.h"
28 #include "Encoding.h"
29 #include "HSpace.h"
30 #include "IndicesList.h"
31 #include "Language.h"
32 #include "LaTeXFeatures.h"
33 #include "LaTeXFonts.h"
34 #include "ModuleList.h"
35 #include "Font.h"
36 #include "Lexer.h"
37 #include "LyXRC.h"
38 #include "OutputParams.h"
39 #include "Spacing.h"
40 #include "TexRow.h"
41 #include "VSpace.h"
42 #include "PDFOptions.h"
43
44 #include "frontends/alert.h"
45
46 #include "insets/InsetListingsParams.h"
47
48 #include "support/convert.h"
49 #include "support/debug.h"
50 #include "support/docstream.h"
51 #include "support/FileName.h"
52 #include "support/filetools.h"
53 #include "support/gettext.h"
54 #include "support/Messages.h"
55 #include "support/Translator.h"
56 #include "support/lstrings.h"
57
58 #include <algorithm>
59 #include <sstream>
60
61 using namespace std;
62 using namespace lyx::support;
63
64
65 static char const * const string_paragraph_separation[] = {
66         "indent", "skip", ""
67 };
68
69
70 static char const * const string_quotes_language[] = {
71         "english", "swedish", "german", "polish", "french", "danish", ""
72 };
73
74
75 static char const * const string_papersize[] = {
76         "default", "custom", "letterpaper", "legalpaper", "executivepaper",
77         "a0paper", "a1paper", "a2paper", "a3paper",     "a4paper", "a5paper",
78         "a6paper", "b0paper", "b1paper", "b2paper","b3paper", "b4paper",
79         "b5paper", "b6paper", "c0paper", "c1paper", "c2paper", "c3paper",
80         "c4paper", "c5paper", "c6paper", "b0j", "b1j", "b2j", "b3j", "b4j", "b5j",
81         "b6j", ""
82 };
83
84
85 static char const * const string_orientation[] = {
86         "portrait", "landscape", ""
87 };
88
89
90 static char const * const string_footnotekinds[] = {
91         "footnote", "margin", "fig", "tab", "alg", "wide-fig", "wide-tab", ""
92 };
93
94
95 static char const * const tex_graphics[] = {
96         "default", "dvialw", "dvilaser", "dvipdf", "dvipdfm", "dvipdfmx",
97         "dvips", "dvipsone", "dvitops", "dviwin", "dviwindo", "dvi2ps", "emtex",
98         "ln", "oztex", "pctexhp", "pctexps", "pctexwin", "pctex32", "pdftex",
99         "psprint", "pubps", "tcidvi", "textures", "truetex", "vtex", "xdvi",
100         "xetex", "none", ""
101 };
102
103
104
105 namespace lyx {
106
107 // Local translators
108 namespace {
109
110 // Paragraph separation
111 typedef Translator<string, BufferParams::ParagraphSeparation> ParSepTranslator;
112
113
114 ParSepTranslator const init_parseptranslator()
115 {
116         ParSepTranslator translator
117                 (string_paragraph_separation[0], BufferParams::ParagraphIndentSeparation);
118         translator.addPair(string_paragraph_separation[1], BufferParams::ParagraphSkipSeparation);
119         return translator;
120 }
121
122
123 ParSepTranslator const & parseptranslator()
124 {
125         static ParSepTranslator translator = init_parseptranslator();
126         return translator;
127 }
128
129
130 // Quotes language
131 typedef Translator<string, InsetQuotes::QuoteLanguage> QuotesLangTranslator;
132
133
134 QuotesLangTranslator const init_quoteslangtranslator()
135 {
136         QuotesLangTranslator translator
137                 (string_quotes_language[0], InsetQuotes::EnglishQuotes);
138         translator.addPair(string_quotes_language[1], InsetQuotes::SwedishQuotes);
139         translator.addPair(string_quotes_language[2], InsetQuotes::GermanQuotes);
140         translator.addPair(string_quotes_language[3], InsetQuotes::PolishQuotes);
141         translator.addPair(string_quotes_language[4], InsetQuotes::FrenchQuotes);
142         translator.addPair(string_quotes_language[5], InsetQuotes::DanishQuotes);
143         return translator;
144 }
145
146
147 QuotesLangTranslator const & quoteslangtranslator()
148 {
149         static QuotesLangTranslator translator = init_quoteslangtranslator();
150         return translator;
151 }
152
153
154 // Paper size
155 typedef Translator<string, PAPER_SIZE> PaperSizeTranslator;
156
157
158 static PaperSizeTranslator initPaperSizeTranslator()
159 {
160         PaperSizeTranslator translator(string_papersize[0], PAPER_DEFAULT);
161         translator.addPair(string_papersize[1], PAPER_CUSTOM);
162         translator.addPair(string_papersize[2], PAPER_USLETTER);
163         translator.addPair(string_papersize[3], PAPER_USLEGAL);
164         translator.addPair(string_papersize[4], PAPER_USEXECUTIVE);
165         translator.addPair(string_papersize[5], PAPER_A0);
166         translator.addPair(string_papersize[6], PAPER_A1);
167         translator.addPair(string_papersize[7], PAPER_A2);
168         translator.addPair(string_papersize[8], PAPER_A3);
169         translator.addPair(string_papersize[9], PAPER_A4);
170         translator.addPair(string_papersize[10], PAPER_A5);
171         translator.addPair(string_papersize[11], PAPER_A6);
172         translator.addPair(string_papersize[12], PAPER_B0);
173         translator.addPair(string_papersize[13], PAPER_B1);
174         translator.addPair(string_papersize[14], PAPER_B2);
175         translator.addPair(string_papersize[15], PAPER_B3);
176         translator.addPair(string_papersize[16], PAPER_B4);
177         translator.addPair(string_papersize[17], PAPER_B5);
178         translator.addPair(string_papersize[18], PAPER_B6);
179         translator.addPair(string_papersize[19], PAPER_C0);
180         translator.addPair(string_papersize[20], PAPER_C1);
181         translator.addPair(string_papersize[21], PAPER_C2);
182         translator.addPair(string_papersize[22], PAPER_C3);
183         translator.addPair(string_papersize[23], PAPER_C4);
184         translator.addPair(string_papersize[24], PAPER_C5);
185         translator.addPair(string_papersize[25], PAPER_C6);
186         translator.addPair(string_papersize[26], PAPER_JISB0);
187         translator.addPair(string_papersize[27], PAPER_JISB1);
188         translator.addPair(string_papersize[28], PAPER_JISB2);
189         translator.addPair(string_papersize[29], PAPER_JISB3);
190         translator.addPair(string_papersize[30], PAPER_JISB4);
191         translator.addPair(string_papersize[31], PAPER_JISB5);
192         translator.addPair(string_papersize[32], PAPER_JISB6);
193         return translator;
194 }
195
196
197 PaperSizeTranslator const & papersizetranslator()
198 {
199         static PaperSizeTranslator translator = initPaperSizeTranslator();
200         return translator;
201 }
202
203
204 // Paper orientation
205 typedef Translator<string, PAPER_ORIENTATION> PaperOrientationTranslator;
206
207
208 PaperOrientationTranslator const init_paperorientationtranslator()
209 {
210         PaperOrientationTranslator translator(string_orientation[0], ORIENTATION_PORTRAIT);
211         translator.addPair(string_orientation[1], ORIENTATION_LANDSCAPE);
212         return translator;
213 }
214
215
216 PaperOrientationTranslator const & paperorientationtranslator()
217 {
218         static PaperOrientationTranslator translator = init_paperorientationtranslator();
219         return translator;
220 }
221
222
223 // Page sides
224 typedef Translator<int, PageSides> SidesTranslator;
225
226
227 SidesTranslator const init_sidestranslator()
228 {
229         SidesTranslator translator(1, OneSide);
230         translator.addPair(2, TwoSides);
231         return translator;
232 }
233
234
235 SidesTranslator const & sidestranslator()
236 {
237         static SidesTranslator translator = init_sidestranslator();
238         return translator;
239 }
240
241
242 // LaTeX packages
243 typedef Translator<int, BufferParams::Package> PackageTranslator;
244
245
246 PackageTranslator const init_packagetranslator()
247 {
248         PackageTranslator translator(0, BufferParams::package_off);
249         translator.addPair(1, BufferParams::package_auto);
250         translator.addPair(2, BufferParams::package_on);
251         return translator;
252 }
253
254
255 PackageTranslator const & packagetranslator()
256 {
257         static PackageTranslator translator = init_packagetranslator();
258         return translator;
259 }
260
261
262 // Cite engine
263 typedef Translator<string, CiteEngineType> CiteEngineTypeTranslator;
264
265
266 CiteEngineTypeTranslator const init_citeenginetypetranslator()
267 {
268         CiteEngineTypeTranslator translator("authoryear", ENGINE_TYPE_AUTHORYEAR);
269         translator.addPair("numerical", ENGINE_TYPE_NUMERICAL);
270         return translator;
271 }
272
273
274 CiteEngineTypeTranslator const & citeenginetypetranslator()
275 {
276         static CiteEngineTypeTranslator translator = init_citeenginetypetranslator();
277         return translator;
278 }
279
280
281 // Spacing
282 typedef Translator<string, Spacing::Space> SpaceTranslator;
283
284
285 SpaceTranslator const init_spacetranslator()
286 {
287         SpaceTranslator translator("default", Spacing::Default);
288         translator.addPair("single", Spacing::Single);
289         translator.addPair("onehalf", Spacing::Onehalf);
290         translator.addPair("double", Spacing::Double);
291         translator.addPair("other", Spacing::Other);
292         return translator;
293 }
294
295
296 SpaceTranslator const & spacetranslator()
297 {
298         static SpaceTranslator translator = init_spacetranslator();
299         return translator;
300 }
301
302 } // anon namespace
303
304
305 class BufferParams::Impl
306 {
307 public:
308         Impl();
309
310         AuthorList authorlist;
311         BranchList branchlist;
312         Bullet temp_bullets[4];
313         Bullet user_defined_bullets[4];
314         IndicesList indiceslist;
315         Spacing spacing;
316         /** This is the amount of space used for paragraph_separation "skip",
317          * and for detached paragraphs in "indented" documents.
318          */
319         HSpace indentation;
320         VSpace defskip;
321         PDFOptions pdfoptions;
322         LayoutFileIndex baseClass_;
323 };
324
325
326 BufferParams::Impl::Impl()
327         : defskip(VSpace::MEDSKIP), baseClass_(string(""))
328 {
329         // set initial author
330         // FIXME UNICODE
331         authorlist.record(Author(from_utf8(lyxrc.user_name), from_utf8(lyxrc.user_email)));
332 }
333
334
335 BufferParams::Impl *
336 BufferParams::MemoryTraits::clone(BufferParams::Impl const * ptr)
337 {
338         LASSERT(ptr, /**/);
339
340         return new BufferParams::Impl(*ptr);
341 }
342
343
344 void BufferParams::MemoryTraits::destroy(BufferParams::Impl * ptr)
345 {
346         delete ptr;
347 }
348
349
350 BufferParams::BufferParams()
351         : pimpl_(new Impl)
352 {
353         setBaseClass(defaultBaseclass());
354         makeDocumentClass();
355         paragraph_separation = ParagraphIndentSeparation;
356         quotes_language = InsetQuotes::EnglishQuotes;
357         fontsize = "default";
358
359         /*  PaperLayout */
360         papersize = PAPER_DEFAULT;
361         orientation = ORIENTATION_PORTRAIT;
362         use_geometry = false;
363         cite_engine_.push_back("basic");
364         cite_engine_type_ = ENGINE_TYPE_NUMERICAL;
365         biblio_style = "plain";
366         use_bibtopic = false;
367         use_indices = false;
368         trackChanges = false;
369         outputChanges = false;
370         use_default_options = true;
371         maintain_unincluded_children = false;
372         secnumdepth = 3;
373         tocdepth = 3;
374         language = default_language;
375         fontenc = "global";
376         fonts_roman = "default";
377         fonts_sans = "default";
378         fonts_typewriter = "default";
379         fonts_math = "auto";
380         fonts_default_family = "default";
381         useNonTeXFonts = false;
382         fonts_expert_sc = false;
383         fonts_old_figures = false;
384         fonts_sans_scale = 100;
385         fonts_typewriter_scale = 100;
386         inputenc = "auto";
387         lang_package = "default";
388         graphics_driver = "default";
389         default_output_format = "default";
390         bibtex_command = "default";
391         index_command = "default";
392         sides = OneSide;
393         columns = 1;
394         listings_params = string();
395         pagestyle = "default";
396         suppress_date = false;
397         justification = true;
398         // no color is the default (white)
399         backgroundcolor = lyx::rgbFromHexName("#ffffff");
400         isbackgroundcolor = false;
401         // no color is the default (black)
402         fontcolor = lyx::rgbFromHexName("#000000");
403         isfontcolor = false;
404         // light gray is the default font color for greyed-out notes
405         notefontcolor = lyx::rgbFromHexName("#cccccc");
406         boxbgcolor = lyx::rgbFromHexName("#ff0000");
407         compressed = lyxrc.save_compressed;
408         for (int iter = 0; iter < 4; ++iter) {
409                 user_defined_bullet(iter) = ITEMIZE_DEFAULTS[iter];
410                 temp_bullet(iter) = ITEMIZE_DEFAULTS[iter];
411         }
412         // default index
413         indiceslist().addDefault(B_("Index"));
414         html_be_strict = false;
415         html_math_output = MathML;
416         html_math_img_scale = 1.0;
417         html_css_as_file = false;
418
419         output_sync = false;
420         use_refstyle = true;
421 }
422
423
424 docstring BufferParams::B_(string const & l10n) const
425 {
426         LASSERT(language, /**/);
427         return getMessages(language->code()).get(l10n);
428 }
429
430
431 BufferParams::Package BufferParams::use_package(std::string const & p) const
432 {
433         PackageMap::const_iterator it = use_packages.find(p);
434         if (it == use_packages.end())
435                 return package_auto;
436         return it->second;
437 }
438
439
440 void BufferParams::use_package(std::string const & p, BufferParams::Package u)
441 {
442         use_packages[p] = u;
443 }
444
445
446 vector<string> const & BufferParams::auto_packages()
447 {
448         static vector<string> packages;
449         if (packages.empty()) {
450                 // adding a package here implies a file format change!
451                 packages.push_back("amsmath");
452                 packages.push_back("amssymb");
453                 packages.push_back("esint");
454                 packages.push_back("mathdots");
455                 packages.push_back("mathtools");
456                 packages.push_back("mhchem");
457                 packages.push_back("undertilde");
458         }
459         return packages;
460 }
461
462
463 AuthorList & BufferParams::authors()
464 {
465         return pimpl_->authorlist;
466 }
467
468
469 AuthorList const & BufferParams::authors() const
470 {
471         return pimpl_->authorlist;
472 }
473
474
475 BranchList & BufferParams::branchlist()
476 {
477         return pimpl_->branchlist;
478 }
479
480
481 BranchList const & BufferParams::branchlist() const
482 {
483         return pimpl_->branchlist;
484 }
485
486
487 IndicesList & BufferParams::indiceslist()
488 {
489         return pimpl_->indiceslist;
490 }
491
492
493 IndicesList const & BufferParams::indiceslist() const
494 {
495         return pimpl_->indiceslist;
496 }
497
498
499 Bullet & BufferParams::temp_bullet(lyx::size_type const index)
500 {
501         LASSERT(index < 4, /**/);
502         return pimpl_->temp_bullets[index];
503 }
504
505
506 Bullet const & BufferParams::temp_bullet(lyx::size_type const index) const
507 {
508         LASSERT(index < 4, /**/);
509         return pimpl_->temp_bullets[index];
510 }
511
512
513 Bullet & BufferParams::user_defined_bullet(lyx::size_type const index)
514 {
515         LASSERT(index < 4, /**/);
516         return pimpl_->user_defined_bullets[index];
517 }
518
519
520 Bullet const & BufferParams::user_defined_bullet(lyx::size_type const index) const
521 {
522         LASSERT(index < 4, /**/);
523         return pimpl_->user_defined_bullets[index];
524 }
525
526
527 Spacing & BufferParams::spacing()
528 {
529         return pimpl_->spacing;
530 }
531
532
533 Spacing const & BufferParams::spacing() const
534 {
535         return pimpl_->spacing;
536 }
537
538
539 PDFOptions & BufferParams::pdfoptions()
540 {
541         return pimpl_->pdfoptions;
542 }
543
544
545 PDFOptions const & BufferParams::pdfoptions() const
546 {
547         return pimpl_->pdfoptions;
548 }
549
550
551 HSpace const & BufferParams::getIndentation() const
552 {
553         return pimpl_->indentation;
554 }
555
556
557 void BufferParams::setIndentation(HSpace const & indent)
558 {
559         pimpl_->indentation = indent;
560 }
561
562
563 VSpace const & BufferParams::getDefSkip() const
564 {
565         return pimpl_->defskip;
566 }
567
568
569 void BufferParams::setDefSkip(VSpace const & vs)
570 {
571         // DEFSKIP will cause an infinite loop
572         LASSERT(vs.kind() != VSpace::DEFSKIP, return);
573         pimpl_->defskip = vs;
574 }
575
576
577 string BufferParams::readToken(Lexer & lex, string const & token,
578         FileName const & filepath)
579 {
580         if (token == "\\textclass") {
581                 lex.next();
582                 string const classname = lex.getString();
583                 // if there exists a local layout file, ignore the system one
584                 // NOTE: in this case, the textclass (.cls file) is assumed to
585                 // be available.
586                 string tcp;
587                 LayoutFileList & bcl = LayoutFileList::get();
588                 if (tcp.empty() && !filepath.empty())
589                         tcp = bcl.addLocalLayout(classname, filepath.absFileName());
590                 if (!tcp.empty())
591                         setBaseClass(tcp);
592                 else
593                         setBaseClass(classname);
594                 // We assume that a tex class exists for local or unknown
595                 // layouts so this warning, will only be given for system layouts.
596                 if (!baseClass()->isTeXClassAvailable()) {
597                         docstring const desc =
598                                 translateIfPossible(from_utf8(baseClass()->description()));
599                         docstring const prereqs =
600                                 from_utf8(baseClass()->prerequisites());
601                         docstring const msg =
602                                 bformat(_("The selected document class\n"
603                                                  "\t%1$s\n"
604                                                  "requires external files that are not available.\n"
605                                                  "The document class can still be used, but the\n"
606                                                  "document cannot be compiled until the following\n"
607                                                  "prerequisites are installed:\n"
608                                                  "\t%2$s\n"
609                                                  "See section 3.1.2.2 (Class Availability) of the\n"
610                                                  "User's Guide for more information."), desc, prereqs);
611                         frontend::Alert::warning(_("Document class not available"),
612                                        msg);
613                 }
614         } else if (token == "\\begin_preamble") {
615                 readPreamble(lex);
616         } else if (token == "\\begin_local_layout") {
617                 readLocalLayout(lex);
618         } else if (token == "\\begin_modules") {
619                 readModules(lex);
620         } else if (token == "\\begin_removed_modules") {
621                 readRemovedModules(lex);
622         } else if (token == "\\begin_includeonly") {
623                 readIncludeonly(lex);
624         } else if (token == "\\maintain_unincluded_children") {
625                 lex >> maintain_unincluded_children;
626         } else if (token == "\\options") {
627                 lex.eatLine();
628                 options = lex.getString();
629         } else if (token == "\\use_default_options") {
630                 lex >> use_default_options;
631         } else if (token == "\\master") {
632                 lex.eatLine();
633                 master = lex.getString();
634         } else if (token == "\\suppress_date") {
635                 lex >> suppress_date;
636         } else if (token == "\\justification") {
637                 lex >> justification;
638         } else if (token == "\\language") {
639                 readLanguage(lex);
640         } else if (token == "\\language_package") {
641                 lex.eatLine();
642                 lang_package = lex.getString();
643         } else if (token == "\\inputencoding") {
644                 lex >> inputenc;
645         } else if (token == "\\graphics") {
646                 readGraphicsDriver(lex);
647         } else if (token == "\\default_output_format") {
648                 lex >> default_output_format;
649         } else if (token == "\\bibtex_command") {
650                 lex.eatLine();
651                 bibtex_command = lex.getString();
652         } else if (token == "\\index_command") {
653                 lex.eatLine();
654                 index_command = lex.getString();
655         } else if (token == "\\fontencoding") {
656                 lex.eatLine();
657                 fontenc = lex.getString();
658         } else if (token == "\\font_roman") {
659                 lex.eatLine();
660                 fonts_roman = lex.getString();
661         } else if (token == "\\font_sans") {
662                 lex.eatLine();
663                 fonts_sans = lex.getString();
664         } else if (token == "\\font_typewriter") {
665                 lex.eatLine();
666                 fonts_typewriter = lex.getString();
667         } else if (token == "\\font_math") {
668                 lex.eatLine();
669                 fonts_math = lex.getString();
670         } else if (token == "\\font_default_family") {
671                 lex >> fonts_default_family;
672         } else if (token == "\\use_non_tex_fonts") {
673                 lex >> useNonTeXFonts;
674         } else if (token == "\\font_sc") {
675                 lex >> fonts_expert_sc;
676         } else if (token == "\\font_osf") {
677                 lex >> fonts_old_figures;
678         } else if (token == "\\font_sf_scale") {
679                 lex >> fonts_sans_scale;
680         } else if (token == "\\font_tt_scale") {
681                 lex >> fonts_typewriter_scale;
682         } else if (token == "\\font_cjk") {
683                 lex >> fonts_cjk;
684         } else if (token == "\\paragraph_separation") {
685                 string parsep;
686                 lex >> parsep;
687                 paragraph_separation = parseptranslator().find(parsep);
688         } else if (token == "\\paragraph_indentation") {
689                 lex.next();
690                 string indentation = lex.getString();
691                 pimpl_->indentation = HSpace(indentation);
692         } else if (token == "\\defskip") {
693                 lex.next();
694                 string const defskip = lex.getString();
695                 pimpl_->defskip = VSpace(defskip);
696                 if (pimpl_->defskip.kind() == VSpace::DEFSKIP)
697                         // that is invalid
698                         pimpl_->defskip = VSpace(VSpace::MEDSKIP);
699         } else if (token == "\\quotes_language") {
700                 string quotes_lang;
701                 lex >> quotes_lang;
702                 quotes_language = quoteslangtranslator().find(quotes_lang);
703         } else if (token == "\\papersize") {
704                 string ppsize;
705                 lex >> ppsize;
706                 papersize = papersizetranslator().find(ppsize);
707         } else if (token == "\\use_geometry") {
708                 lex >> use_geometry;
709         } else if (token == "\\use_package") {
710                 string package;
711                 int use;
712                 lex >> package;
713                 lex >> use;
714                 use_package(package, packagetranslator().find(use));
715         } else if (token == "\\cite_engine") {
716                 lex.eatLine();
717                 vector<string> engine = getVectorFromString(lex.getString());
718                 setCiteEngine(engine);
719         } else if (token == "\\cite_engine_type") {
720                 string engine_type;
721                 lex >> engine_type;
722                 cite_engine_type_ = citeenginetypetranslator().find(engine_type);
723         } else if (token == "\\biblio_style") {
724                 lex.eatLine();
725                 biblio_style = lex.getString();
726         } else if (token == "\\use_bibtopic") {
727                 lex >> use_bibtopic;
728         } else if (token == "\\use_indices") {
729                 lex >> use_indices;
730         } else if (token == "\\tracking_changes") {
731                 lex >> trackChanges;
732         } else if (token == "\\output_changes") {
733                 lex >> outputChanges;
734         } else if (token == "\\branch") {
735                 lex.eatLine();
736                 docstring branch = lex.getDocString();
737                 branchlist().add(branch);
738                 while (true) {
739                         lex.next();
740                         string const tok = lex.getString();
741                         if (tok == "\\end_branch")
742                                 break;
743                         Branch * branch_ptr = branchlist().find(branch);
744                         if (tok == "\\selected") {
745                                 lex.next();
746                                 if (branch_ptr)
747                                         branch_ptr->setSelected(lex.getInteger());
748                         }
749                         if (tok == "\\filename_suffix") {
750                                 lex.next();
751                                 if (branch_ptr)
752                                         branch_ptr->setFileNameSuffix(lex.getInteger());
753                         }
754                         if (tok == "\\color") {
755                                 lex.eatLine();
756                                 string color = lex.getString();
757                                 if (branch_ptr)
758                                         branch_ptr->setColor(color);
759                                 // Update also the Color table:
760                                 if (color == "none")
761                                         color = lcolor.getX11Name(Color_background);
762                                 // FIXME UNICODE
763                                 lcolor.setColor(to_utf8(branch), color);
764                         }
765                 }
766         } else if (token == "\\index") {
767                 lex.eatLine();
768                 docstring index = lex.getDocString();
769                 docstring shortcut;
770                 indiceslist().add(index);
771                 while (true) {
772                         lex.next();
773                         string const tok = lex.getString();
774                         if (tok == "\\end_index")
775                                 break;
776                         Index * index_ptr = indiceslist().find(index);
777                         if (tok == "\\shortcut") {
778                                 lex.next();
779                                 shortcut = lex.getDocString();
780                                 if (index_ptr)
781                                         index_ptr->setShortcut(shortcut);
782                         }
783                         if (tok == "\\color") {
784                                 lex.eatLine();
785                                 string color = lex.getString();
786                                 if (index_ptr)
787                                         index_ptr->setColor(color);
788                                 // Update also the Color table:
789                                 if (color == "none")
790                                         color = lcolor.getX11Name(Color_background);
791                                 // FIXME UNICODE
792                                 if (!shortcut.empty())
793                                         lcolor.setColor(to_utf8(shortcut), color);
794                         }
795                 }
796         } else if (token == "\\author") {
797                 lex.eatLine();
798                 istringstream ss(lex.getString());
799                 Author a;
800                 ss >> a;
801                 author_map[a.bufferId()] = pimpl_->authorlist.record(a);
802         } else if (token == "\\paperorientation") {
803                 string orient;
804                 lex >> orient;
805                 orientation = paperorientationtranslator().find(orient);
806         } else if (token == "\\backgroundcolor") {
807                 lex.eatLine();
808                 backgroundcolor = lyx::rgbFromHexName(lex.getString());
809                 isbackgroundcolor = true;
810         } else if (token == "\\fontcolor") {
811                 lex.eatLine();
812                 fontcolor = lyx::rgbFromHexName(lex.getString());
813                 isfontcolor = true;
814         } else if (token == "\\notefontcolor") {
815                 lex.eatLine();
816                 string color = lex.getString();
817                 notefontcolor = lyx::rgbFromHexName(color);
818         } else if (token == "\\boxbgcolor") {
819                 lex.eatLine();
820                 string color = lex.getString();
821                 boxbgcolor = lyx::rgbFromHexName(color);
822         } else if (token == "\\paperwidth") {
823                 lex >> paperwidth;
824         } else if (token == "\\paperheight") {
825                 lex >> paperheight;
826         } else if (token == "\\leftmargin") {
827                 lex >> leftmargin;
828         } else if (token == "\\topmargin") {
829                 lex >> topmargin;
830         } else if (token == "\\rightmargin") {
831                 lex >> rightmargin;
832         } else if (token == "\\bottommargin") {
833                 lex >> bottommargin;
834         } else if (token == "\\headheight") {
835                 lex >> headheight;
836         } else if (token == "\\headsep") {
837                 lex >> headsep;
838         } else if (token == "\\footskip") {
839                 lex >> footskip;
840         } else if (token == "\\columnsep") {
841                 lex >> columnsep;
842         } else if (token == "\\paperfontsize") {
843                 lex >> fontsize;
844         } else if (token == "\\papercolumns") {
845                 lex >> columns;
846         } else if (token == "\\listings_params") {
847                 string par;
848                 lex >> par;
849                 listings_params = InsetListingsParams(par).params();
850         } else if (token == "\\papersides") {
851                 int psides;
852                 lex >> psides;
853                 sides = sidestranslator().find(psides);
854         } else if (token == "\\paperpagestyle") {
855                 lex >> pagestyle;
856         } else if (token == "\\bullet") {
857                 readBullets(lex);
858         } else if (token == "\\bulletLaTeX") {
859                 readBulletsLaTeX(lex);
860         } else if (token == "\\secnumdepth") {
861                 lex >> secnumdepth;
862         } else if (token == "\\tocdepth") {
863                 lex >> tocdepth;
864         } else if (token == "\\spacing") {
865                 string nspacing;
866                 lex >> nspacing;
867                 string tmp_val;
868                 if (nspacing == "other") {
869                         lex >> tmp_val;
870                 }
871                 spacing().set(spacetranslator().find(nspacing), tmp_val);
872         } else if (token == "\\float_placement") {
873                 lex >> float_placement;
874
875         } else if (prefixIs(token, "\\pdf_") || token == "\\use_hyperref") {
876                 string toktmp = pdfoptions().readToken(lex, token);
877                 if (!toktmp.empty()) {
878                         lyxerr << "PDFOptions::readToken(): Unknown token: " <<
879                                 toktmp << endl;
880                         return toktmp;
881                 }
882         } else if (token == "\\html_math_output") {
883                 int temp;
884                 lex >> temp;
885                 html_math_output = static_cast<MathOutput>(temp);
886         } else if (token == "\\html_be_strict") {
887                 lex >> html_be_strict;
888         } else if (token == "\\html_css_as_file") {
889                 lex >> html_css_as_file;
890         } else if (token == "\\html_math_img_scale") {
891                 lex >> html_math_img_scale;
892         } else if (token == "\\html_latex_start") {
893                 lex.eatLine();
894                 html_latex_start = lex.getString();
895         } else if (token == "\\html_latex_end") {
896                 lex.eatLine();
897                 html_latex_end = lex.getString();
898         } else if (token == "\\output_sync") {
899                 lex >> output_sync;
900         } else if (token == "\\output_sync_macro") {
901                 lex >> output_sync_macro;
902         } else if (token == "\\use_refstyle") {
903                 lex >> use_refstyle;
904         } else {
905                 lyxerr << "BufferParams::readToken(): Unknown token: " <<
906                         token << endl;
907                 return token;
908         }
909
910         return string();
911 }
912
913
914 void BufferParams::writeFile(ostream & os) const
915 {
916         // The top of the file is written by the buffer.
917         // Prints out the buffer info into the .lyx file given by file
918
919         // the textclass
920         os << "\\textclass " << baseClass()->name() << '\n';
921
922         // then the preamble
923         if (!preamble.empty()) {
924                 // remove '\n' from the end of preamble
925                 string const tmppreamble = rtrim(preamble, "\n");
926                 os << "\\begin_preamble\n"
927                    << tmppreamble
928                    << "\n\\end_preamble\n";
929         }
930
931         // the options
932         if (!options.empty()) {
933                 os << "\\options " << options << '\n';
934         }
935
936         // use the class options defined in the layout?
937         os << "\\use_default_options "
938            << convert<string>(use_default_options) << "\n";
939
940         // the master document
941         if (!master.empty()) {
942                 os << "\\master " << master << '\n';
943         }
944
945         // removed modules
946         if (!removed_modules_.empty()) {
947                 os << "\\begin_removed_modules" << '\n';
948                 list<string>::const_iterator it = removed_modules_.begin();
949                 list<string>::const_iterator en = removed_modules_.end();
950                 for (; it != en; ++it)
951                         os << *it << '\n';
952                 os << "\\end_removed_modules" << '\n';
953         }
954
955         // the modules
956         if (!layout_modules_.empty()) {
957                 os << "\\begin_modules" << '\n';
958                 LayoutModuleList::const_iterator it = layout_modules_.begin();
959                 LayoutModuleList::const_iterator en = layout_modules_.end();
960                 for (; it != en; ++it)
961                         os << *it << '\n';
962                 os << "\\end_modules" << '\n';
963         }
964
965         // includeonly
966         if (!included_children_.empty()) {
967                 os << "\\begin_includeonly" << '\n';
968                 list<string>::const_iterator it = included_children_.begin();
969                 list<string>::const_iterator en = included_children_.end();
970                 for (; it != en; ++it)
971                         os << *it << '\n';
972                 os << "\\end_includeonly" << '\n';
973         }
974         os << "\\maintain_unincluded_children "
975            << convert<string>(maintain_unincluded_children) << '\n';
976
977         // local layout information
978         if (!local_layout.empty()) {
979                 // remove '\n' from the end
980                 string const tmplocal = rtrim(local_layout, "\n");
981                 os << "\\begin_local_layout\n"
982                    << tmplocal
983                    << "\n\\end_local_layout\n";
984         }
985
986         // then the text parameters
987         if (language != ignore_language)
988                 os << "\\language " << language->lang() << '\n';
989         os << "\\language_package " << lang_package
990            << "\n\\inputencoding " << inputenc
991            << "\n\\fontencoding " << fontenc
992            << "\n\\font_roman " << fonts_roman
993            << "\n\\font_sans " << fonts_sans
994            << "\n\\font_typewriter " << fonts_typewriter
995            << "\n\\font_math " << fonts_math
996            << "\n\\font_default_family " << fonts_default_family
997            << "\n\\use_non_tex_fonts " << convert<string>(useNonTeXFonts)
998            << "\n\\font_sc " << convert<string>(fonts_expert_sc)
999            << "\n\\font_osf " << convert<string>(fonts_old_figures)
1000            << "\n\\font_sf_scale " << fonts_sans_scale
1001            << "\n\\font_tt_scale " << fonts_typewriter_scale
1002            << '\n';
1003         if (!fonts_cjk.empty()) {
1004                 os << "\\font_cjk " << fonts_cjk << '\n';
1005         }
1006         os << "\\graphics " << graphics_driver << '\n';
1007         os << "\\default_output_format " << default_output_format << '\n';
1008         os << "\\output_sync " << output_sync << '\n';
1009         if (!output_sync_macro.empty())
1010                 os << "\\output_sync_macro \"" << output_sync_macro << "\"\n";
1011         os << "\\bibtex_command " << bibtex_command << '\n';
1012         os << "\\index_command " << index_command << '\n';
1013
1014         if (!float_placement.empty()) {
1015                 os << "\\float_placement " << float_placement << '\n';
1016         }
1017         os << "\\paperfontsize " << fontsize << '\n';
1018
1019         spacing().writeFile(os);
1020         pdfoptions().writeFile(os);
1021
1022         os << "\\papersize " << string_papersize[papersize]
1023            << "\n\\use_geometry " << convert<string>(use_geometry);
1024         vector<string> const & packages = auto_packages();
1025         for (size_t i = 0; i < packages.size(); ++i)
1026                 os << "\n\\use_package " << packages[i] << ' '
1027                    << use_package(packages[i]);
1028
1029         os << "\n\\cite_engine ";
1030
1031         if (!cite_engine_.empty()) {
1032                 LayoutModuleList::const_iterator be = cite_engine_.begin();
1033                 LayoutModuleList::const_iterator en = cite_engine_.end();
1034                 for (LayoutModuleList::const_iterator it = be; it != en; ++it) {
1035                         if (it != be)
1036                                 os << ',';
1037                         os << *it;
1038                 }
1039         } else {
1040                 os << "basic";
1041         }
1042
1043         os << "\n\\cite_engine_type " << citeenginetypetranslator().find(cite_engine_type_)
1044            << "\n\\biblio_style " << biblio_style
1045            << "\n\\use_bibtopic " << convert<string>(use_bibtopic)
1046            << "\n\\use_indices " << convert<string>(use_indices)
1047            << "\n\\paperorientation " << string_orientation[orientation]
1048            << "\n\\suppress_date " << convert<string>(suppress_date)
1049            << "\n\\justification " << convert<string>(justification)
1050            << "\n\\use_refstyle " << use_refstyle
1051            << '\n';
1052         if (isbackgroundcolor == true)
1053                 os << "\\backgroundcolor " << lyx::X11hexname(backgroundcolor) << '\n';
1054         if (isfontcolor == true)
1055                 os << "\\fontcolor " << lyx::X11hexname(fontcolor) << '\n';
1056         if (notefontcolor != lyx::rgbFromHexName("#cccccc"))
1057                 os << "\\notefontcolor " << lyx::X11hexname(notefontcolor) << '\n';
1058         if (boxbgcolor != lyx::rgbFromHexName("#ff0000"))
1059                 os << "\\boxbgcolor " << lyx::X11hexname(boxbgcolor) << '\n';
1060
1061         BranchList::const_iterator it = branchlist().begin();
1062         BranchList::const_iterator end = branchlist().end();
1063         for (; it != end; ++it) {
1064                 os << "\\branch " << to_utf8(it->branch())
1065                    << "\n\\selected " << it->isSelected()
1066                    << "\n\\filename_suffix " << it->hasFileNameSuffix()
1067                    << "\n\\color " << lyx::X11hexname(it->color())
1068                    << "\n\\end_branch"
1069                    << "\n";
1070         }
1071
1072         IndicesList::const_iterator iit = indiceslist().begin();
1073         IndicesList::const_iterator iend = indiceslist().end();
1074         for (; iit != iend; ++iit) {
1075                 os << "\\index " << to_utf8(iit->index())
1076                    << "\n\\shortcut " << to_utf8(iit->shortcut())
1077                    << "\n\\color " << lyx::X11hexname(iit->color())
1078                    << "\n\\end_index"
1079                    << "\n";
1080         }
1081
1082         if (!paperwidth.empty())
1083                 os << "\\paperwidth "
1084                    << VSpace(paperwidth).asLyXCommand() << '\n';
1085         if (!paperheight.empty())
1086                 os << "\\paperheight "
1087                    << VSpace(paperheight).asLyXCommand() << '\n';
1088         if (!leftmargin.empty())
1089                 os << "\\leftmargin "
1090                    << VSpace(leftmargin).asLyXCommand() << '\n';
1091         if (!topmargin.empty())
1092                 os << "\\topmargin "
1093                    << VSpace(topmargin).asLyXCommand() << '\n';
1094         if (!rightmargin.empty())
1095                 os << "\\rightmargin "
1096                    << VSpace(rightmargin).asLyXCommand() << '\n';
1097         if (!bottommargin.empty())
1098                 os << "\\bottommargin "
1099                    << VSpace(bottommargin).asLyXCommand() << '\n';
1100         if (!headheight.empty())
1101                 os << "\\headheight "
1102                    << VSpace(headheight).asLyXCommand() << '\n';
1103         if (!headsep.empty())
1104                 os << "\\headsep "
1105                    << VSpace(headsep).asLyXCommand() << '\n';
1106         if (!footskip.empty())
1107                 os << "\\footskip "
1108                    << VSpace(footskip).asLyXCommand() << '\n';
1109         if (!columnsep.empty())
1110                 os << "\\columnsep "
1111                          << VSpace(columnsep).asLyXCommand() << '\n';
1112         os << "\\secnumdepth " << secnumdepth
1113            << "\n\\tocdepth " << tocdepth
1114            << "\n\\paragraph_separation "
1115            << string_paragraph_separation[paragraph_separation];
1116         if (!paragraph_separation)
1117                 os << "\n\\paragraph_indentation " << getIndentation().asLyXCommand();
1118         else
1119                 os << "\n\\defskip " << getDefSkip().asLyXCommand();
1120         os << "\n\\quotes_language "
1121            << string_quotes_language[quotes_language]
1122            << "\n\\papercolumns " << columns
1123            << "\n\\papersides " << sides
1124            << "\n\\paperpagestyle " << pagestyle << '\n';
1125         if (!listings_params.empty())
1126                 os << "\\listings_params \"" <<
1127                         InsetListingsParams(listings_params).encodedString() << "\"\n";
1128         for (int i = 0; i < 4; ++i) {
1129                 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1130                         if (user_defined_bullet(i).getFont() != -1) {
1131                                 os << "\\bullet " << i << " "
1132                                    << user_defined_bullet(i).getFont() << " "
1133                                    << user_defined_bullet(i).getCharacter() << " "
1134                                    << user_defined_bullet(i).getSize() << "\n";
1135                         }
1136                         else {
1137                                 // FIXME UNICODE
1138                                 os << "\\bulletLaTeX " << i << " \""
1139                                    << lyx::to_ascii(user_defined_bullet(i).getText())
1140                                    << "\"\n";
1141                         }
1142                 }
1143         }
1144
1145         os << "\\tracking_changes " << convert<string>(trackChanges) << '\n'
1146            << "\\output_changes " << convert<string>(outputChanges) << '\n'
1147            << "\\html_math_output " << html_math_output << '\n'
1148            << "\\html_css_as_file " << html_css_as_file << '\n'
1149            << "\\html_be_strict " << convert<string>(html_be_strict) << '\n';
1150
1151         if (html_math_img_scale != 1.0)
1152                 os << "\\html_math_img_scale " << convert<string>(html_math_img_scale) << '\n';
1153         if (!html_latex_start.empty())
1154                 os << "\\html_latex_start " << html_latex_start << '\n';
1155         if (!html_latex_end.empty())
1156                  os << "\\html_latex_end " << html_latex_end << '\n';
1157
1158         os << pimpl_->authorlist;
1159 }
1160
1161
1162 void BufferParams::validate(LaTeXFeatures & features) const
1163 {
1164         features.require(documentClass().requires());
1165
1166         if (outputChanges) {
1167                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1168                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1169                                   LaTeXFeatures::isAvailable("xcolor");
1170
1171                 switch (features.runparams().flavor) {
1172                 case OutputParams::LATEX:
1173                 case OutputParams::DVILUATEX:
1174                         if (dvipost) {
1175                                 features.require("ct-dvipost");
1176                                 features.require("dvipost");
1177                         } else if (xcolorulem) {
1178                                 features.require("ct-xcolor-ulem");
1179                                 features.require("ulem");
1180                                 features.require("xcolor");
1181                         } else {
1182                                 features.require("ct-none");
1183                         }
1184                         break;
1185                 case OutputParams::LUATEX:
1186                 case OutputParams::PDFLATEX:
1187                 case OutputParams::XETEX:
1188                         if (xcolorulem) {
1189                                 features.require("ct-xcolor-ulem");
1190                                 features.require("ulem");
1191                                 features.require("xcolor");
1192                                 // improves color handling in PDF output
1193                                 features.require("pdfcolmk");
1194                         } else {
1195                                 features.require("ct-none");
1196                         }
1197                         break;
1198                 default:
1199                         break;
1200                 }
1201         }
1202
1203         // Floats with 'Here definitely' as default setting.
1204         if (float_placement.find('H') != string::npos)
1205                 features.require("float");
1206
1207         for (PackageMap::const_iterator it = use_packages.begin();
1208              it != use_packages.end(); ++it) {
1209                 if (it->first == "amsmath") {
1210                         // AMS Style is at document level
1211                         if (it->second == package_on ||
1212                             features.isProvided("amsmath"))
1213                                 features.require(it->first);
1214                 } else if (it->second == package_on)
1215                         features.require(it->first);
1216         }
1217
1218         // Document-level line spacing
1219         if (spacing().getSpace() != Spacing::Single && !spacing().isDefault())
1220                 features.require("setspace");
1221
1222         // the bullet shapes are buffer level not paragraph level
1223         // so they are tested here
1224         for (int i = 0; i < 4; ++i) {
1225                 if (user_defined_bullet(i) == ITEMIZE_DEFAULTS[i])
1226                         continue;
1227                 int const font = user_defined_bullet(i).getFont();
1228                 if (font == 0) {
1229                         int const c = user_defined_bullet(i).getCharacter();
1230                         if (c == 16
1231                             || c == 17
1232                             || c == 25
1233                             || c == 26
1234                             || c == 31) {
1235                                 features.require("latexsym");
1236                         }
1237                 } else if (font == 1) {
1238                         features.require("amssymb");
1239                 } else if (font >= 2 && font <= 5) {
1240                         features.require("pifont");
1241                 }
1242         }
1243
1244         if (pdfoptions().use_hyperref) {
1245                 features.require("hyperref");
1246                 // due to interferences with babel and hyperref, the color package has to
1247                 // be loaded after hyperref when hyperref is used with the colorlinks
1248                 // option, see http://www.lyx.org/trac/ticket/5291
1249                 if (pdfoptions().colorlinks)
1250                         features.require("color");
1251         }
1252
1253         // some languages are only available via polyglossia
1254         if (features.runparams().flavor == OutputParams::XETEX
1255             && (features.hasPolyglossiaExclusiveLanguages()
1256                 || useNonTeXFonts))
1257                 features.require("polyglossia");
1258
1259         if (!language->requires().empty())
1260                 features.require(language->requires());
1261 }
1262
1263
1264 bool BufferParams::writeLaTeX(otexstream & os, LaTeXFeatures & features,
1265                               FileName const & filepath) const
1266 {
1267         // http://www.tug.org/texmf-dist/doc/latex/base/fixltx2e.pdf
1268         // !! To use the Fix-cm package, load it before \documentclass, and use the command
1269         // \RequirePackage to do so, rather than the normal \usepackage
1270         // Do not try to load any other package before the document class, unless you
1271         // have a thorough understanding of the LATEX internals and know exactly what you
1272         // are doing!
1273         if (features.mustProvide("fix-cm"))
1274                 os << "\\RequirePackage{fix-cm}\n";
1275
1276         os << "\\documentclass";
1277
1278         DocumentClass const & tclass = documentClass();
1279
1280         ostringstream clsoptions; // the document class options.
1281
1282         if (tokenPos(tclass.opt_fontsize(),
1283                      '|', fontsize) >= 0) {
1284                 // only write if existing in list (and not default)
1285                 clsoptions << fontsize << "pt,";
1286         }
1287
1288         // all paper sizes except of A4, A5, B5 and the US sizes need the
1289         // geometry package
1290         bool nonstandard_papersize = papersize != PAPER_DEFAULT
1291                 && papersize != PAPER_USLETTER
1292                 && papersize != PAPER_USLEGAL
1293                 && papersize != PAPER_USEXECUTIVE
1294                 && papersize != PAPER_A4
1295                 && papersize != PAPER_A5
1296                 && papersize != PAPER_B5;
1297
1298         if (!use_geometry) {
1299                 switch (papersize) {
1300                 case PAPER_A4:
1301                         clsoptions << "a4paper,";
1302                         break;
1303                 case PAPER_USLETTER:
1304                         clsoptions << "letterpaper,";
1305                         break;
1306                 case PAPER_A5:
1307                         clsoptions << "a5paper,";
1308                         break;
1309                 case PAPER_B5:
1310                         clsoptions << "b5paper,";
1311                         break;
1312                 case PAPER_USEXECUTIVE:
1313                         clsoptions << "executivepaper,";
1314                         break;
1315                 case PAPER_USLEGAL:
1316                         clsoptions << "legalpaper,";
1317                         break;
1318                 case PAPER_DEFAULT:
1319                 case PAPER_A0:
1320                 case PAPER_A1:
1321                 case PAPER_A2:
1322                 case PAPER_A3:
1323                 case PAPER_A6:
1324                 case PAPER_B0:
1325                 case PAPER_B1:
1326                 case PAPER_B2:
1327                 case PAPER_B3:
1328                 case PAPER_B4:
1329                 case PAPER_B6:
1330                 case PAPER_C0:
1331                 case PAPER_C1:
1332                 case PAPER_C2:
1333                 case PAPER_C3:
1334                 case PAPER_C4:
1335                 case PAPER_C5:
1336                 case PAPER_C6:
1337                 case PAPER_JISB0:
1338                 case PAPER_JISB1:
1339                 case PAPER_JISB2:
1340                 case PAPER_JISB3:
1341                 case PAPER_JISB4:
1342                 case PAPER_JISB5:
1343                 case PAPER_JISB6:
1344                 case PAPER_CUSTOM:
1345                         break;
1346                 }
1347         }
1348
1349         // if needed
1350         if (sides != tclass.sides()) {
1351                 switch (sides) {
1352                 case OneSide:
1353                         clsoptions << "oneside,";
1354                         break;
1355                 case TwoSides:
1356                         clsoptions << "twoside,";
1357                         break;
1358                 }
1359         }
1360
1361         // if needed
1362         if (columns != tclass.columns()) {
1363                 if (columns == 2)
1364                         clsoptions << "twocolumn,";
1365                 else
1366                         clsoptions << "onecolumn,";
1367         }
1368
1369         if (!use_geometry
1370             && orientation == ORIENTATION_LANDSCAPE)
1371                 clsoptions << "landscape,";
1372
1373         // language should be a parameter to \documentclass
1374         if (language->babel() == "hebrew"
1375             && default_language->babel() != "hebrew")
1376                 // This seems necessary
1377                 features.useLanguage(default_language);
1378
1379         ostringstream language_options;
1380         bool const use_babel = features.useBabel() && !features.isProvided("babel");
1381         bool const use_polyglossia = features.usePolyglossia();
1382         bool const global = lyxrc.language_global_options;
1383         if (use_babel || (use_polyglossia && global)) {
1384                 language_options << features.getBabelLanguages();
1385                 if (!language->babel().empty()) {
1386                         if (!language_options.str().empty())
1387                                 language_options << ',';
1388                         language_options << language->babel();
1389                 }
1390                 if (global && !features.needBabelLangOptions()
1391                     && !language_options.str().empty())
1392                         clsoptions << language_options.str() << ',';
1393         }
1394
1395         // the predefined options from the layout
1396         if (use_default_options && !tclass.options().empty())
1397                 clsoptions << tclass.options() << ',';
1398
1399         // the user-defined options
1400         if (!options.empty()) {
1401                 clsoptions << options << ',';
1402         }
1403
1404         string strOptions(clsoptions.str());
1405         if (!strOptions.empty()) {
1406                 strOptions = rtrim(strOptions, ",");
1407                 // FIXME UNICODE
1408                 os << '[' << from_utf8(strOptions) << ']';
1409         }
1410
1411         os << '{' << from_ascii(tclass.latexname()) << "}\n";
1412         // end of \documentclass defs
1413
1414         // if we use fontspec, we have to load the AMS packages here
1415         string const ams = features.loadAMSPackages();
1416         if (useNonTeXFonts && !ams.empty())
1417                 os << from_ascii(ams);
1418
1419         if (useNonTeXFonts)
1420                 os << "\\usepackage{fontspec}\n";
1421
1422         // font selection must be done before loading fontenc.sty
1423         string const fonts = loadFonts(features);
1424         if (!fonts.empty())
1425                 os << from_utf8(fonts);
1426
1427         if (fonts_default_family != "default")
1428                 os << "\\renewcommand{\\familydefault}{\\"
1429                    << from_ascii(fonts_default_family) << "}\n";
1430
1431         // set font encoding
1432         // for arabic_arabi and farsi we also need to load the LAE and
1433         // LFE encoding
1434         // XeTeX and LuaTeX (with OS fonts) work without fontenc
1435         if (font_encoding() != "default" && language->lang() != "japanese"
1436             && !useNonTeXFonts && !features.isProvided("fontenc")) {
1437                 size_t fars = language_options.str().find("farsi");
1438                 size_t arab = language_options.str().find("arabic");
1439                 if (language->lang() == "arabic_arabi"
1440                         || language->lang() == "farsi" || fars != string::npos
1441                         || arab != string::npos) {
1442                         os << "\\usepackage[" << from_ascii(font_encoding())
1443                            << ",LFE,LAE]{fontenc}\n";
1444                 } else {
1445                         os << "\\usepackage[" << from_ascii(font_encoding())
1446                            << "]{fontenc}\n";
1447                 }
1448         }
1449
1450         // handle inputenc etc.
1451         writeEncodingPreamble(os, features);
1452
1453         // includeonly
1454         if (!features.runparams().includeall && !included_children_.empty()) {
1455                 os << "\\includeonly{";
1456                 list<string>::const_iterator it = included_children_.begin();
1457                 list<string>::const_iterator en = included_children_.end();
1458                 bool first = true;
1459                 for (; it != en; ++it) {
1460                         string incfile = *it;
1461                         FileName inc = makeAbsPath(incfile, filepath.absFileName());
1462                         string mangled = DocFileName(changeExtension(inc.absFileName(), ".tex")).
1463                         mangledFileName();
1464                         if (!features.runparams().nice)
1465                                 incfile = mangled;
1466                         // \includeonly doesn't want an extension
1467                         incfile = changeExtension(incfile, string());
1468                         incfile = support::latex_path(incfile);
1469                         if (!incfile.empty()) {
1470                                 if (!first)
1471                                         os << ",";
1472                                 os << from_utf8(incfile);
1473                         }
1474                         first = false;
1475                 }
1476                 os << "}\n";
1477         }
1478
1479         if (!listings_params.empty() || features.isRequired("listings"))
1480                 os << "\\usepackage{listings}\n";
1481
1482         if (!listings_params.empty()) {
1483                 os << "\\lstset{";
1484                 // do not test validity because listings_params is
1485                 // supposed to be valid
1486                 string par =
1487                         InsetListingsParams(listings_params).separatedParams(true);
1488                 // we can't support all packages, but we should load the color package
1489                 if (par.find("\\color", 0) != string::npos)
1490                         features.require("color");
1491                 os << from_utf8(par)
1492                    << "}\n";
1493         }
1494         if (!features.isProvided("geometry")
1495             && (use_geometry || nonstandard_papersize)) {
1496                 odocstringstream ods;
1497                 if (!getGraphicsDriver("geometry").empty())
1498                         ods << getGraphicsDriver("geometry");
1499                 if (orientation == ORIENTATION_LANDSCAPE)
1500                         ods << ",landscape";
1501                 switch (papersize) {
1502                 case PAPER_CUSTOM:
1503                         if (!paperwidth.empty())
1504                                 ods << ",paperwidth="
1505                                    << from_ascii(paperwidth);
1506                         if (!paperheight.empty())
1507                                 ods << ",paperheight="
1508                                    << from_ascii(paperheight);
1509                         break;
1510                 case PAPER_USLETTER:
1511                         ods << ",letterpaper";
1512                         break;
1513                 case PAPER_USLEGAL:
1514                         ods << ",legalpaper";
1515                         break;
1516                 case PAPER_USEXECUTIVE:
1517                         ods << ",executivepaper";
1518                         break;
1519                 case PAPER_A0:
1520                         ods << ",a0paper";
1521                         break;
1522                 case PAPER_A1:
1523                         ods << ",a1paper";
1524                         break;
1525                 case PAPER_A2:
1526                         ods << ",a2paper";
1527                         break;
1528                 case PAPER_A3:
1529                         ods << ",a3paper";
1530                         break;
1531                 case PAPER_A4:
1532                         ods << ",a4paper";
1533                         break;
1534                 case PAPER_A5:
1535                         ods << ",a5paper";
1536                         break;
1537                 case PAPER_A6:
1538                         ods << ",a6paper";
1539                         break;
1540                 case PAPER_B0:
1541                         ods << ",b0paper";
1542                         break;
1543                 case PAPER_B1:
1544                         ods << ",b1paper";
1545                         break;
1546                 case PAPER_B2:
1547                         ods << ",b2paper";
1548                         break;
1549                 case PAPER_B3:
1550                         ods << ",b3paper";
1551                         break;
1552                 case PAPER_B4:
1553                         ods << ",b4paper";
1554                         break;
1555                 case PAPER_B5:
1556                         ods << ",b5paper";
1557                         break;
1558                 case PAPER_B6:
1559                         ods << ",b6paper";
1560                         break;
1561                 case PAPER_C0:
1562                         ods << ",c0paper";
1563                         break;
1564                 case PAPER_C1:
1565                         ods << ",c1paper";
1566                         break;
1567                 case PAPER_C2:
1568                         ods << ",c2paper";
1569                         break;
1570                 case PAPER_C3:
1571                         ods << ",c3paper";
1572                         break;
1573                 case PAPER_C4:
1574                         ods << ",c4paper";
1575                         break;
1576                 case PAPER_C5:
1577                         ods << ",c5paper";
1578                         break;
1579                 case PAPER_C6:
1580                         ods << ",c6paper";
1581                         break;
1582                 case PAPER_JISB0:
1583                         ods << ",b0j";
1584                         break;
1585                 case PAPER_JISB1:
1586                         ods << ",b1j";
1587                         break;
1588                 case PAPER_JISB2:
1589                         ods << ",b2j";
1590                         break;
1591                 case PAPER_JISB3:
1592                         ods << ",b3j";
1593                         break;
1594                 case PAPER_JISB4:
1595                         ods << ",b4j";
1596                         break;
1597                 case PAPER_JISB5:
1598                         ods << ",b5j";
1599                         break;
1600                 case PAPER_JISB6:
1601                         ods << ",b6j";
1602                         break;
1603                 case PAPER_DEFAULT:
1604                         break;
1605                 }
1606                 docstring const g_options = trim(ods.str(), ",");
1607                 os << "\\usepackage";
1608                 if (!g_options.empty())
1609                         os << '[' << g_options << ']';
1610                 os << "{geometry}\n";
1611                 // output this only if use_geometry is true
1612                 if (use_geometry) {
1613                         os << "\\geometry{verbose";
1614                         if (!topmargin.empty())
1615                                 os << ",tmargin=" << from_ascii(Length(topmargin).asLatexString());
1616                         if (!bottommargin.empty())
1617                                 os << ",bmargin=" << from_ascii(Length(bottommargin).asLatexString());
1618                         if (!leftmargin.empty())
1619                                 os << ",lmargin=" << from_ascii(Length(leftmargin).asLatexString());
1620                         if (!rightmargin.empty())
1621                                 os << ",rmargin=" << from_ascii(Length(rightmargin).asLatexString());
1622                         if (!headheight.empty())
1623                                 os << ",headheight=" << from_ascii(Length(headheight).asLatexString());
1624                         if (!headsep.empty())
1625                                 os << ",headsep=" << from_ascii(Length(headsep).asLatexString());
1626                         if (!footskip.empty())
1627                                 os << ",footskip=" << from_ascii(Length(footskip).asLatexString());
1628                         if (!columnsep.empty())
1629                                 os << ",columnsep=" << from_ascii(Length(columnsep).asLatexString());
1630                         os << "}\n";
1631                 }
1632         } else if (orientation == ORIENTATION_LANDSCAPE
1633                    || papersize != PAPER_DEFAULT) {
1634                 features.require("papersize");
1635         }
1636
1637         if (tokenPos(tclass.opt_pagestyle(), '|', pagestyle) >= 0) {
1638                 if (pagestyle == "fancy")
1639                         os << "\\usepackage{fancyhdr}\n";
1640                 os << "\\pagestyle{" << from_ascii(pagestyle) << "}\n";
1641         }
1642
1643         // only output when the background color is not default
1644         if (isbackgroundcolor == true) {
1645                 // only require color here, the background color will be defined
1646                 // in LaTeXFeatures.cpp to avoid interferences with the LaTeX
1647                 // package pdfpages
1648                 features.require("color");
1649                 features.require("pagecolor");
1650         }
1651
1652         // only output when the font color is not default
1653         if (isfontcolor == true) {
1654                 // only require color here, the font color will be defined
1655                 // in LaTeXFeatures.cpp to avoid interferences with the LaTeX
1656                 // package pdfpages
1657                 features.require("color");
1658                 features.require("fontcolor");
1659         }
1660
1661         // Only if class has a ToC hierarchy
1662         if (tclass.hasTocLevels()) {
1663                 if (secnumdepth != tclass.secnumdepth()) {
1664                         os << "\\setcounter{secnumdepth}{"
1665                            << secnumdepth
1666                            << "}\n";
1667                 }
1668                 if (tocdepth != tclass.tocdepth()) {
1669                         os << "\\setcounter{tocdepth}{"
1670                            << tocdepth
1671                            << "}\n";
1672                 }
1673         }
1674
1675         if (paragraph_separation) {
1676                 // when skip separation
1677                 switch (getDefSkip().kind()) {
1678                 case VSpace::SMALLSKIP:
1679                         os << "\\setlength{\\parskip}{\\smallskipamount}\n";
1680                         break;
1681                 case VSpace::MEDSKIP:
1682                         os << "\\setlength{\\parskip}{\\medskipamount}\n";
1683                         break;
1684                 case VSpace::BIGSKIP:
1685                         os << "\\setlength{\\parskip}{\\bigskipamount}\n";
1686                         break;
1687                 case VSpace::LENGTH:
1688                         os << "\\setlength{\\parskip}{"
1689                            << from_utf8(getDefSkip().length().asLatexString())
1690                            << "}\n";
1691                         break;
1692                 default: // should never happen // Then delete it.
1693                         os << "\\setlength{\\parskip}{\\medskipamount}\n";
1694                         break;
1695                 }
1696                 os << "\\setlength{\\parindent}{0pt}\n";
1697         } else {
1698                 // when separation by indentation
1699                 // only output something when a width is given
1700                 if (getIndentation().asLyXCommand() != "default") {
1701                         os << "\\setlength{\\parindent}{"
1702                            << from_utf8(getIndentation().asLatexCommand())
1703                            << "}\n";
1704                 }
1705         }
1706
1707         // Now insert the LyX specific LaTeX commands...
1708         docstring lyxpreamble;
1709         features.resolveAlternatives();
1710
1711         if (output_sync) {
1712                 if (!output_sync_macro.empty())
1713                         lyxpreamble += from_utf8(output_sync_macro) +"\n";
1714                 else if (features.runparams().flavor == OutputParams::LATEX)
1715                         lyxpreamble += "\\usepackage[active]{srcltx}\n";
1716                 else if (features.runparams().flavor == OutputParams::PDFLATEX)
1717                         lyxpreamble += "\\synctex=-1\n";
1718         }
1719
1720         // due to interferences with babel and hyperref, the color package has to
1721         // be loaded (when it is not already loaded) before babel when hyperref
1722         // is used with the colorlinks option, see
1723         // http://www.lyx.org/trac/ticket/5291
1724         // we decided therefore to load color always before babel, see
1725         // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg144349.html
1726         lyxpreamble += from_ascii(features.getColorOptions());
1727
1728         // If we use hyperref, jurabib, japanese, or vietnamese, we have to call babel before them.
1729         if (use_babel
1730             && (features.isRequired("jurabib")
1731                 || features.isRequired("hyperref")
1732                 || features.isRequired("vietnamese")
1733                 || features.isRequired("japanese"))) {
1734                         // FIXME UNICODE
1735                         lyxpreamble += from_utf8(features.getBabelPresettings());
1736                         lyxpreamble += from_utf8(babelCall(language_options.str(),
1737                                                            features.needBabelLangOptions())) + '\n';
1738                         lyxpreamble += from_utf8(features.getBabelPostsettings());
1739         }
1740
1741         // The optional packages;
1742         lyxpreamble += from_ascii(features.getPackages());
1743
1744         // Additional Indices
1745         if (features.isRequired("splitidx")) {
1746                 IndicesList::const_iterator iit = indiceslist().begin();
1747                 IndicesList::const_iterator iend = indiceslist().end();
1748                 for (; iit != iend; ++iit) {
1749                         pair<docstring, docstring> indexname_latex =
1750                                 features.runparams().encoding->latexString(iit->index(),
1751                                                                            features.runparams().dryrun);
1752                         if (!indexname_latex.second.empty()) {
1753                                 // issue a warning about omitted characters
1754                                 // FIXME: should be passed to the error dialog
1755                                 frontend::Alert::warning(_("Uncodable characters"),
1756                                         bformat(_("The following characters that are used in an index name are not\n"
1757                                                   "representable in the current encoding and therefore have been omitted:\n%1$s."),
1758                                                 indexname_latex.second));
1759                         }
1760                         lyxpreamble += "\\newindex[";
1761                         lyxpreamble += indexname_latex.first;
1762                         lyxpreamble += "]{";
1763                         lyxpreamble += escape(iit->shortcut());
1764                         lyxpreamble += "}\n";
1765                 }
1766         }
1767
1768         // Line spacing
1769         lyxpreamble += from_utf8(spacing().writePreamble(features.isProvided("SetSpace")));
1770
1771         // PDF support.
1772         // * Hyperref manual: "Make sure it comes last of your loaded
1773         //   packages, to give it a fighting chance of not being over-written,
1774         //   since its job is to redefine many LaTeX commands."
1775         // * Email from Heiko Oberdiek: "It is usually better to load babel
1776         //   before hyperref. Then hyperref has a chance to detect babel.
1777         // * Has to be loaded before the "LyX specific LaTeX commands" to
1778         //   avoid errors with algorithm floats.
1779         // use hyperref explicitly if it is required
1780         if (features.isRequired("hyperref")) {
1781                 // pass what we have to stream here, since we need
1782                 // to access the stream itself in PDFOptions.
1783                 os << lyxpreamble;
1784
1785                 OutputParams tmp_params = features.runparams();
1786                 pdfoptions().writeLaTeX(tmp_params, os,
1787                                         features.isProvided("hyperref"));
1788                 // set back for the rest
1789                 lyxpreamble.clear();
1790                 // correctly break URLs with hyperref and dvi output
1791                 if (features.runparams().flavor == OutputParams::LATEX
1792                     && features.isAvailable("breakurl"))
1793                         lyxpreamble += "\\usepackage{breakurl}\n";
1794         } else if (features.isRequired("nameref"))
1795                 // hyperref loads this automatically
1796                 lyxpreamble += "\\usepackage{nameref}\n";
1797
1798         // bibtopic needs to be loaded after hyperref.
1799         // the dot provides the aux file naming which LyX can detect.
1800         if (features.mustProvide("bibtopic"))
1801                 lyxpreamble += "\\usepackage[dot]{bibtopic}\n";
1802
1803         // Will be surrounded by \makeatletter and \makeatother when not empty
1804         docstring atlyxpreamble;
1805
1806         // Some macros LyX will need
1807         docstring tmppreamble(features.getMacros());
1808
1809         if (!tmppreamble.empty())
1810                 atlyxpreamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1811                         "LyX specific LaTeX commands.\n"
1812                         + tmppreamble + '\n';
1813
1814         // the text class specific preamble
1815         tmppreamble = features.getTClassPreamble();
1816         if (!tmppreamble.empty())
1817                 atlyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1818                         "Textclass specific LaTeX commands.\n"
1819                         + tmppreamble + '\n';
1820
1821         // suppress date if selected
1822         // use \@ifundefined because we cannot be sure that every document class
1823         // has a \date command
1824         if (suppress_date)
1825                 atlyxpreamble += "\\@ifundefined{date}{}{\\date{}}\n";
1826
1827         /* the user-defined preamble */
1828         if (!containsOnly(preamble, " \n\t"))
1829                 // FIXME UNICODE
1830                 atlyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1831                         "User specified LaTeX commands.\n"
1832                         + from_utf8(preamble) + '\n';
1833
1834         // subfig loads internally the LaTeX package "caption". As
1835         // caption is a very popular package, users will load it in
1836         // the preamble. Therefore we must load subfig behind the
1837         // user-defined preamble and check if the caption package was
1838         // loaded or not. For the case that caption is loaded before
1839         // subfig, there is the subfig option "caption=false". This
1840         // option also works when a koma-script class is used and
1841         // koma's own caption commands are used instead of caption. We
1842         // use \PassOptionsToPackage here because the user could have
1843         // already loaded subfig in the preamble.
1844         if (features.isRequired("subfig")) {
1845                 atlyxpreamble += "\\@ifundefined{showcaptionsetup}{}{%\n"
1846                         " \\PassOptionsToPackage{caption=false}{subfig}}\n"
1847                         "\\usepackage{subfig}\n";
1848         }
1849
1850         // Itemize bullet settings need to be last in case the user
1851         // defines their own bullets that use a package included
1852         // in the user-defined preamble -- ARRae
1853         // Actually it has to be done much later than that
1854         // since some packages like frenchb make modifications
1855         // at \begin{document} time -- JMarc
1856         docstring bullets_def;
1857         for (int i = 0; i < 4; ++i) {
1858                 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1859                         if (bullets_def.empty())
1860                                 bullets_def += "\\AtBeginDocument{\n";
1861                         bullets_def += "  \\def\\labelitemi";
1862                         switch (i) {
1863                                 // `i' is one less than the item to modify
1864                         case 0:
1865                                 break;
1866                         case 1:
1867                                 bullets_def += 'i';
1868                                 break;
1869                         case 2:
1870                                 bullets_def += "ii";
1871                                 break;
1872                         case 3:
1873                                 bullets_def += 'v';
1874                                 break;
1875                         }
1876                         bullets_def += '{' +
1877                                 user_defined_bullet(i).getText()
1878                                 + "}\n";
1879                 }
1880         }
1881
1882         if (!bullets_def.empty())
1883                 atlyxpreamble += bullets_def + "}\n\n";
1884
1885         if (!atlyxpreamble.empty())
1886                 lyxpreamble += "\n\\makeatletter\n"
1887                         + atlyxpreamble + "\\makeatother\n\n";
1888
1889         // We try to load babel late, in case it interferes with other packages.
1890         // Jurabib and Hyperref have to be called after babel, though.
1891         if (use_babel && !features.isRequired("jurabib")
1892             && !features.isRequired("hyperref")
1893             && !features.isRequired("vietnamese")
1894             && !features.isRequired("japanese")) {
1895                 // FIXME UNICODE
1896                 lyxpreamble += from_utf8(features.getBabelPresettings());
1897                 lyxpreamble += from_utf8(babelCall(language_options.str(),
1898                                                    features.needBabelLangOptions())) + '\n';
1899                 lyxpreamble += from_utf8(features.getBabelPostsettings());
1900         }
1901
1902         // xunicode needs to be loaded at least after amsmath, amssymb,
1903         // esint and the other packages that provide special glyphs
1904         if (features.runparams().flavor == OutputParams::XETEX)
1905                 lyxpreamble += "\\usepackage{xunicode}\n";
1906
1907         // Polyglossia must be loaded last
1908         if (use_polyglossia) {
1909                 // call the package
1910                 lyxpreamble += "\\usepackage{polyglossia}\n";
1911                 // set the main language
1912                 lyxpreamble += "\\setdefaultlanguage";
1913                 if (!language->polyglossiaOpts().empty())
1914                         lyxpreamble += "[" + from_ascii(language->polyglossiaOpts()) + "]";
1915                 lyxpreamble += "{" + from_ascii(language->polyglossia()) + "}\n";
1916                 // now setup the other languages
1917                 std::map<std::string, std::string> const polylangs =
1918                         features.getPolyglossiaLanguages();
1919                 for (std::map<std::string, std::string>::const_iterator mit = polylangs.begin();
1920                      mit != polylangs.end() ; ++mit) {
1921                         lyxpreamble += "\\setotherlanguage";
1922                         if (!mit->second.empty())
1923                                 lyxpreamble += "[" + from_ascii(mit->second) + "]";
1924                         lyxpreamble += "{" + from_ascii(mit->first) + "}\n";
1925                 }
1926         }
1927
1928         // Load custom language package here
1929         if (features.langPackage() == LaTeXFeatures::LANG_PACK_CUSTOM) {
1930                 if (lang_package == "default")
1931                         lyxpreamble += from_utf8(lyxrc.language_custom_package);
1932                 else
1933                         lyxpreamble += from_utf8(lang_package);
1934                 lyxpreamble += '\n';
1935         }
1936
1937         docstring const i18npreamble =
1938                 features.getTClassI18nPreamble(use_babel, use_polyglossia);
1939         if (!i18npreamble.empty())
1940                 lyxpreamble += i18npreamble + '\n';
1941
1942         os << lyxpreamble;
1943
1944         return use_babel;
1945 }
1946
1947
1948 void BufferParams::useClassDefaults()
1949 {
1950         DocumentClass const & tclass = documentClass();
1951
1952         sides = tclass.sides();
1953         columns = tclass.columns();
1954         pagestyle = tclass.pagestyle();
1955         use_default_options = true;
1956         // Only if class has a ToC hierarchy
1957         if (tclass.hasTocLevels()) {
1958                 secnumdepth = tclass.secnumdepth();
1959                 tocdepth = tclass.tocdepth();
1960         }
1961 }
1962
1963
1964 bool BufferParams::hasClassDefaults() const
1965 {
1966         DocumentClass const & tclass = documentClass();
1967
1968         return sides == tclass.sides()
1969                 && columns == tclass.columns()
1970                 && pagestyle == tclass.pagestyle()
1971                 && use_default_options
1972                 && secnumdepth == tclass.secnumdepth()
1973                 && tocdepth == tclass.tocdepth();
1974 }
1975
1976
1977 DocumentClass const & BufferParams::documentClass() const
1978 {
1979         return *doc_class_.get();
1980 }
1981
1982
1983 DocumentClassConstPtr BufferParams::documentClassPtr() const
1984 {
1985         return doc_class_;
1986 }
1987
1988
1989 void BufferParams::setDocumentClass(DocumentClassConstPtr tc)
1990 {
1991         // evil, but this function is evil
1992         doc_class_ = const_pointer_cast<DocumentClass>(tc);
1993 }
1994
1995
1996 bool BufferParams::setBaseClass(string const & classname)
1997 {
1998         LYXERR(Debug::TCLASS, "setBaseClass: " << classname);
1999         LayoutFileList & bcl = LayoutFileList::get();
2000         if (!bcl.haveClass(classname)) {
2001                 docstring s =
2002                         bformat(_("The layout file:\n"
2003                                 "%1$s\n"
2004                                 "could not be found. A default textclass with default\n"
2005                                 "layouts will be used. LyX will not be able to produce\n"
2006                                 "correct output."),
2007                         from_utf8(classname));
2008                 frontend::Alert::error(_("Document class not found"), s);
2009                 bcl.addEmptyClass(classname);
2010         }
2011
2012         bool const success = bcl[classname].load();
2013         if (!success) {
2014                 docstring s =
2015                         bformat(_("Due to some error in it, the layout file:\n"
2016                                 "%1$s\n"
2017                                 "could not be loaded. A default textclass with default\n"
2018                                 "layouts will be used. LyX will not be able to produce\n"
2019                                 "correct output."),
2020                         from_utf8(classname));
2021                 frontend::Alert::error(_("Could not load class"), s);
2022                 bcl.addEmptyClass(classname);
2023         }
2024
2025         pimpl_->baseClass_ = classname;
2026         layout_modules_.adaptToBaseClass(baseClass(), removed_modules_);
2027         return true;
2028 }
2029
2030
2031 LayoutFile const * BufferParams::baseClass() const
2032 {
2033         if (LayoutFileList::get().haveClass(pimpl_->baseClass_))
2034                 return &(LayoutFileList::get()[pimpl_->baseClass_]);
2035         else
2036                 return 0;
2037 }
2038
2039
2040 LayoutFileIndex const & BufferParams::baseClassID() const
2041 {
2042         return pimpl_->baseClass_;
2043 }
2044
2045
2046 void BufferParams::makeDocumentClass()
2047 {
2048         if (!baseClass())
2049                 return;
2050
2051         LayoutModuleList mods;
2052         LayoutModuleList::iterator it;
2053         LayoutModuleList::iterator en;
2054
2055         it = layout_modules_.begin();
2056         en = layout_modules_.end();
2057         for (; it != en; ++it)
2058                 mods.push_back(*it);
2059         it = cite_engine_.begin();
2060         en = cite_engine_.end();
2061         for (; it != en; ++it)
2062                 mods.push_back(*it);
2063         doc_class_ = getDocumentClass(*baseClass(), mods);
2064
2065         if (!local_layout.empty()) {
2066                 TextClass::ReturnValues success =
2067                         doc_class_->read(local_layout, TextClass::MODULE);
2068                 if (success != TextClass::OK && success != TextClass::OK_OLDFORMAT) {
2069                         docstring const msg = _("Error reading internal layout information");
2070                         frontend::Alert::warning(_("Read Error"), msg);
2071                 }
2072         }
2073 }
2074
2075
2076 bool BufferParams::moduleCanBeAdded(string const & modName) const
2077 {
2078         return cite_engine_.moduleCanBeAdded(modName, baseClass()) &&
2079                 layout_modules_.moduleCanBeAdded(modName, baseClass());
2080 }
2081
2082
2083 bool BufferParams::addLayoutModule(string const & modName)
2084 {
2085         LayoutModuleList::const_iterator it = layout_modules_.begin();
2086         LayoutModuleList::const_iterator end = layout_modules_.end();
2087         for (; it != end; ++it)
2088                 if (*it == modName)
2089                         return false;
2090         layout_modules_.push_back(modName);
2091         return true;
2092 }
2093
2094
2095 string BufferParams::bufferFormat() const
2096 {
2097         string format = documentClass().outputFormat();
2098         if (format == "latex") {
2099                 if (useNonTeXFonts)
2100                         return "xetex";
2101                 if (encoding().package() == Encoding::japanese)
2102                         return "platex";
2103         }
2104         return format;
2105 }
2106
2107
2108 bool BufferParams::isExportable(string const & format) const
2109 {
2110         vector<string> backs = backends();
2111         for (vector<string>::const_iterator it = backs.begin();
2112              it != backs.end(); ++it)
2113                 if (theConverters().isReachable(*it, format))
2114                         return true;
2115         return false;
2116 }
2117
2118
2119 namespace {
2120 bool formatSorter(Format const * lhs, Format const * rhs) {
2121         return _(lhs->prettyname()) < _(rhs->prettyname());
2122 }
2123 }
2124
2125
2126 vector<Format const *> BufferParams::exportableFormats(bool only_viewable) const
2127 {
2128         vector<string> const backs = backends();
2129         set<string> excludes;
2130         if (useNonTeXFonts) {
2131                 excludes.insert("latex");
2132                 excludes.insert("pdflatex");
2133         }
2134         vector<Format const *> result =
2135                 theConverters().getReachable(backs[0], only_viewable, true, excludes);
2136         for (vector<string>::const_iterator it = backs.begin() + 1;
2137              it != backs.end(); ++it) {
2138                 vector<Format const *>  r =
2139                         theConverters().getReachable(*it, only_viewable, false, excludes);
2140                 result.insert(result.end(), r.begin(), r.end());
2141         }
2142         sort(result.begin(), result.end(), formatSorter);
2143         return result;
2144 }
2145
2146
2147 bool BufferParams::isExportableFormat(string const & format) const
2148 {
2149         typedef vector<Format const *> Formats;
2150         Formats formats;
2151         formats = exportableFormats(true);
2152         Formats::const_iterator fit = formats.begin();
2153         Formats::const_iterator end = formats.end();
2154         for (; fit != end ; ++fit) {
2155                 if ((*fit)->name() == format)
2156                         return true;
2157         }
2158         return false;
2159 }
2160
2161
2162 vector<string> BufferParams::backends() const
2163 {
2164         vector<string> v;
2165         string const buffmt = bufferFormat();
2166
2167         // FIXME: Don't hardcode format names here, but use a flag
2168         if (buffmt == "latex") {
2169                 if (!useNonTeXFonts) {
2170                         v.push_back("pdflatex");
2171                         v.push_back("latex");
2172                 }
2173                 v.push_back("luatex");
2174                 v.push_back("dviluatex");
2175                 v.push_back("xetex");
2176         } else if (buffmt == "xetex") {
2177                 v.push_back("xetex");
2178                 v.push_back("luatex");
2179                 v.push_back("dviluatex");
2180         } else
2181                 v.push_back(buffmt);
2182
2183         v.push_back("xhtml");
2184         v.push_back("text");
2185         v.push_back("lyx");
2186         return v;
2187 }
2188
2189
2190 OutputParams::FLAVOR BufferParams::getOutputFlavor(string const format) const
2191 {
2192         string const dformat = (format.empty() || format == "default") ?
2193                 getDefaultOutputFormat() : format;
2194         DefaultFlavorCache::const_iterator it =
2195                 default_flavors_.find(dformat);
2196
2197         if (it != default_flavors_.end())
2198                 return it->second;
2199
2200         OutputParams::FLAVOR result = OutputParams::LATEX;
2201
2202         // FIXME It'd be better not to hardcode this, but to do
2203         //       something with formats.
2204         if (dformat == "xhtml")
2205                 result = OutputParams::HTML;
2206         else if (dformat == "text")
2207                 result = OutputParams::TEXT;
2208         else if (dformat == "lyx")
2209                 result = OutputParams::LYX;
2210         else if (dformat == "pdflatex")
2211                 result = OutputParams::PDFLATEX;
2212         else if (dformat == "xetex")
2213                 result = OutputParams::XETEX;
2214         else if (dformat == "luatex")
2215                 result = OutputParams::LUATEX;
2216         else if (dformat == "dviluatex")
2217                 result = OutputParams::DVILUATEX;
2218         else {
2219                 // Try to determine flavor of default output format
2220                 vector<string> backs = backends();
2221                 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
2222                         // Get shortest path to format
2223                         Graph::EdgePath path;
2224                         for (vector<string>::const_iterator it = backs.begin();
2225                             it != backs.end(); ++it) {
2226                                 Graph::EdgePath p = theConverters().getPath(*it, dformat);
2227                                 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2228                                         path = p;
2229                                 }
2230                         }
2231                         if (!path.empty())
2232                                 result = theConverters().getFlavor(path);
2233                 }
2234         }
2235         // cache this flavor
2236         default_flavors_[dformat] = result;
2237         return result;
2238 }
2239
2240
2241 string BufferParams::getDefaultOutputFormat() const
2242 {
2243         if (!default_output_format.empty()
2244             && default_output_format != "default")
2245                 return default_output_format;
2246         if (isDocBook()
2247             || useNonTeXFonts
2248             || encoding().package() == Encoding::japanese) {
2249                 vector<Format const *> const formats = exportableFormats(true);
2250                 if (formats.empty())
2251                         return string();
2252                 // return the first we find
2253                 return formats.front()->name();
2254         }
2255         return lyxrc.default_view_format;
2256 }
2257
2258 Font const BufferParams::getFont() const
2259 {
2260         FontInfo f = documentClass().defaultfont();
2261         if (fonts_default_family == "rmdefault")
2262                 f.setFamily(ROMAN_FAMILY);
2263         else if (fonts_default_family == "sfdefault")
2264                 f.setFamily(SANS_FAMILY);
2265         else if (fonts_default_family == "ttdefault")
2266                 f.setFamily(TYPEWRITER_FAMILY);
2267         return Font(f, language);
2268 }
2269
2270
2271 InsetQuotes::QuoteLanguage BufferParams::getQuoteStyle(string const qs) const
2272 {
2273         return quoteslangtranslator().find(qs);
2274 }
2275
2276
2277 bool BufferParams::isLatex() const
2278 {
2279         return documentClass().outputType() == LATEX;
2280 }
2281
2282
2283 bool BufferParams::isLiterate() const
2284 {
2285         return documentClass().outputType() == LITERATE;
2286 }
2287
2288
2289 bool BufferParams::isDocBook() const
2290 {
2291         return documentClass().outputType() == DOCBOOK;
2292 }
2293
2294
2295 void BufferParams::readPreamble(Lexer & lex)
2296 {
2297         if (lex.getString() != "\\begin_preamble")
2298                 lyxerr << "Error (BufferParams::readPreamble):"
2299                         "consistency check failed." << endl;
2300
2301         preamble = lex.getLongString("\\end_preamble");
2302 }
2303
2304
2305 void BufferParams::readLocalLayout(Lexer & lex)
2306 {
2307         if (lex.getString() != "\\begin_local_layout")
2308                 lyxerr << "Error (BufferParams::readLocalLayout):"
2309                         "consistency check failed." << endl;
2310
2311         local_layout = lex.getLongString("\\end_local_layout");
2312 }
2313
2314
2315 bool BufferParams::setLanguage(string const & lang)
2316 {
2317         Language const *new_language = languages.getLanguage(lang);
2318         if (!new_language) {
2319                 // Language lang was not found
2320                 return false;
2321         }
2322         language = new_language;
2323         return true;
2324 }
2325
2326
2327 void BufferParams::readLanguage(Lexer & lex)
2328 {
2329         if (!lex.next()) return;
2330
2331         string const tmptok = lex.getString();
2332
2333         // check if tmptok is part of tex_babel in tex-defs.h
2334         if (!setLanguage(tmptok)) {
2335                 // Language tmptok was not found
2336                 language = default_language;
2337                 lyxerr << "Warning: Setting language `"
2338                        << tmptok << "' to `" << language->lang()
2339                        << "'." << endl;
2340         }
2341 }
2342
2343
2344 void BufferParams::readGraphicsDriver(Lexer & lex)
2345 {
2346         if (!lex.next())
2347                 return;
2348
2349         string const tmptok = lex.getString();
2350         // check if tmptok is part of tex_graphics in tex_defs.h
2351         int n = 0;
2352         while (true) {
2353                 string const test = tex_graphics[n++];
2354
2355                 if (test == tmptok) {
2356                         graphics_driver = tmptok;
2357                         break;
2358                 }
2359                 if (test.empty()) {
2360                         lex.printError(
2361                                 "Warning: graphics driver `$$Token' not recognized!\n"
2362                                 "         Setting graphics driver to `default'.\n");
2363                         graphics_driver = "default";
2364                         break;
2365                 }
2366         }
2367 }
2368
2369
2370 void BufferParams::readBullets(Lexer & lex)
2371 {
2372         if (!lex.next())
2373                 return;
2374
2375         int const index = lex.getInteger();
2376         lex.next();
2377         int temp_int = lex.getInteger();
2378         user_defined_bullet(index).setFont(temp_int);
2379         temp_bullet(index).setFont(temp_int);
2380         lex >> temp_int;
2381         user_defined_bullet(index).setCharacter(temp_int);
2382         temp_bullet(index).setCharacter(temp_int);
2383         lex >> temp_int;
2384         user_defined_bullet(index).setSize(temp_int);
2385         temp_bullet(index).setSize(temp_int);
2386 }
2387
2388
2389 void BufferParams::readBulletsLaTeX(Lexer & lex)
2390 {
2391         // The bullet class should be able to read this.
2392         if (!lex.next())
2393                 return;
2394         int const index = lex.getInteger();
2395         lex.next(true);
2396         docstring const temp_str = lex.getDocString();
2397
2398         user_defined_bullet(index).setText(temp_str);
2399         temp_bullet(index).setText(temp_str);
2400 }
2401
2402
2403 void BufferParams::readModules(Lexer & lex)
2404 {
2405         if (!lex.eatLine()) {
2406                 lyxerr << "Error (BufferParams::readModules):"
2407                                 "Unexpected end of input." << endl;
2408                 return;
2409         }
2410         while (true) {
2411                 string mod = lex.getString();
2412                 if (mod == "\\end_modules")
2413                         break;
2414                 addLayoutModule(mod);
2415                 lex.eatLine();
2416         }
2417 }
2418
2419
2420 void BufferParams::readRemovedModules(Lexer & lex)
2421 {
2422         if (!lex.eatLine()) {
2423                 lyxerr << "Error (BufferParams::readRemovedModules):"
2424                                 "Unexpected end of input." << endl;
2425                 return;
2426         }
2427         while (true) {
2428                 string mod = lex.getString();
2429                 if (mod == "\\end_removed_modules")
2430                         break;
2431                 removed_modules_.push_back(mod);
2432                 lex.eatLine();
2433         }
2434         // now we want to remove any removed modules that were previously
2435         // added. normally, that will be because default modules were added in
2436         // setBaseClass(), which gets called when \textclass is read at the
2437         // start of the read.
2438         list<string>::const_iterator rit = removed_modules_.begin();
2439         list<string>::const_iterator const ren = removed_modules_.end();
2440         for (; rit != ren; ++rit) {
2441                 LayoutModuleList::iterator const mit = layout_modules_.begin();
2442                 LayoutModuleList::iterator const men = layout_modules_.end();
2443                 LayoutModuleList::iterator found = find(mit, men, *rit);
2444                 if (found == men)
2445                         continue;
2446                 layout_modules_.erase(found);
2447         }
2448 }
2449
2450
2451 void BufferParams::readIncludeonly(Lexer & lex)
2452 {
2453         if (!lex.eatLine()) {
2454                 lyxerr << "Error (BufferParams::readIncludeonly):"
2455                                 "Unexpected end of input." << endl;
2456                 return;
2457         }
2458         while (true) {
2459                 string child = lex.getString();
2460                 if (child == "\\end_includeonly")
2461                         break;
2462                 included_children_.push_back(child);
2463                 lex.eatLine();
2464         }
2465 }
2466
2467
2468 string BufferParams::paperSizeName(PapersizePurpose purpose) const
2469 {
2470         switch (papersize) {
2471         case PAPER_DEFAULT:
2472                 // could be anything, so don't guess
2473                 return string();
2474         case PAPER_CUSTOM: {
2475                 if (purpose == XDVI && !paperwidth.empty() &&
2476                     !paperheight.empty()) {
2477                         // heightxwidth<unit>
2478                         string first = paperwidth;
2479                         string second = paperheight;
2480                         if (orientation == ORIENTATION_LANDSCAPE)
2481                                 first.swap(second);
2482                         // cut off unit.
2483                         return first.erase(first.length() - 2)
2484                                 + "x" + second;
2485                 }
2486                 return string();
2487         }
2488         case PAPER_A0:
2489                 // dvips and dvipdfm do not know this
2490                 if (purpose == DVIPS || purpose == DVIPDFM)
2491                         return string();
2492                 return "a0";
2493         case PAPER_A1:
2494                 if (purpose == DVIPS || purpose == DVIPDFM)
2495                         return string();
2496                 return "a1";
2497         case PAPER_A2:
2498                 if (purpose == DVIPS || purpose == DVIPDFM)
2499                         return string();
2500                 return "a2";
2501         case PAPER_A3:
2502                 return "a3";
2503         case PAPER_A4:
2504                 return "a4";
2505         case PAPER_A5:
2506                 return "a5";
2507         case PAPER_A6:
2508                 if (purpose == DVIPS || purpose == DVIPDFM)
2509                         return string();
2510                 return "a6";
2511         case PAPER_B0:
2512                 if (purpose == DVIPS || purpose == DVIPDFM)
2513                         return string();
2514                 return "b0";
2515         case PAPER_B1:
2516                 if (purpose == DVIPS || purpose == DVIPDFM)
2517                         return string();
2518                 return "b1";
2519         case PAPER_B2:
2520                 if (purpose == DVIPS || purpose == DVIPDFM)
2521                         return string();
2522                 return "b2";
2523         case PAPER_B3:
2524                 if (purpose == DVIPS || purpose == DVIPDFM)
2525                         return string();
2526                 return "b3";
2527         case PAPER_B4:
2528                 // dvipdfm does not know this
2529                 if (purpose == DVIPDFM)
2530                         return string();
2531                 return "b4";
2532         case PAPER_B5:
2533                 if (purpose == DVIPDFM)
2534                         return string();
2535                 return "b5";
2536         case PAPER_B6:
2537                 if (purpose == DVIPS || purpose == DVIPDFM)
2538                         return string();
2539                 return "b6";
2540         case PAPER_C0:
2541                 if (purpose == DVIPS || purpose == DVIPDFM)
2542                         return string();
2543                 return "c0";
2544         case PAPER_C1:
2545                 if (purpose == DVIPS || purpose == DVIPDFM)
2546                         return string();
2547                 return "c1";
2548         case PAPER_C2:
2549                 if (purpose == DVIPS || purpose == DVIPDFM)
2550                         return string();
2551                 return "c2";
2552         case PAPER_C3:
2553                 if (purpose == DVIPS || purpose == DVIPDFM)
2554                         return string();
2555                 return "c3";
2556         case PAPER_C4:
2557                 if (purpose == DVIPS || purpose == DVIPDFM)
2558                         return string();
2559                 return "c4";
2560         case PAPER_C5:
2561                 if (purpose == DVIPS || purpose == DVIPDFM)
2562                         return string();
2563                 return "c5";
2564         case PAPER_C6:
2565                 if (purpose == DVIPS || purpose == DVIPDFM)
2566                         return string();
2567                 return "c6";
2568         case PAPER_JISB0:
2569                 if (purpose == DVIPS || purpose == DVIPDFM)
2570                         return string();
2571                 return "jisb0";
2572         case PAPER_JISB1:
2573                 if (purpose == DVIPS || purpose == DVIPDFM)
2574                         return string();
2575                 return "jisb1";
2576         case PAPER_JISB2:
2577                 if (purpose == DVIPS || purpose == DVIPDFM)
2578                         return string();
2579                 return "jisb2";
2580         case PAPER_JISB3:
2581                 if (purpose == DVIPS || purpose == DVIPDFM)
2582                         return string();
2583                 return "jisb3";
2584         case PAPER_JISB4:
2585                 if (purpose == DVIPS || purpose == DVIPDFM)
2586                         return string();
2587                 return "jisb4";
2588         case PAPER_JISB5:
2589                 if (purpose == DVIPS || purpose == DVIPDFM)
2590                         return string();
2591                 return "jisb5";
2592         case PAPER_JISB6:
2593                 if (purpose == DVIPS || purpose == DVIPDFM)
2594                         return string();
2595                 return "jisb6";
2596         case PAPER_USEXECUTIVE:
2597                 // dvipdfm does not know this
2598                 if (purpose == DVIPDFM)
2599                         return string();
2600                 return "foolscap";
2601         case PAPER_USLEGAL:
2602                 return "legal";
2603         case PAPER_USLETTER:
2604         default:
2605                 if (purpose == XDVI)
2606                         return "us";
2607                 return "letter";
2608         }
2609 }
2610
2611
2612 string const BufferParams::dvips_options() const
2613 {
2614         string result;
2615
2616         // If the class loads the geometry package, we do not know which
2617         // paper size is used, since we do not set it (bug 7013).
2618         // Therefore we must not specify any argument here.
2619         // dvips gets the correct paper size via DVI specials in this case
2620         // (if the class uses the geometry package correctly).
2621         if (documentClass().provides("geometry"))
2622                 return result;
2623
2624         if (use_geometry
2625             && papersize == PAPER_CUSTOM
2626             && !lyxrc.print_paper_dimension_flag.empty()
2627             && !paperwidth.empty()
2628             && !paperheight.empty()) {
2629                 // using a custom papersize
2630                 result = lyxrc.print_paper_dimension_flag;
2631                 result += ' ' + paperwidth;
2632                 result += ',' + paperheight;
2633         } else {
2634                 string const paper_option = paperSizeName(DVIPS);
2635                 if (!paper_option.empty() && (paper_option != "letter" ||
2636                     orientation != ORIENTATION_LANDSCAPE)) {
2637                         // dvips won't accept -t letter -t landscape.
2638                         // In all other cases, include the paper size
2639                         // explicitly.
2640                         result = lyxrc.print_paper_flag;
2641                         result += ' ' + paper_option;
2642                 }
2643         }
2644         if (orientation == ORIENTATION_LANDSCAPE &&
2645             papersize != PAPER_CUSTOM)
2646                 result += ' ' + lyxrc.print_landscape_flag;
2647         return result;
2648 }
2649
2650
2651 string const BufferParams::font_encoding() const
2652 {
2653         return (fontenc == "global") ? lyxrc.fontenc : fontenc;
2654 }
2655
2656
2657 string BufferParams::babelCall(string const & lang_opts, bool const langoptions) const
2658 {
2659         // suppress the babel call if there is no BabelName defined
2660         // for the document language in the lib/languages file and if no
2661         // other languages are used (lang_opts is then empty)
2662         if (lang_opts.empty())
2663                 return string();
2664         // either a specific language (AsBabelOptions setting in
2665         // lib/languages) or the prefs require the languages to
2666         // be submitted to babel itself (not the class).
2667         if (langoptions)
2668                 return "\\usepackage[" + lang_opts + "]{babel}";
2669         return "\\usepackage{babel}";
2670 }
2671
2672
2673 docstring BufferParams::getGraphicsDriver(string const & package) const
2674 {
2675         docstring result;
2676
2677         if (package == "geometry") {
2678                 if (graphics_driver == "dvips"
2679                     || graphics_driver == "dvipdfm"
2680                     || graphics_driver == "pdftex"
2681                     || graphics_driver == "vtex")
2682                         result = from_ascii(graphics_driver);
2683                 else if (graphics_driver == "dvipdfmx")
2684                         result = from_ascii("dvipdfm");
2685         }
2686
2687         return result;
2688 }
2689
2690
2691 void BufferParams::writeEncodingPreamble(otexstream & os,
2692                                          LaTeXFeatures & features) const
2693 {
2694         // XeTeX does not need this
2695         if (features.runparams().flavor == OutputParams::XETEX)
2696                 return;
2697         // LuaTeX neither, but with tex fonts, we need to load
2698         // the luainputenc package.
2699         if (features.runparams().flavor == OutputParams::LUATEX
2700                 || features.runparams().flavor == OutputParams::DVILUATEX) {
2701                 if (!useNonTeXFonts && inputenc != "default"
2702                     && ((inputenc == "auto" && language->encoding()->package() == Encoding::inputenc)
2703                         || (inputenc != "auto" && encoding().package() == Encoding::inputenc))) {
2704                         os << "\\usepackage[utf8]{luainputenc}\n";
2705                 }
2706                 return;
2707         }
2708         if (inputenc == "auto") {
2709                 string const doc_encoding =
2710                         language->encoding()->latexName();
2711                 Encoding::Package const package =
2712                         language->encoding()->package();
2713
2714                 // Create a list with all the input encodings used
2715                 // in the document
2716                 set<string> encodings =
2717                         features.getEncodingSet(doc_encoding);
2718
2719                 // If the "japanese" package (i.e. pLaTeX) is used,
2720                 // inputenc must be omitted.
2721                 // see http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg129680.html
2722                 if ((!encodings.empty() || package == Encoding::inputenc)
2723                     && !features.isRequired("japanese")) {
2724                         os << "\\usepackage[";
2725                         set<string>::const_iterator it = encodings.begin();
2726                         set<string>::const_iterator const end = encodings.end();
2727                         if (it != end) {
2728                                 os << from_ascii(*it);
2729                                 ++it;
2730                         }
2731                         for (; it != end; ++it)
2732                                 os << ',' << from_ascii(*it);
2733                         if (package == Encoding::inputenc) {
2734                                 if (!encodings.empty())
2735                                         os << ',';
2736                                 os << from_ascii(doc_encoding);
2737                         }
2738                         os << "]{inputenc}\n";
2739                 }
2740                 if (package == Encoding::CJK || features.mustProvide("CJK")) {
2741                         if (language->encoding()->name() == "utf8-cjk"
2742                             && LaTeXFeatures::isAvailable("CJKutf8"))
2743                                 os << "\\usepackage{CJKutf8}\n";
2744                         else
2745                                 os << "\\usepackage{CJK}\n";
2746                 }
2747         } else if (inputenc != "default") {
2748                 switch (encoding().package()) {
2749                 case Encoding::none:
2750                 case Encoding::japanese:
2751                         break;
2752                 case Encoding::inputenc:
2753                         // do not load inputenc if japanese is used
2754                         if (features.isRequired("japanese"))
2755                                 break;
2756                         os << "\\usepackage[" << from_ascii(inputenc)
2757                            << "]{inputenc}\n";
2758                         break;
2759                 case Encoding::CJK:
2760                         if (encoding().name() == "utf8-cjk"
2761                             && LaTeXFeatures::isAvailable("CJKutf8"))
2762                                 os << "\\usepackage{CJKutf8}\n";
2763                         else
2764                                 os << "\\usepackage{CJK}\n";
2765                         break;
2766                 }
2767         }
2768 }
2769
2770
2771 string const BufferParams::parseFontName(string const & name) const
2772 {
2773         string mangled = name;
2774         size_t const idx = mangled.find('[');
2775         if (idx == string::npos || idx == 0)
2776                 return mangled;
2777         else
2778                 return mangled.substr(0, idx - 1);
2779 }
2780
2781
2782 string const BufferParams::loadFonts(LaTeXFeatures & features) const
2783 {
2784         if (fonts_roman == "default" && fonts_sans == "default"
2785             && fonts_typewriter == "default"
2786             && (fonts_math == "default" || fonts_math == "auto"))
2787                 //nothing to do
2788                 return string();
2789
2790         ostringstream os;
2791
2792         /* Fontspec (XeTeX, LuaTeX): we provide GUI support for oldstyle
2793          * numbers (Numbers=OldStyle) and sf/tt scaling. The Ligatures=TeX/
2794          * Mapping=tex-text option assures TeX ligatures (such as "--")
2795          * are resolved. Note that tt does not use these ligatures.
2796          * TODO:
2797          *    -- add more GUI options?
2798          *    -- add more fonts (fonts for other scripts)
2799          *    -- if there's a way to find out if a font really supports
2800          *       OldStyle, enable/disable the widget accordingly.
2801         */
2802         if (useNonTeXFonts && features.isAvailable("fontspec")) {
2803                 // "Mapping=tex-text" and "Ligatures=TeX" are equivalent.
2804                 // However, until v.2 (2010/07/11) fontspec only knew
2805                 // Mapping=tex-text (for XeTeX only); then "Ligatures=TeX"
2806                 // was introduced for both XeTeX and LuaTeX (LuaTeX
2807                 // didn't understand "Mapping=tex-text", while XeTeX
2808                 // understood both. With most recent versions, both
2809                 // variants are understood by both engines. However,
2810                 // we want to provide support for at least TeXLive 2009
2811                 // (for XeTeX; LuaTeX is only supported as of v.2)
2812                 string const texmapping =
2813                         (features.runparams().flavor == OutputParams::XETEX) ?
2814                         "Mapping=tex-text" : "Ligatures=TeX";
2815                 if (fonts_roman != "default") {
2816                         os << "\\setmainfont[" << texmapping;
2817                         if (fonts_old_figures)
2818                                 os << ",Numbers=OldStyle";
2819                         os << "]{" << parseFontName(fonts_roman) << "}\n";
2820                 }
2821                 if (fonts_sans != "default") {
2822                         string const sans = parseFontName(fonts_sans);
2823                         if (fonts_sans_scale != 100)
2824                                 os << "\\setsansfont[Scale="
2825                                    << float(fonts_sans_scale) / 100
2826                                    << "," << texmapping << "]{"
2827                                    << sans << "}\n";
2828                         else
2829                                 os << "\\setsansfont[" << texmapping << "]{"
2830                                    << sans << "}\n";
2831                 }
2832                 if (fonts_typewriter != "default") {
2833                         string const mono = parseFontName(fonts_typewriter);
2834                         if (fonts_typewriter_scale != 100)
2835                                 os << "\\setmonofont[Scale="
2836                                    << float(fonts_typewriter_scale) / 100
2837                                    << "]{"
2838                                    << mono << "}\n";
2839                         else
2840                                 os << "\\setmonofont{"
2841                                    << mono << "}\n";
2842                 }
2843                 return os.str();
2844         }
2845
2846         // Tex Fonts
2847         bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
2848         bool const dryrun = features.runparams().dryrun;
2849         bool const complete = (fonts_sans == "default" && fonts_typewriter == "default");
2850         bool const nomath = (fonts_math == "default");
2851
2852         // ROMAN FONTS
2853         os << theLaTeXFonts().getLaTeXFont(from_ascii(fonts_roman)).getLaTeXCode(
2854                 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
2855                 nomath);
2856
2857         // SANS SERIF
2858         os << theLaTeXFonts().getLaTeXFont(from_ascii(fonts_sans)).getLaTeXCode(
2859                 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
2860                 nomath, fonts_sans_scale);
2861
2862         // MONOSPACED/TYPEWRITER
2863         os << theLaTeXFonts().getLaTeXFont(from_ascii(fonts_typewriter)).getLaTeXCode(
2864                 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
2865                 nomath, fonts_typewriter_scale);
2866
2867         // MATH
2868         os << theLaTeXFonts().getLaTeXFont(from_ascii(fonts_math)).getLaTeXCode(
2869                 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
2870                 nomath);
2871
2872         return os.str();
2873 }
2874
2875
2876 Encoding const & BufferParams::encoding() const
2877 {
2878         // FIXME: actually, we should check for the flavor
2879         // or runparams.isFullyUnicode() here:
2880         // This check will not work with XeTeX/LuaTeX and tex fonts.
2881         // Thus we have to reset the encoding in Buffer::makeLaTeXFile.
2882         if (useNonTeXFonts)
2883                 return *(encodings.fromLaTeXName("utf8-plain"));
2884         if (inputenc == "auto" || inputenc == "default")
2885                 return *language->encoding();
2886         Encoding const * const enc = encodings.fromLaTeXName(inputenc);
2887         if (enc)
2888                 return *enc;
2889         LYXERR0("Unknown inputenc value `" << inputenc
2890                << "'. Using `auto' instead.");
2891         return *language->encoding();
2892 }
2893
2894
2895 bool BufferParams::addCiteEngine(string const & engine)
2896 {
2897         LayoutModuleList::const_iterator it = cite_engine_.begin();
2898         LayoutModuleList::const_iterator en = cite_engine_.end();
2899         for (; it != en; ++it)
2900                 if (*it == engine)
2901                         return false;
2902         cite_engine_.push_back(engine);
2903         return true;
2904 }
2905
2906
2907 bool BufferParams::addCiteEngine(vector<string> const & engine)
2908 {
2909         vector<string>::const_iterator it = engine.begin();
2910         vector<string>::const_iterator en = engine.end();
2911         bool ret = true;
2912         for (; it != en; ++it)
2913                 if (!addCiteEngine(*it))
2914                         ret = false;
2915         return ret;
2916 }
2917
2918
2919 string const & BufferParams::defaultBiblioStyle() const
2920 {
2921         return documentClass().defaultBiblioStyle();
2922 }
2923
2924
2925 bool const & BufferParams::fullAuthorList() const
2926 {
2927         return documentClass().fullAuthorList();
2928 }
2929
2930
2931 void BufferParams::setCiteEngine(string const & engine)
2932 {
2933         clearCiteEngine();
2934         addCiteEngine(engine);
2935 }
2936
2937
2938 void BufferParams::setCiteEngine(vector<string> const & engine)
2939 {
2940         clearCiteEngine();
2941         addCiteEngine(engine);
2942 }
2943
2944
2945 vector<string> BufferParams::citeCommands() const
2946 {
2947         static CitationStyle const default_style;
2948         vector<string> commands =
2949                 documentClass().citeCommands(citeEngineType());
2950         if (commands.empty())
2951                 commands.push_back(default_style.cmd);
2952         return commands;
2953 }
2954
2955
2956 vector<CitationStyle> BufferParams::citeStyles() const
2957 {
2958         static CitationStyle const default_style;
2959         vector<CitationStyle> styles =
2960                 documentClass().citeStyles(citeEngineType());
2961         if (styles.empty())
2962                 styles.push_back(default_style);
2963         return styles;
2964 }
2965
2966 } // namespace lyx