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