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