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