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