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