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