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