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