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