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