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