]> git.lyx.org Git - features.git/blob - src/BufferParams.cpp
Streamify a docstring
[features.git] / src / BufferParams.cpp
1 /**
2  * \file BufferParams.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Martin Vermeer
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "BufferParams.h"
19
20 #include "Author.h"
21 #include "LayoutFile.h"
22 #include "BranchList.h"
23 #include "Buffer.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                 docstring const tmppreamble = rtrim(preamble, "\n");
1086                 os << "\\begin_preamble\n"
1087                    << to_utf8(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         docstring const local_layout = getLocalLayout(false);
1139         if (!local_layout.empty()) {
1140                 // remove '\n' from the end
1141                 docstring const tmplocal = rtrim(local_layout, "\n");
1142                 os << "\\begin_local_layout\n"
1143                    << to_utf8(tmplocal)
1144                    << "\n\\end_local_layout\n";
1145         }
1146         docstring const forced_local_layout = getLocalLayout(true);
1147         if (!forced_local_layout.empty()) {
1148                 // remove '\n' from the end
1149                 docstring const tmplocal = rtrim(forced_local_layout, "\n");
1150                 os << "\\begin_forced_local_layout\n"
1151                    << to_utf8(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         features.resolveAlternatives();
1903         features.expandMultiples();
1904
1905         if (output_sync) {
1906                 if (!output_sync_macro.empty())
1907                         os << from_utf8(output_sync_macro) +"\n";
1908                 else if (features.runparams().flavor == OutputParams::LATEX)
1909                         os << "\\usepackage[active]{srcltx}\n";
1910                 else if (features.runparams().flavor == OutputParams::PDFLATEX)
1911                         os << "\\synctex=-1\n";
1912         }
1913
1914         // The package options (via \PassOptionsToPackage)
1915         os << from_ascii(features.getPackageOptions());
1916
1917         // due to interferences with babel and hyperref, the color package has to
1918         // be loaded (when it is not already loaded) before babel when hyperref
1919         // is used with the colorlinks option, see
1920         // http://www.lyx.org/trac/ticket/5291
1921         // we decided therefore to load color always before babel, see
1922         // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg144349.html
1923         os << from_ascii(features.getColorOptions());
1924
1925         // If we use hyperref, jurabib, japanese, varioref or vietnamese,
1926         // we have to call babel before
1927         if (use_babel
1928             && (features.isRequired("jurabib")
1929                 || features.isRequired("hyperref")
1930                 || features.isRequired("varioref")
1931                 || features.isRequired("vietnamese")
1932                 || features.isRequired("japanese"))) {
1933                         os << features.getBabelPresettings();
1934                         // FIXME UNICODE
1935                         os << from_utf8(babelCall(language_options.str(),
1936                                                   features.needBabelLangOptions())) + '\n';
1937                         os << features.getBabelPostsettings();
1938         }
1939
1940         // The optional packages;
1941         os << from_ascii(features.getPackages());
1942
1943         // Additional Indices
1944         if (features.isRequired("splitidx")) {
1945                 IndicesList::const_iterator iit = indiceslist().begin();
1946                 IndicesList::const_iterator iend = indiceslist().end();
1947                 for (; iit != iend; ++iit) {
1948                         pair<docstring, docstring> indexname_latex =
1949                                 features.runparams().encoding->latexString(iit->index(),
1950                                                                            features.runparams().dryrun);
1951                         if (!indexname_latex.second.empty()) {
1952                                 // issue a warning about omitted characters
1953                                 // FIXME: should be passed to the error dialog
1954                                 frontend::Alert::warning(_("Uncodable characters"),
1955                                         bformat(_("The following characters that are used in an index name are not\n"
1956                                                   "representable in the current encoding and therefore have been omitted:\n%1$s."),
1957                                                 indexname_latex.second));
1958                         }
1959                         os << "\\newindex[";
1960                         os << indexname_latex.first;
1961                         os << "]{";
1962                         os << escape(iit->shortcut());
1963                         os << "}\n";
1964                 }
1965         }
1966
1967         // Line spacing
1968         os << from_utf8(spacing().writePreamble(features.isProvided("SetSpace")));
1969
1970         // PDF support.
1971         // * Hyperref manual: "Make sure it comes last of your loaded
1972         //   packages, to give it a fighting chance of not being over-written,
1973         //   since its job is to redefine many LaTeX commands."
1974         // * Email from Heiko Oberdiek: "It is usually better to load babel
1975         //   before hyperref. Then hyperref has a chance to detect babel.
1976         // * Has to be loaded before the "LyX specific LaTeX commands" to
1977         //   avoid errors with algorithm floats.
1978         // use hyperref explicitly if it is required
1979         if (features.isRequired("hyperref")) {
1980                 OutputParams tmp_params = features.runparams();
1981                 pdfoptions().writeLaTeX(tmp_params, os,
1982                                         features.isProvided("hyperref"));
1983                 // correctly break URLs with hyperref and dvi output
1984                 if (features.runparams().flavor == OutputParams::LATEX
1985                     && features.isAvailable("breakurl"))
1986                         os << "\\usepackage{breakurl}\n";
1987         } else if (features.isRequired("nameref"))
1988                 // hyperref loads this automatically
1989                 os << "\\usepackage{nameref}\n";
1990
1991         // bibtopic needs to be loaded after hyperref.
1992         // the dot provides the aux file naming which LyX can detect.
1993         if (features.mustProvide("bibtopic"))
1994                 os << "\\usepackage[dot]{bibtopic}\n";
1995
1996         // Will be surrounded by \makeatletter and \makeatother when not empty
1997         docstring atlyxpreamble;
1998
1999         // Some macros LyX will need
2000         docstring tmppreamble(features.getMacros());
2001
2002         if (!tmppreamble.empty())
2003                 atlyxpreamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2004                         "LyX specific LaTeX commands.\n"
2005                         + tmppreamble + '\n';
2006
2007         // the text class specific preamble
2008         tmppreamble = features.getTClassPreamble();
2009         if (!tmppreamble.empty())
2010                 atlyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2011                         "Textclass specific LaTeX commands.\n"
2012                         + tmppreamble + '\n';
2013
2014         // suppress date if selected
2015         // use \@ifundefined because we cannot be sure that every document class
2016         // has a \date command
2017         if (suppress_date)
2018                 atlyxpreamble += "\\@ifundefined{date}{}{\\date{}}\n";
2019
2020         /* the user-defined preamble */
2021         if (!containsOnly(preamble, " \n\t")) {
2022                 // FIXME UNICODE
2023                 atlyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2024                         "User specified LaTeX commands.\n";
2025
2026                 // Check if the user preamble contains uncodable glyphs
2027                 odocstringstream user_preamble;
2028                 docstring uncodable_glyphs;
2029                 Encoding const * const enc = features.runparams().encoding;
2030                 if (enc) {
2031                         for (size_t n = 0; n < preamble.size(); ++n) {
2032                                 char_type c = preamble[n];
2033                                 if (!enc->encodable(c)) {
2034                                         docstring const glyph(1, c);
2035                                         LYXERR0("Uncodable character '"
2036                                                 << glyph
2037                                                 << "' in user preamble!");
2038                                         uncodable_glyphs += glyph;
2039                                         if (features.runparams().dryrun) {
2040                                                 user_preamble << "<" << _("LyX Warning: ")
2041                                                    << _("uncodable character") << " '";
2042                                                 user_preamble.put(c);
2043                                                 user_preamble << "'>";
2044                                         }
2045                                 } else
2046                                         user_preamble.put(c);
2047                         }
2048                 } else
2049                         user_preamble << preamble;
2050
2051                 // On BUFFER_VIEW|UPDATE, warn user if we found uncodable glyphs
2052                 if (!features.runparams().dryrun && !uncodable_glyphs.empty()) {
2053                         frontend::Alert::warning(
2054                                 _("Uncodable character in user preamble"),
2055                                 support::bformat(
2056                                   _("The user preamble of your document contains glyphs "
2057                                     "that are unknown in the current document encoding "
2058                                     "(namely %1$s).\nThese glyphs are omitted "
2059                                     " from the output, which may result in "
2060                                     "incomplete output."
2061                                     "\n\nPlease select an appropriate "
2062                                     "document encoding\n"
2063                                     "(such as utf8) or change the "
2064                                     "preamble code accordingly."),
2065                                   uncodable_glyphs));
2066                 }
2067                 atlyxpreamble += user_preamble.str() + '\n';
2068         }
2069
2070         // footmisc must be loaded after setspace
2071         // Load it here to avoid clashes with footmisc loaded in the user
2072         // preamble. For that reason we also pass the options via
2073         // \PassOptionsToPackage in getPreamble() and not here.
2074         if (features.mustProvide("footmisc"))
2075                 atlyxpreamble += "\\usepackage{footmisc}\n";
2076
2077         // subfig loads internally the LaTeX package "caption". As
2078         // caption is a very popular package, users will load it in
2079         // the preamble. Therefore we must load subfig behind the
2080         // user-defined preamble and check if the caption package was
2081         // loaded or not. For the case that caption is loaded before
2082         // subfig, there is the subfig option "caption=false". This
2083         // option also works when a koma-script class is used and
2084         // koma's own caption commands are used instead of caption. We
2085         // use \PassOptionsToPackage here because the user could have
2086         // already loaded subfig in the preamble.
2087         if (features.mustProvide("subfig")) {
2088                 atlyxpreamble += "\\@ifundefined{showcaptionsetup}{}{%\n"
2089                         " \\PassOptionsToPackage{caption=false}{subfig}}\n"
2090                         "\\usepackage{subfig}\n";
2091         }
2092
2093         // Itemize bullet settings need to be last in case the user
2094         // defines their own bullets that use a package included
2095         // in the user-defined preamble -- ARRae
2096         // Actually it has to be done much later than that
2097         // since some packages like frenchb make modifications
2098         // at \begin{document} time -- JMarc
2099         docstring bullets_def;
2100         for (int i = 0; i < 4; ++i) {
2101                 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
2102                         if (bullets_def.empty())
2103                                 bullets_def += "\\AtBeginDocument{\n";
2104                         bullets_def += "  \\def\\labelitemi";
2105                         switch (i) {
2106                                 // `i' is one less than the item to modify
2107                         case 0:
2108                                 break;
2109                         case 1:
2110                                 bullets_def += 'i';
2111                                 break;
2112                         case 2:
2113                                 bullets_def += "ii";
2114                                 break;
2115                         case 3:
2116                                 bullets_def += 'v';
2117                                 break;
2118                         }
2119                         bullets_def += '{' +
2120                                 user_defined_bullet(i).getText()
2121                                 + "}\n";
2122                 }
2123         }
2124
2125         if (!bullets_def.empty())
2126                 atlyxpreamble += bullets_def + "}\n\n";
2127
2128         if (!atlyxpreamble.empty()) {
2129                 os << "\n\\makeatletter\n"
2130                    << atlyxpreamble
2131                    << "\\makeatother\n\n";
2132         }
2133
2134         // We try to load babel late, in case it interferes with other packages.
2135         // Jurabib, hyperref, varioref, bicaption and listings (bug 8995) have to be
2136         // called after babel, though.
2137         if (use_babel && !features.isRequired("jurabib")
2138             && !features.isRequired("hyperref")
2139                 && !features.isRequired("varioref")
2140             && !features.isRequired("vietnamese")
2141             && !features.isRequired("japanese")) {
2142                 os << features.getBabelPresettings();
2143                 // FIXME UNICODE
2144                 os << from_utf8(babelCall(language_options.str(),
2145                                           features.needBabelLangOptions())) + '\n';
2146                 os << features.getBabelPostsettings();
2147         }
2148         if (features.isRequired("bicaption"))
2149                 os << "\\usepackage{bicaption}\n";
2150         if (!listings_params.empty() || features.mustProvide("listings"))
2151                 os << "\\usepackage{listings}\n";
2152         if (!listings_params.empty()) {
2153                 os << "\\lstset{";
2154                 // do not test validity because listings_params is
2155                 // supposed to be valid
2156                 string par =
2157                         InsetListingsParams(listings_params).separatedParams(true);
2158                 os << from_utf8(par);
2159                 os << "}\n";
2160         }
2161
2162         // xunicode needs to be loaded at least after amsmath, amssymb,
2163         // esint and the other packages that provide special glyphs
2164         // The package only supports XeTeX currently.
2165         if (features.runparams().flavor == OutputParams::XETEX
2166             && useNonTeXFonts)
2167                 os << "\\usepackage{xunicode}\n";
2168
2169         // Polyglossia must be loaded last
2170         if (use_polyglossia) {
2171                 // call the package
2172                 os << "\\usepackage{polyglossia}\n";
2173                 // set the main language
2174                 os << "\\setdefaultlanguage";
2175                 if (!language->polyglossiaOpts().empty())
2176                         os << "[" << from_ascii(language->polyglossiaOpts()) << "]";
2177                 os << "{" << from_ascii(language->polyglossia()) << "}\n";
2178                 // now setup the other languages
2179                 std::map<std::string, std::string> const polylangs =
2180                         features.getPolyglossiaLanguages();
2181                 for (std::map<std::string, std::string>::const_iterator mit = polylangs.begin();
2182                      mit != polylangs.end() ; ++mit) {
2183                         os << "\\setotherlanguage";
2184                         if (!mit->second.empty())
2185                                 os << "[" << from_ascii(mit->second) << "]";
2186                         os << "{" << from_ascii(mit->first) << "}\n";
2187                 }
2188         }
2189
2190         // Load custom language package here
2191         if (features.langPackage() == LaTeXFeatures::LANG_PACK_CUSTOM) {
2192                 if (lang_package == "default")
2193                         os << from_utf8(lyxrc.language_custom_package);
2194                 else
2195                         os << from_utf8(lang_package);
2196                 os << '\n';
2197         }
2198
2199         docstring const i18npreamble =
2200                 features.getTClassI18nPreamble(use_babel, use_polyglossia);
2201         if (!i18npreamble.empty())
2202                 os << i18npreamble + '\n';
2203
2204         return use_babel;
2205 }
2206
2207
2208 void BufferParams::useClassDefaults()
2209 {
2210         DocumentClass const & tclass = documentClass();
2211
2212         sides = tclass.sides();
2213         columns = tclass.columns();
2214         pagestyle = tclass.pagestyle();
2215         use_default_options = true;
2216         // Only if class has a ToC hierarchy
2217         if (tclass.hasTocLevels()) {
2218                 secnumdepth = tclass.secnumdepth();
2219                 tocdepth = tclass.tocdepth();
2220         }
2221 }
2222
2223
2224 bool BufferParams::hasClassDefaults() const
2225 {
2226         DocumentClass const & tclass = documentClass();
2227
2228         return sides == tclass.sides()
2229                 && columns == tclass.columns()
2230                 && pagestyle == tclass.pagestyle()
2231                 && use_default_options
2232                 && secnumdepth == tclass.secnumdepth()
2233                 && tocdepth == tclass.tocdepth();
2234 }
2235
2236
2237 DocumentClass const & BufferParams::documentClass() const
2238 {
2239         return *doc_class_;
2240 }
2241
2242
2243 DocumentClassConstPtr BufferParams::documentClassPtr() const
2244 {
2245         return doc_class_;
2246 }
2247
2248
2249 void BufferParams::setDocumentClass(DocumentClassConstPtr tc)
2250 {
2251         // evil, but this function is evil
2252         doc_class_ = const_pointer_cast<DocumentClass>(tc);
2253 }
2254
2255
2256 bool BufferParams::setBaseClass(string const & classname)
2257 {
2258         LYXERR(Debug::TCLASS, "setBaseClass: " << classname);
2259         LayoutFileList & bcl = LayoutFileList::get();
2260         if (!bcl.haveClass(classname)) {
2261                 docstring s =
2262                         bformat(_("The layout file:\n"
2263                                 "%1$s\n"
2264                                 "could not be found. A default textclass with default\n"
2265                                 "layouts will be used. LyX will not be able to produce\n"
2266                                 "correct output."),
2267                         from_utf8(classname));
2268                 frontend::Alert::error(_("Document class not found"), s);
2269                 bcl.addEmptyClass(classname);
2270         }
2271
2272         bool const success = bcl[classname].load();
2273         if (!success) {
2274                 docstring s =
2275                         bformat(_("Due to some error in it, the layout file:\n"
2276                                 "%1$s\n"
2277                                 "could not be loaded. A default textclass with default\n"
2278                                 "layouts will be used. LyX will not be able to produce\n"
2279                                 "correct output."),
2280                         from_utf8(classname));
2281                 frontend::Alert::error(_("Could not load class"), s);
2282                 bcl.addEmptyClass(classname);
2283         }
2284
2285         pimpl_->baseClass_ = classname;
2286         layout_modules_.adaptToBaseClass(baseClass(), removed_modules_);
2287         return true;
2288 }
2289
2290
2291 LayoutFile const * BufferParams::baseClass() const
2292 {
2293         if (LayoutFileList::get().haveClass(pimpl_->baseClass_))
2294                 return &(LayoutFileList::get()[pimpl_->baseClass_]);
2295         else
2296                 return 0;
2297 }
2298
2299
2300 LayoutFileIndex const & BufferParams::baseClassID() const
2301 {
2302         return pimpl_->baseClass_;
2303 }
2304
2305
2306 void BufferParams::makeDocumentClass(bool const clone)
2307 {
2308         if (!baseClass())
2309                 return;
2310
2311         LayoutModuleList mods;
2312         LayoutModuleList::iterator it = layout_modules_.begin();
2313         LayoutModuleList::iterator en = layout_modules_.end();
2314         for (; it != en; ++it)
2315                 mods.push_back(*it);
2316
2317         it = cite_engine_.begin();
2318         en = cite_engine_.end();
2319         for (; it != en; ++it)
2320                 mods.push_back(*it);
2321
2322         doc_class_ = getDocumentClass(*baseClass(), mods, clone);
2323
2324         TextClass::ReturnValues success = TextClass::OK;
2325         if (!forced_local_layout_.empty())
2326                 success = doc_class_->read(to_utf8(forced_local_layout_),
2327                                            TextClass::MODULE);
2328         if (!local_layout_.empty() &&
2329             (success == TextClass::OK || success == TextClass::OK_OLDFORMAT))
2330                 success = doc_class_->read(to_utf8(local_layout_), TextClass::MODULE);
2331         if (success != TextClass::OK && success != TextClass::OK_OLDFORMAT) {
2332                 docstring const msg = _("Error reading internal layout information");
2333                 frontend::Alert::warning(_("Read Error"), msg);
2334         }
2335 }
2336
2337
2338 bool BufferParams::layoutModuleCanBeAdded(string const & modName) const
2339 {
2340         return layout_modules_.moduleCanBeAdded(modName, baseClass());
2341 }
2342
2343
2344 bool BufferParams::citationModuleCanBeAdded(string const & modName) const
2345 {
2346         return cite_engine_.moduleCanBeAdded(modName, baseClass());
2347 }
2348
2349
2350 docstring BufferParams::getLocalLayout(bool forced) const
2351 {
2352         if (forced)
2353                 return from_utf8(doc_class_->forcedLayouts());
2354         else
2355                 return local_layout_;
2356 }
2357
2358
2359 void BufferParams::setLocalLayout(docstring const & layout, bool forced)
2360 {
2361         if (forced)
2362                 forced_local_layout_ = layout;
2363         else
2364                 local_layout_ = layout;
2365 }
2366
2367
2368 bool BufferParams::addLayoutModule(string const & modName)
2369 {
2370         LayoutModuleList::const_iterator it = layout_modules_.begin();
2371         LayoutModuleList::const_iterator end = layout_modules_.end();
2372         for (; it != end; ++it)
2373                 if (*it == modName)
2374                         return false;
2375         layout_modules_.push_back(modName);
2376         return true;
2377 }
2378
2379
2380 string BufferParams::bufferFormat() const
2381 {
2382         return documentClass().outputFormat();
2383 }
2384
2385
2386 bool BufferParams::isExportable(string const & format) const
2387 {
2388         vector<string> backs = backends();
2389         for (vector<string>::const_iterator it = backs.begin();
2390              it != backs.end(); ++it)
2391                 if (theConverters().isReachable(*it, format))
2392                         return true;
2393         return false;
2394 }
2395
2396
2397 vector<Format const *> BufferParams::exportableFormats(bool only_viewable) const
2398 {
2399         vector<string> const backs = backends();
2400         set<string> excludes;
2401         if (useNonTeXFonts) {
2402                 excludes.insert("latex");
2403                 excludes.insert("pdflatex");
2404         }
2405         vector<Format const *> result =
2406                 theConverters().getReachable(backs[0], only_viewable, true, excludes);
2407         for (vector<string>::const_iterator it = backs.begin() + 1;
2408              it != backs.end(); ++it) {
2409                 vector<Format const *>  r =
2410                         theConverters().getReachable(*it, only_viewable, false, excludes);
2411                 result.insert(result.end(), r.begin(), r.end());
2412         }
2413         return result;
2414 }
2415
2416
2417 bool BufferParams::isExportableFormat(string const & format) const
2418 {
2419         typedef vector<Format const *> Formats;
2420         Formats formats;
2421         formats = exportableFormats(true);
2422         Formats::const_iterator fit = formats.begin();
2423         Formats::const_iterator end = formats.end();
2424         for (; fit != end ; ++fit) {
2425                 if ((*fit)->name() == format)
2426                         return true;
2427         }
2428         return false;
2429 }
2430
2431
2432 vector<string> BufferParams::backends() const
2433 {
2434         vector<string> v;
2435         string const buffmt = bufferFormat();
2436
2437         // FIXME: Don't hardcode format names here, but use a flag
2438         if (buffmt == "latex") {
2439                 if (encoding().package() == Encoding::japanese)
2440                         v.push_back("platex");
2441                 else {
2442                         if (!useNonTeXFonts) {
2443                                 v.push_back("pdflatex");
2444                                 v.push_back("latex");
2445                         }
2446                         v.push_back("xetex");
2447                         v.push_back("luatex");
2448                         v.push_back("dviluatex");
2449                 }
2450         } else
2451                 v.push_back(buffmt);
2452
2453         v.push_back("xhtml");
2454         v.push_back("text");
2455         v.push_back("lyx");
2456         return v;
2457 }
2458
2459
2460 OutputParams::FLAVOR BufferParams::getOutputFlavor(string const & format) const
2461 {
2462         string const dformat = (format.empty() || format == "default") ?
2463                 getDefaultOutputFormat() : format;
2464         DefaultFlavorCache::const_iterator it =
2465                 default_flavors_.find(dformat);
2466
2467         if (it != default_flavors_.end())
2468                 return it->second;
2469
2470         OutputParams::FLAVOR result = OutputParams::LATEX;
2471
2472         // FIXME It'd be better not to hardcode this, but to do
2473         //       something with formats.
2474         if (dformat == "xhtml")
2475                 result = OutputParams::HTML;
2476         else if (dformat == "text")
2477                 result = OutputParams::TEXT;
2478         else if (dformat == "lyx")
2479                 result = OutputParams::LYX;
2480         else if (dformat == "pdflatex")
2481                 result = OutputParams::PDFLATEX;
2482         else if (dformat == "xetex")
2483                 result = OutputParams::XETEX;
2484         else if (dformat == "luatex")
2485                 result = OutputParams::LUATEX;
2486         else if (dformat == "dviluatex")
2487                 result = OutputParams::DVILUATEX;
2488         else {
2489                 // Try to determine flavor of default output format
2490                 vector<string> backs = backends();
2491                 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
2492                         // Get shortest path to format
2493                         Graph::EdgePath path;
2494                         for (vector<string>::const_iterator it = backs.begin();
2495                             it != backs.end(); ++it) {
2496                                 Graph::EdgePath p = theConverters().getPath(*it, dformat);
2497                                 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2498                                         path = p;
2499                                 }
2500                         }
2501                         if (!path.empty())
2502                                 result = theConverters().getFlavor(path);
2503                 }
2504         }
2505         // cache this flavor
2506         default_flavors_[dformat] = result;
2507         return result;
2508 }
2509
2510
2511 string BufferParams::getDefaultOutputFormat() const
2512 {
2513         if (!default_output_format.empty()
2514             && default_output_format != "default")
2515                 return default_output_format;
2516         if (isDocBook()
2517             || encoding().package() == Encoding::japanese) {
2518                 vector<Format const *> const formats = exportableFormats(true);
2519                 if (formats.empty())
2520                         return string();
2521                 // return the first we find
2522                 return formats.front()->name();
2523         }
2524         if (useNonTeXFonts)
2525                 return lyxrc.default_otf_view_format;
2526         return lyxrc.default_view_format;
2527 }
2528
2529 Font const BufferParams::getFont() const
2530 {
2531         FontInfo f = documentClass().defaultfont();
2532         if (fonts_default_family == "rmdefault")
2533                 f.setFamily(ROMAN_FAMILY);
2534         else if (fonts_default_family == "sfdefault")
2535                 f.setFamily(SANS_FAMILY);
2536         else if (fonts_default_family == "ttdefault")
2537                 f.setFamily(TYPEWRITER_FAMILY);
2538         return Font(f, language);
2539 }
2540
2541
2542 InsetQuotes::QuoteLanguage BufferParams::getQuoteStyle(string const & qs) const
2543 {
2544         return quoteslangtranslator().find(qs);
2545 }
2546
2547
2548 bool BufferParams::isLatex() const
2549 {
2550         return documentClass().outputType() == LATEX;
2551 }
2552
2553
2554 bool BufferParams::isLiterate() const
2555 {
2556         return documentClass().outputType() == LITERATE;
2557 }
2558
2559
2560 bool BufferParams::isDocBook() const
2561 {
2562         return documentClass().outputType() == DOCBOOK;
2563 }
2564
2565
2566 void BufferParams::readPreamble(Lexer & lex)
2567 {
2568         if (lex.getString() != "\\begin_preamble")
2569                 lyxerr << "Error (BufferParams::readPreamble):"
2570                         "consistency check failed." << endl;
2571
2572         preamble = lex.getLongString(from_ascii("\\end_preamble"));
2573 }
2574
2575
2576 void BufferParams::readLocalLayout(Lexer & lex, bool forced)
2577 {
2578         string const expected = forced ? "\\begin_forced_local_layout" :
2579                                          "\\begin_local_layout";
2580         if (lex.getString() != expected)
2581                 lyxerr << "Error (BufferParams::readLocalLayout):"
2582                         "consistency check failed." << endl;
2583
2584         if (forced)
2585                 forced_local_layout_ =
2586                         lex.getLongString(from_ascii("\\end_forced_local_layout"));
2587         else
2588                 local_layout_ = lex.getLongString(from_ascii("\\end_local_layout"));
2589 }
2590
2591
2592 bool BufferParams::setLanguage(string const & lang)
2593 {
2594         Language const *new_language = languages.getLanguage(lang);
2595         if (!new_language) {
2596                 // Language lang was not found
2597                 return false;
2598         }
2599         language = new_language;
2600         return true;
2601 }
2602
2603
2604 void BufferParams::readLanguage(Lexer & lex)
2605 {
2606         if (!lex.next()) return;
2607
2608         string const tmptok = lex.getString();
2609
2610         // check if tmptok is part of tex_babel in tex-defs.h
2611         if (!setLanguage(tmptok)) {
2612                 // Language tmptok was not found
2613                 language = default_language;
2614                 lyxerr << "Warning: Setting language `"
2615                        << tmptok << "' to `" << language->lang()
2616                        << "'." << endl;
2617         }
2618 }
2619
2620
2621 void BufferParams::readGraphicsDriver(Lexer & lex)
2622 {
2623         if (!lex.next())
2624                 return;
2625
2626         string const tmptok = lex.getString();
2627         // check if tmptok is part of tex_graphics in tex_defs.h
2628         int n = 0;
2629         while (true) {
2630                 string const test = tex_graphics[n++];
2631
2632                 if (test == tmptok) {
2633                         graphics_driver = tmptok;
2634                         break;
2635                 }
2636                 if (test.empty()) {
2637                         lex.printError(
2638                                 "Warning: graphics driver `$$Token' not recognized!\n"
2639                                 "         Setting graphics driver to `default'.\n");
2640                         graphics_driver = "default";
2641                         break;
2642                 }
2643         }
2644 }
2645
2646
2647 void BufferParams::readBullets(Lexer & lex)
2648 {
2649         if (!lex.next())
2650                 return;
2651
2652         int const index = lex.getInteger();
2653         lex.next();
2654         int temp_int = lex.getInteger();
2655         user_defined_bullet(index).setFont(temp_int);
2656         temp_bullet(index).setFont(temp_int);
2657         lex >> temp_int;
2658         user_defined_bullet(index).setCharacter(temp_int);
2659         temp_bullet(index).setCharacter(temp_int);
2660         lex >> temp_int;
2661         user_defined_bullet(index).setSize(temp_int);
2662         temp_bullet(index).setSize(temp_int);
2663 }
2664
2665
2666 void BufferParams::readBulletsLaTeX(Lexer & lex)
2667 {
2668         // The bullet class should be able to read this.
2669         if (!lex.next())
2670                 return;
2671         int const index = lex.getInteger();
2672         lex.next(true);
2673         docstring const temp_str = lex.getDocString();
2674
2675         user_defined_bullet(index).setText(temp_str);
2676         temp_bullet(index).setText(temp_str);
2677 }
2678
2679
2680 void BufferParams::readModules(Lexer & lex)
2681 {
2682         if (!lex.eatLine()) {
2683                 lyxerr << "Error (BufferParams::readModules):"
2684                                 "Unexpected end of input." << endl;
2685                 return;
2686         }
2687         while (true) {
2688                 string mod = lex.getString();
2689                 if (mod == "\\end_modules")
2690                         break;
2691                 addLayoutModule(mod);
2692                 lex.eatLine();
2693         }
2694 }
2695
2696
2697 void BufferParams::readRemovedModules(Lexer & lex)
2698 {
2699         if (!lex.eatLine()) {
2700                 lyxerr << "Error (BufferParams::readRemovedModules):"
2701                                 "Unexpected end of input." << endl;
2702                 return;
2703         }
2704         while (true) {
2705                 string mod = lex.getString();
2706                 if (mod == "\\end_removed_modules")
2707                         break;
2708                 removed_modules_.push_back(mod);
2709                 lex.eatLine();
2710         }
2711         // now we want to remove any removed modules that were previously
2712         // added. normally, that will be because default modules were added in
2713         // setBaseClass(), which gets called when \textclass is read at the
2714         // start of the read.
2715         list<string>::const_iterator rit = removed_modules_.begin();
2716         list<string>::const_iterator const ren = removed_modules_.end();
2717         for (; rit != ren; ++rit) {
2718                 LayoutModuleList::iterator const mit = layout_modules_.begin();
2719                 LayoutModuleList::iterator const men = layout_modules_.end();
2720                 LayoutModuleList::iterator found = find(mit, men, *rit);
2721                 if (found == men)
2722                         continue;
2723                 layout_modules_.erase(found);
2724         }
2725 }
2726
2727
2728 void BufferParams::readIncludeonly(Lexer & lex)
2729 {
2730         if (!lex.eatLine()) {
2731                 lyxerr << "Error (BufferParams::readIncludeonly):"
2732                                 "Unexpected end of input." << endl;
2733                 return;
2734         }
2735         while (true) {
2736                 string child = lex.getString();
2737                 if (child == "\\end_includeonly")
2738                         break;
2739                 included_children_.push_back(child);
2740                 lex.eatLine();
2741         }
2742 }
2743
2744
2745 string BufferParams::paperSizeName(PapersizePurpose purpose) const
2746 {
2747         switch (papersize) {
2748         case PAPER_DEFAULT:
2749                 // could be anything, so don't guess
2750                 return string();
2751         case PAPER_CUSTOM: {
2752                 if (purpose == XDVI && !paperwidth.empty() &&
2753                     !paperheight.empty()) {
2754                         // heightxwidth<unit>
2755                         string first = paperwidth;
2756                         string second = paperheight;
2757                         if (orientation == ORIENTATION_LANDSCAPE)
2758                                 first.swap(second);
2759                         // cut off unit.
2760                         return first.erase(first.length() - 2)
2761                                 + "x" + second;
2762                 }
2763                 return string();
2764         }
2765         case PAPER_A0:
2766                 // dvips and dvipdfm do not know this
2767                 if (purpose == DVIPS || purpose == DVIPDFM)
2768                         return string();
2769                 return "a0";
2770         case PAPER_A1:
2771                 if (purpose == DVIPS || purpose == DVIPDFM)
2772                         return string();
2773                 return "a1";
2774         case PAPER_A2:
2775                 if (purpose == DVIPS || purpose == DVIPDFM)
2776                         return string();
2777                 return "a2";
2778         case PAPER_A3:
2779                 return "a3";
2780         case PAPER_A4:
2781                 return "a4";
2782         case PAPER_A5:
2783                 return "a5";
2784         case PAPER_A6:
2785                 if (purpose == DVIPS || purpose == DVIPDFM)
2786                         return string();
2787                 return "a6";
2788         case PAPER_B0:
2789                 if (purpose == DVIPS || purpose == DVIPDFM)
2790                         return string();
2791                 return "b0";
2792         case PAPER_B1:
2793                 if (purpose == DVIPS || purpose == DVIPDFM)
2794                         return string();
2795                 return "b1";
2796         case PAPER_B2:
2797                 if (purpose == DVIPS || purpose == DVIPDFM)
2798                         return string();
2799                 return "b2";
2800         case PAPER_B3:
2801                 if (purpose == DVIPS || purpose == DVIPDFM)
2802                         return string();
2803                 return "b3";
2804         case PAPER_B4:
2805                 // dvipdfm does not know this
2806                 if (purpose == DVIPDFM)
2807                         return string();
2808                 return "b4";
2809         case PAPER_B5:
2810                 if (purpose == DVIPDFM)
2811                         return string();
2812                 return "b5";
2813         case PAPER_B6:
2814                 if (purpose == DVIPS || purpose == DVIPDFM)
2815                         return string();
2816                 return "b6";
2817         case PAPER_C0:
2818                 if (purpose == DVIPS || purpose == DVIPDFM)
2819                         return string();
2820                 return "c0";
2821         case PAPER_C1:
2822                 if (purpose == DVIPS || purpose == DVIPDFM)
2823                         return string();
2824                 return "c1";
2825         case PAPER_C2:
2826                 if (purpose == DVIPS || purpose == DVIPDFM)
2827                         return string();
2828                 return "c2";
2829         case PAPER_C3:
2830                 if (purpose == DVIPS || purpose == DVIPDFM)
2831                         return string();
2832                 return "c3";
2833         case PAPER_C4:
2834                 if (purpose == DVIPS || purpose == DVIPDFM)
2835                         return string();
2836                 return "c4";
2837         case PAPER_C5:
2838                 if (purpose == DVIPS || purpose == DVIPDFM)
2839                         return string();
2840                 return "c5";
2841         case PAPER_C6:
2842                 if (purpose == DVIPS || purpose == DVIPDFM)
2843                         return string();
2844                 return "c6";
2845         case PAPER_JISB0:
2846                 if (purpose == DVIPS || purpose == DVIPDFM)
2847                         return string();
2848                 return "jisb0";
2849         case PAPER_JISB1:
2850                 if (purpose == DVIPS || purpose == DVIPDFM)
2851                         return string();
2852                 return "jisb1";
2853         case PAPER_JISB2:
2854                 if (purpose == DVIPS || purpose == DVIPDFM)
2855                         return string();
2856                 return "jisb2";
2857         case PAPER_JISB3:
2858                 if (purpose == DVIPS || purpose == DVIPDFM)
2859                         return string();
2860                 return "jisb3";
2861         case PAPER_JISB4:
2862                 if (purpose == DVIPS || purpose == DVIPDFM)
2863                         return string();
2864                 return "jisb4";
2865         case PAPER_JISB5:
2866                 if (purpose == DVIPS || purpose == DVIPDFM)
2867                         return string();
2868                 return "jisb5";
2869         case PAPER_JISB6:
2870                 if (purpose == DVIPS || purpose == DVIPDFM)
2871                         return string();
2872                 return "jisb6";
2873         case PAPER_USEXECUTIVE:
2874                 // dvipdfm does not know this
2875                 if (purpose == DVIPDFM)
2876                         return string();
2877                 return "foolscap";
2878         case PAPER_USLEGAL:
2879                 return "legal";
2880         case PAPER_USLETTER:
2881         default:
2882                 if (purpose == XDVI)
2883                         return "us";
2884                 return "letter";
2885         }
2886 }
2887
2888
2889 string const BufferParams::dvips_options() const
2890 {
2891         string result;
2892
2893         // If the class loads the geometry package, we do not know which
2894         // paper size is used, since we do not set it (bug 7013).
2895         // Therefore we must not specify any argument here.
2896         // dvips gets the correct paper size via DVI specials in this case
2897         // (if the class uses the geometry package correctly).
2898         if (documentClass().provides("geometry"))
2899                 return result;
2900
2901         if (use_geometry
2902             && papersize == PAPER_CUSTOM
2903             && !lyxrc.print_paper_dimension_flag.empty()
2904             && !paperwidth.empty()
2905             && !paperheight.empty()) {
2906                 // using a custom papersize
2907                 result = lyxrc.print_paper_dimension_flag;
2908                 result += ' ' + paperwidth;
2909                 result += ',' + paperheight;
2910         } else {
2911                 string const paper_option = paperSizeName(DVIPS);
2912                 if (!paper_option.empty() && (paper_option != "letter" ||
2913                     orientation != ORIENTATION_LANDSCAPE)) {
2914                         // dvips won't accept -t letter -t landscape.
2915                         // In all other cases, include the paper size
2916                         // explicitly.
2917                         result = lyxrc.print_paper_flag;
2918                         result += ' ' + paper_option;
2919                 }
2920         }
2921         if (orientation == ORIENTATION_LANDSCAPE &&
2922             papersize != PAPER_CUSTOM)
2923                 result += ' ' + lyxrc.print_landscape_flag;
2924         return result;
2925 }
2926
2927
2928 string const BufferParams::font_encoding() const
2929 {
2930         return font_encodings().empty() ? "default" : font_encodings().back();
2931 }
2932
2933
2934 vector<string> const BufferParams::font_encodings() const
2935 {
2936         string doc_fontenc = (fontenc == "global") ? lyxrc.fontenc : fontenc;
2937
2938         vector<string> fontencs;
2939
2940         // "default" means "no explicit font encoding"
2941         if (doc_fontenc != "default") {
2942                 fontencs = getVectorFromString(doc_fontenc);
2943                 if (!language->fontenc().empty()
2944                     && ascii_lowercase(language->fontenc()) != "none") {
2945                         vector<string> fencs = getVectorFromString(language->fontenc());
2946                         vector<string>::const_iterator fit = fencs.begin();
2947                         for (; fit != fencs.end(); ++fit) {
2948                                 if (find(fontencs.begin(), fontencs.end(), *fit) == fontencs.end())
2949                                         fontencs.push_back(*fit);
2950                         }
2951                 }
2952         }
2953
2954         return fontencs;
2955 }
2956
2957
2958 string BufferParams::babelCall(string const & lang_opts, bool const langoptions) const
2959 {
2960         // suppress the babel call if there is no BabelName defined
2961         // for the document language in the lib/languages file and if no
2962         // other languages are used (lang_opts is then empty)
2963         if (lang_opts.empty())
2964                 return string();
2965         // either a specific language (AsBabelOptions setting in
2966         // lib/languages) or the prefs require the languages to
2967         // be submitted to babel itself (not the class).
2968         if (langoptions)
2969                 return "\\usepackage[" + lang_opts + "]{babel}";
2970         return "\\usepackage{babel}";
2971 }
2972
2973
2974 docstring BufferParams::getGraphicsDriver(string const & package) const
2975 {
2976         docstring result;
2977
2978         if (package == "geometry") {
2979                 if (graphics_driver == "dvips"
2980                     || graphics_driver == "dvipdfm"
2981                     || graphics_driver == "pdftex"
2982                     || graphics_driver == "vtex")
2983                         result = from_ascii(graphics_driver);
2984                 else if (graphics_driver == "dvipdfmx")
2985                         result = from_ascii("dvipdfm");
2986         }
2987
2988         return result;
2989 }
2990
2991
2992 void BufferParams::writeEncodingPreamble(otexstream & os,
2993                                          LaTeXFeatures & features) const
2994 {
2995         // XeTeX/LuaTeX: (see also #9740)
2996         // With Unicode fonts we use utf8-plain without encoding package.
2997         // With TeX fonts, we cannot use utf8-plain, but "inputenc" fails.
2998         // XeTeX must use ASCII encoding (see Buffer.cpp),
2999         //  for LuaTeX, we load "luainputenc" (see below).
3000         if (useNonTeXFonts || features.runparams().flavor == OutputParams::XETEX)
3001                 return;
3002
3003         if (inputenc == "auto") {
3004                 string const doc_encoding =
3005                         language->encoding()->latexName();
3006                 Encoding::Package const package =
3007                         language->encoding()->package();
3008
3009                 // Create list of inputenc options:
3010                 set<string> encodings;
3011                 // luainputenc fails with more than one encoding
3012                 if (!features.runparams().isFullUnicode()) // if we reach this point, this means LuaTeX with TeX fonts
3013                         // list all input encodings used in the document
3014                         encodings = features.getEncodingSet(doc_encoding);
3015
3016                 // If the "japanese" package (i.e. pLaTeX) is used,
3017                 // inputenc must be omitted.
3018                 // see http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg129680.html
3019                 if ((!encodings.empty() || package == Encoding::inputenc)
3020                     && !features.isRequired("japanese")
3021                     && !features.isProvided("inputenc")) {
3022                         os << "\\usepackage[";
3023                         set<string>::const_iterator it = encodings.begin();
3024                         set<string>::const_iterator const end = encodings.end();
3025                         if (it != end) {
3026                                 os << from_ascii(*it);
3027                                 ++it;
3028                         }
3029                         for (; it != end; ++it)
3030                                 os << ',' << from_ascii(*it);
3031                         if (package == Encoding::inputenc) {
3032                                 if (!encodings.empty())
3033                                         os << ',';
3034                                 os << from_ascii(doc_encoding);
3035                         }
3036                         if (features.runparams().flavor == OutputParams::LUATEX
3037                             || features.runparams().flavor == OutputParams::DVILUATEX)
3038                                 os << "]{luainputenc}\n";
3039                         else
3040                                 os << "]{inputenc}\n";
3041                 }
3042                 if (package == Encoding::CJK || features.mustProvide("CJK")) {
3043                         if (language->encoding()->name() == "utf8-cjk"
3044                             && LaTeXFeatures::isAvailable("CJKutf8"))
3045                                 os << "\\usepackage{CJKutf8}\n";
3046                         else
3047                                 os << "\\usepackage{CJK}\n";
3048                 }
3049         } else if (inputenc != "default") {
3050                 switch (encoding().package()) {
3051                 case Encoding::none:
3052                 case Encoding::japanese:
3053                         break;
3054                 case Encoding::inputenc:
3055                         // do not load inputenc if japanese is used
3056                         // or if the class provides inputenc
3057                         if (features.isRequired("japanese")
3058                             || features.isProvided("inputenc"))
3059                                 break;
3060                         os << "\\usepackage[" << from_ascii(encoding().latexName());
3061                         if (features.runparams().flavor == OutputParams::LUATEX
3062                             || features.runparams().flavor == OutputParams::DVILUATEX)
3063                                 os << "]{luainputenc}\n";
3064                         else
3065                                 os << "]{inputenc}\n";
3066                         break;
3067                 case Encoding::CJK:
3068                         if (encoding().name() == "utf8-cjk"
3069                             && LaTeXFeatures::isAvailable("CJKutf8"))
3070                                 os << "\\usepackage{CJKutf8}\n";
3071                         else
3072                                 os << "\\usepackage{CJK}\n";
3073                         break;
3074                 }
3075                 // Load the CJK package if needed by a secondary language.
3076                 // If the main encoding is some variant of UTF8, use CJKutf8.
3077                 if (encoding().package() != Encoding::CJK && features.mustProvide("CJK")) {
3078                         if (encoding().iconvName() == "UTF-8"
3079                             && LaTeXFeatures::isAvailable("CJKutf8"))
3080                                 os << "\\usepackage{CJKutf8}\n";
3081                         else
3082                                 os << "\\usepackage{CJK}\n";
3083                 }
3084         }
3085 }
3086
3087
3088 string const BufferParams::parseFontName(string const & name) const
3089 {
3090         string mangled = name;
3091         size_t const idx = mangled.find('[');
3092         if (idx == string::npos || idx == 0)
3093                 return mangled;
3094         else
3095                 return mangled.substr(0, idx - 1);
3096 }
3097
3098
3099 string const BufferParams::loadFonts(LaTeXFeatures & features) const
3100 {
3101         if (fontsRoman() == "default" && fontsSans() == "default"
3102             && fontsTypewriter() == "default"
3103             && (fontsMath() == "default" || fontsMath() == "auto"))
3104                 //nothing to do
3105                 return string();
3106
3107         ostringstream os;
3108
3109         /* Fontspec (XeTeX, LuaTeX): we provide GUI support for oldstyle
3110          * numbers (Numbers=OldStyle) and sf/tt scaling. The Ligatures=TeX/
3111          * Mapping=tex-text option assures TeX ligatures (such as "--")
3112          * are resolved. Note that tt does not use these ligatures.
3113          * TODO:
3114          *    -- add more GUI options?
3115          *    -- add more fonts (fonts for other scripts)
3116          *    -- if there's a way to find out if a font really supports
3117          *       OldStyle, enable/disable the widget accordingly.
3118         */
3119         if (useNonTeXFonts && features.isAvailable("fontspec")) {
3120                 // "Mapping=tex-text" and "Ligatures=TeX" are equivalent.
3121                 // However, until v.2 (2010/07/11) fontspec only knew
3122                 // Mapping=tex-text (for XeTeX only); then "Ligatures=TeX"
3123                 // was introduced for both XeTeX and LuaTeX (LuaTeX
3124                 // didn't understand "Mapping=tex-text", while XeTeX
3125                 // understood both. With most recent versions, both
3126                 // variants are understood by both engines. However,
3127                 // we want to provide support for at least TeXLive 2009
3128                 // (for XeTeX; LuaTeX is only supported as of v.2)
3129                 string const texmapping =
3130                         (features.runparams().flavor == OutputParams::XETEX) ?
3131                         "Mapping=tex-text" : "Ligatures=TeX";
3132                 if (fontsRoman() != "default") {
3133                         os << "\\setmainfont[" << texmapping;
3134                         if (fonts_old_figures)
3135                                 os << ",Numbers=OldStyle";
3136                         os << "]{" << parseFontName(fontsRoman()) << "}\n";
3137                 }
3138                 if (fontsSans() != "default") {
3139                         string const sans = parseFontName(fontsSans());
3140                         if (fontsSansScale() != 100)
3141                                 os << "\\setsansfont[Scale="
3142                                    << float(fontsSansScale()) / 100
3143                                    << "," << texmapping << "]{"
3144                                    << sans << "}\n";
3145                         else
3146                                 os << "\\setsansfont[" << texmapping << "]{"
3147                                    << sans << "}\n";
3148                 }
3149                 if (fontsTypewriter() != "default") {
3150                         string const mono = parseFontName(fontsTypewriter());
3151                         if (fontsTypewriterScale() != 100)
3152                                 os << "\\setmonofont[Scale="
3153                                    << float(fontsTypewriterScale()) / 100
3154                                    << "]{"
3155                                    << mono << "}\n";
3156                         else
3157                                 os << "\\setmonofont{"
3158                                    << mono << "}\n";
3159                 }
3160                 return os.str();
3161         }
3162
3163         // Tex Fonts
3164         bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
3165         bool const dryrun = features.runparams().dryrun;
3166         bool const complete = (fontsSans() == "default" && fontsTypewriter() == "default");
3167         bool const nomath = (fontsMath() == "default");
3168
3169         // ROMAN FONTS
3170         os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsRoman())).getLaTeXCode(
3171                 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3172                 nomath);
3173
3174         // SANS SERIF
3175         os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsSans())).getLaTeXCode(
3176                 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3177                 nomath, fontsSansScale());
3178
3179         // MONOSPACED/TYPEWRITER
3180         os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsTypewriter())).getLaTeXCode(
3181                 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3182                 nomath, fontsTypewriterScale());
3183
3184         // MATH
3185         os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getLaTeXCode(
3186                 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3187                 nomath);
3188
3189         return os.str();
3190 }
3191
3192
3193 Encoding const & BufferParams::encoding() const
3194 {
3195         // Main encoding for LaTeX output.
3196         // 
3197         // Exception: XeTeX with 8-bit TeX fonts requires ASCII (see #9740).
3198         // As the "flavor" is only known once export started, this
3199         // cannot be handled here. Instead, runparams.encoding is set
3200         // to ASCII in Buffer::makeLaTeXFile (for export)
3201         // and Buffer::writeLaTeXSource (for preview).
3202         if (useNonTeXFonts)
3203                 return *(encodings.fromLyXName("utf8-plain"));
3204         if (inputenc == "auto" || inputenc == "default")
3205                 return *language->encoding();
3206         Encoding const * const enc = encodings.fromLyXName(inputenc);
3207         if (enc)
3208                 return *enc;
3209         LYXERR0("Unknown inputenc value `" << inputenc
3210                << "'. Using `auto' instead.");
3211         return *language->encoding();
3212 }
3213
3214
3215 bool BufferParams::addCiteEngine(string const & engine)
3216 {
3217         LayoutModuleList::const_iterator it = cite_engine_.begin();
3218         LayoutModuleList::const_iterator en = cite_engine_.end();
3219         for (; it != en; ++it)
3220                 if (*it == engine)
3221                         return false;
3222         cite_engine_.push_back(engine);
3223         return true;
3224 }
3225
3226
3227 bool BufferParams::addCiteEngine(vector<string> const & engine)
3228 {
3229         vector<string>::const_iterator it = engine.begin();
3230         vector<string>::const_iterator en = engine.end();
3231         bool ret = true;
3232         for (; it != en; ++it)
3233                 if (!addCiteEngine(*it))
3234                         ret = false;
3235         return ret;
3236 }
3237
3238
3239 string const & BufferParams::defaultBiblioStyle() const
3240 {
3241         return documentClass().defaultBiblioStyle();
3242 }
3243
3244
3245 bool const & BufferParams::fullAuthorList() const
3246 {
3247         return documentClass().fullAuthorList();
3248 }
3249
3250
3251 void BufferParams::setCiteEngine(string const & engine)
3252 {
3253         clearCiteEngine();
3254         addCiteEngine(engine);
3255 }
3256
3257
3258 void BufferParams::setCiteEngine(vector<string> const & engine)
3259 {
3260         clearCiteEngine();
3261         addCiteEngine(engine);
3262 }
3263
3264
3265 vector<string> BufferParams::citeCommands() const
3266 {
3267         static CitationStyle const default_style;
3268         vector<string> commands =
3269                 documentClass().citeCommands(citeEngineType());
3270         if (commands.empty())
3271                 commands.push_back(default_style.cmd);
3272         return commands;
3273 }
3274
3275
3276 vector<CitationStyle> BufferParams::citeStyles() const
3277 {
3278         static CitationStyle const default_style;
3279         vector<CitationStyle> styles =
3280                 documentClass().citeStyles(citeEngineType());
3281         if (styles.empty())
3282                 styles.push_back(default_style);
3283         return styles;
3284 }
3285
3286 } // namespace lyx