2 * \file BufferParams.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
11 * \author Martin Vermeer
13 * Full author contact details are available in file CREDITS.
18 #include "BufferParams.h"
21 #include "LayoutFile.h"
22 #include "BranchList.h"
24 #include "buffer_funcs.h"
28 #include "Converter.h"
31 #include "IndicesList.h"
33 #include "LaTeXFeatures.h"
34 #include "LaTeXFonts.h"
35 #include "ModuleList.h"
39 #include "OutputParams.h"
41 #include "texstream.h"
44 #include "PDFOptions.h"
46 #include "frontends/alert.h"
48 #include "insets/InsetListingsParams.h"
50 #include "support/convert.h"
51 #include "support/debug.h"
52 #include "support/docstream.h"
53 #include "support/FileName.h"
54 #include "support/filetools.h"
55 #include "support/gettext.h"
56 #include "support/Messages.h"
57 #include "support/mutex.h"
58 #include "support/Package.h"
59 #include "support/Translator.h"
60 #include "support/lstrings.h"
66 using namespace lyx::support;
69 static char const * const string_paragraph_separation[] = {
74 static char const * const string_quotes_language[] = {
75 "english", "swedish", "german", "polish", "french", "danish", ""
79 static char const * const string_papersize[] = {
80 "default", "custom", "letterpaper", "legalpaper", "executivepaper",
81 "a0paper", "a1paper", "a2paper", "a3paper", "a4paper", "a5paper",
82 "a6paper", "b0paper", "b1paper", "b2paper","b3paper", "b4paper",
83 "b5paper", "b6paper", "c0paper", "c1paper", "c2paper", "c3paper",
84 "c4paper", "c5paper", "c6paper", "b0j", "b1j", "b2j", "b3j", "b4j", "b5j",
89 static char const * const string_orientation[] = {
90 "portrait", "landscape", ""
94 static char const * const tex_graphics[] = {
95 "default", "dvialw", "dvilaser", "dvipdf", "dvipdfm", "dvipdfmx",
96 "dvips", "dvipsone", "dvitops", "dviwin", "dviwindo", "dvi2ps", "emtex",
97 "ln", "oztex", "pctexhp", "pctexps", "pctexwin", "pctex32", "pdftex",
98 "psprint", "pubps", "tcidvi", "textures", "truetex", "vtex", "xdvi",
109 // Paragraph separation
110 typedef Translator<string, BufferParams::ParagraphSeparation> ParSepTranslator;
113 ParSepTranslator const init_parseptranslator()
115 ParSepTranslator translator
116 (string_paragraph_separation[0], BufferParams::ParagraphIndentSeparation);
117 translator.addPair(string_paragraph_separation[1], BufferParams::ParagraphSkipSeparation);
122 ParSepTranslator const & parseptranslator()
124 static ParSepTranslator const translator =
125 init_parseptranslator();
131 typedef Translator<string, InsetQuotes::QuoteLanguage> QuotesLangTranslator;
134 QuotesLangTranslator const init_quoteslangtranslator()
136 QuotesLangTranslator translator
137 (string_quotes_language[0], InsetQuotes::EnglishQuotes);
138 translator.addPair(string_quotes_language[1], InsetQuotes::SwedishQuotes);
139 translator.addPair(string_quotes_language[2], InsetQuotes::GermanQuotes);
140 translator.addPair(string_quotes_language[3], InsetQuotes::PolishQuotes);
141 translator.addPair(string_quotes_language[4], InsetQuotes::FrenchQuotes);
142 translator.addPair(string_quotes_language[5], InsetQuotes::DanishQuotes);
147 QuotesLangTranslator const & quoteslangtranslator()
149 static QuotesLangTranslator const translator =
150 init_quoteslangtranslator();
156 typedef Translator<string, PAPER_SIZE> PaperSizeTranslator;
159 static PaperSizeTranslator initPaperSizeTranslator()
161 PaperSizeTranslator translator(string_papersize[0], PAPER_DEFAULT);
162 translator.addPair(string_papersize[1], PAPER_CUSTOM);
163 translator.addPair(string_papersize[2], PAPER_USLETTER);
164 translator.addPair(string_papersize[3], PAPER_USLEGAL);
165 translator.addPair(string_papersize[4], PAPER_USEXECUTIVE);
166 translator.addPair(string_papersize[5], PAPER_A0);
167 translator.addPair(string_papersize[6], PAPER_A1);
168 translator.addPair(string_papersize[7], PAPER_A2);
169 translator.addPair(string_papersize[8], PAPER_A3);
170 translator.addPair(string_papersize[9], PAPER_A4);
171 translator.addPair(string_papersize[10], PAPER_A5);
172 translator.addPair(string_papersize[11], PAPER_A6);
173 translator.addPair(string_papersize[12], PAPER_B0);
174 translator.addPair(string_papersize[13], PAPER_B1);
175 translator.addPair(string_papersize[14], PAPER_B2);
176 translator.addPair(string_papersize[15], PAPER_B3);
177 translator.addPair(string_papersize[16], PAPER_B4);
178 translator.addPair(string_papersize[17], PAPER_B5);
179 translator.addPair(string_papersize[18], PAPER_B6);
180 translator.addPair(string_papersize[19], PAPER_C0);
181 translator.addPair(string_papersize[20], PAPER_C1);
182 translator.addPair(string_papersize[21], PAPER_C2);
183 translator.addPair(string_papersize[22], PAPER_C3);
184 translator.addPair(string_papersize[23], PAPER_C4);
185 translator.addPair(string_papersize[24], PAPER_C5);
186 translator.addPair(string_papersize[25], PAPER_C6);
187 translator.addPair(string_papersize[26], PAPER_JISB0);
188 translator.addPair(string_papersize[27], PAPER_JISB1);
189 translator.addPair(string_papersize[28], PAPER_JISB2);
190 translator.addPair(string_papersize[29], PAPER_JISB3);
191 translator.addPair(string_papersize[30], PAPER_JISB4);
192 translator.addPair(string_papersize[31], PAPER_JISB5);
193 translator.addPair(string_papersize[32], PAPER_JISB6);
198 PaperSizeTranslator const & papersizetranslator()
200 static PaperSizeTranslator const translator =
201 initPaperSizeTranslator();
207 typedef Translator<string, PAPER_ORIENTATION> PaperOrientationTranslator;
210 PaperOrientationTranslator const init_paperorientationtranslator()
212 PaperOrientationTranslator translator(string_orientation[0], ORIENTATION_PORTRAIT);
213 translator.addPair(string_orientation[1], ORIENTATION_LANDSCAPE);
218 PaperOrientationTranslator const & paperorientationtranslator()
220 static PaperOrientationTranslator const translator =
221 init_paperorientationtranslator();
227 typedef Translator<int, PageSides> SidesTranslator;
230 SidesTranslator const init_sidestranslator()
232 SidesTranslator translator(1, OneSide);
233 translator.addPair(2, TwoSides);
238 SidesTranslator const & sidestranslator()
240 static SidesTranslator const translator = init_sidestranslator();
246 typedef Translator<int, BufferParams::Package> PackageTranslator;
249 PackageTranslator const init_packagetranslator()
251 PackageTranslator translator(0, BufferParams::package_off);
252 translator.addPair(1, BufferParams::package_auto);
253 translator.addPair(2, BufferParams::package_on);
258 PackageTranslator const & packagetranslator()
260 static PackageTranslator const translator =
261 init_packagetranslator();
267 typedef Translator<string, CiteEngineType> CiteEngineTypeTranslator;
270 CiteEngineTypeTranslator const init_citeenginetypetranslator()
272 CiteEngineTypeTranslator translator("authoryear", ENGINE_TYPE_AUTHORYEAR);
273 translator.addPair("numerical", ENGINE_TYPE_NUMERICAL);
274 translator.addPair("default", ENGINE_TYPE_DEFAULT);
279 CiteEngineTypeTranslator const & citeenginetypetranslator()
281 static CiteEngineTypeTranslator const translator =
282 init_citeenginetypetranslator();
288 typedef Translator<string, Spacing::Space> SpaceTranslator;
291 SpaceTranslator const init_spacetranslator()
293 SpaceTranslator translator("default", Spacing::Default);
294 translator.addPair("single", Spacing::Single);
295 translator.addPair("onehalf", Spacing::Onehalf);
296 translator.addPair("double", Spacing::Double);
297 translator.addPair("other", Spacing::Other);
302 SpaceTranslator const & spacetranslator()
304 static SpaceTranslator const translator = init_spacetranslator();
309 bool inSystemDir(FileName const & document_dir, string & system_dir)
311 // A document is assumed to be in a system LyX directory (not
312 // necessarily the system directory of the running instance)
313 // if both "configure.py" and "chkconfig.ltx" are found in
314 // either document_dir/../ or document_dir/../../.
315 // If true, the system directory path is returned in system_dir
316 // with a trailing path separator.
318 string const msg = "Checking whether document is in a system dir...";
320 string dir = document_dir.absFileName();
322 for (int i = 0; i < 2; ++i) {
323 dir = addPath(dir, "..");
324 if (!fileSearch(dir, "configure.py").empty() &&
325 !fileSearch(dir, "chkconfig.ltx").empty()) {
326 LYXERR(Debug::FILES, msg << " yes");
327 system_dir = addPath(FileName(dir).realPath(), "");
332 LYXERR(Debug::FILES, msg << " no");
333 system_dir = string();
340 class BufferParams::Impl
345 AuthorList authorlist;
346 BranchList branchlist;
347 Bullet temp_bullets[4];
348 Bullet user_defined_bullets[4];
349 IndicesList indiceslist;
351 /** This is the amount of space used for paragraph_separation "skip",
352 * and for detached paragraphs in "indented" documents.
356 PDFOptions pdfoptions;
357 LayoutFileIndex baseClass_;
361 BufferParams::Impl::Impl()
362 : defskip(VSpace::MEDSKIP), baseClass_(string(""))
364 // set initial author
366 authorlist.record(Author(from_utf8(lyxrc.user_name), from_utf8(lyxrc.user_email)));
371 BufferParams::MemoryTraits::clone(BufferParams::Impl const * ptr)
374 return new BufferParams::Impl(*ptr);
378 void BufferParams::MemoryTraits::destroy(BufferParams::Impl * ptr)
384 BufferParams::BufferParams()
387 setBaseClass(defaultBaseclass());
388 cite_engine_.push_back("basic");
389 cite_engine_type_ = ENGINE_TYPE_DEFAULT;
391 paragraph_separation = ParagraphIndentSeparation;
392 quotes_language = InsetQuotes::EnglishQuotes;
393 fontsize = "default";
396 papersize = PAPER_DEFAULT;
397 orientation = ORIENTATION_PORTRAIT;
398 use_geometry = false;
399 biblio_style = "plain";
400 use_bibtopic = false;
402 save_transient_properties = true;
403 track_changes = false;
404 output_changes = false;
405 use_default_options = true;
406 maintain_unincluded_children = false;
409 language = default_language;
411 fonts_roman[0] = "default";
412 fonts_roman[1] = "default";
413 fonts_sans[0] = "default";
414 fonts_sans[1] = "default";
415 fonts_typewriter[0] = "default";
416 fonts_typewriter[1] = "default";
417 fonts_math[0] = "auto";
418 fonts_math[1] = "auto";
419 fonts_default_family = "default";
420 useNonTeXFonts = false;
421 use_microtype = false;
422 fonts_expert_sc = false;
423 fonts_old_figures = false;
424 fonts_sans_scale[0] = 100;
425 fonts_sans_scale[1] = 100;
426 fonts_typewriter_scale[0] = 100;
427 fonts_typewriter_scale[1] = 100;
429 lang_package = "default";
430 graphics_driver = "default";
431 default_output_format = "default";
432 bibtex_command = "default";
433 index_command = "default";
436 listings_params = string();
437 pagestyle = "default";
438 suppress_date = false;
439 justification = true;
440 // no color is the default (white)
441 backgroundcolor = lyx::rgbFromHexName("#ffffff");
442 isbackgroundcolor = false;
443 // no color is the default (black)
444 fontcolor = lyx::rgbFromHexName("#000000");
446 // light gray is the default font color for greyed-out notes
447 notefontcolor = lyx::rgbFromHexName("#cccccc");
448 boxbgcolor = lyx::rgbFromHexName("#ff0000");
449 compressed = lyxrc.save_compressed;
450 for (int iter = 0; iter < 4; ++iter) {
451 user_defined_bullet(iter) = ITEMIZE_DEFAULTS[iter];
452 temp_bullet(iter) = ITEMIZE_DEFAULTS[iter];
455 indiceslist().addDefault(B_("Index"));
456 html_be_strict = false;
457 html_math_output = MathML;
458 html_math_img_scale = 1.0;
459 html_css_as_file = false;
460 display_pixel_ratio = 1.0;
465 // map current author
466 author_map_[pimpl_->authorlist.get(0).bufferId()] = 0;
470 docstring BufferParams::B_(string const & l10n) const
472 LASSERT(language, return from_utf8(l10n));
473 return getMessages(language->code()).get(l10n);
477 BufferParams::Package BufferParams::use_package(std::string const & p) const
479 PackageMap::const_iterator it = use_packages.find(p);
480 if (it == use_packages.end())
486 void BufferParams::use_package(std::string const & p, BufferParams::Package u)
492 map<string, string> const & BufferParams::auto_packages()
494 static map<string, string> packages;
495 if (packages.empty()) {
496 // We could have a race condition here that two threads
497 // discover an empty map at the same time and want to fill
498 // it, but that is no problem, since the same contents is
499 // filled in twice then. Having the locker inside the
500 // packages.empty() condition has the advantage that we
501 // don't need the mutex overhead for simple reading.
503 Mutex::Locker locker(&mutex);
504 // adding a package here implies a file format change!
505 packages["amsmath"] =
506 N_("The LaTeX package amsmath is only used if AMS formula types or symbols from the AMS math toolbars are inserted into formulas");
507 packages["amssymb"] =
508 N_("The LaTeX package amssymb is only used if symbols from the AMS math toolbars are inserted into formulas");
510 N_("The LaTeX package cancel is only used if \\cancel commands are used in formulas");
512 N_("The LaTeX package esint is only used if special integral symbols are inserted into formulas");
513 packages["mathdots"] =
514 N_("The LaTeX package mathdots is only used if the command \\iddots is inserted into formulas");
515 packages["mathtools"] =
516 N_("The LaTeX package mathtools is only used if some mathematical relations are inserted into formulas");
518 N_("The LaTeX package mhchem is only used if either the command \\ce or \\cf is inserted into formulas");
519 packages["stackrel"] =
520 N_("The LaTeX package stackrel is only used if the command \\stackrel with subscript is inserted into formulas");
521 packages["stmaryrd"] =
522 N_("The LaTeX package stmaryrd is only used if symbols from the St Mary's Road symbol font for theoretical computer science are inserted into formulas");
523 packages["undertilde"] =
524 N_("The LaTeX package undertilde is only used if you use the math frame decoration 'utilde'");
530 AuthorList & BufferParams::authors()
532 return pimpl_->authorlist;
536 AuthorList const & BufferParams::authors() const
538 return pimpl_->authorlist;
542 void BufferParams::addAuthor(Author a)
544 author_map_[a.bufferId()] = pimpl_->authorlist.record(a);
548 BranchList & BufferParams::branchlist()
550 return pimpl_->branchlist;
554 BranchList const & BufferParams::branchlist() const
556 return pimpl_->branchlist;
560 IndicesList & BufferParams::indiceslist()
562 return pimpl_->indiceslist;
566 IndicesList const & BufferParams::indiceslist() const
568 return pimpl_->indiceslist;
572 Bullet & BufferParams::temp_bullet(lyx::size_type const index)
574 LASSERT(index < 4, return pimpl_->temp_bullets[0]);
575 return pimpl_->temp_bullets[index];
579 Bullet const & BufferParams::temp_bullet(lyx::size_type const index) const
581 LASSERT(index < 4, return pimpl_->temp_bullets[0]);
582 return pimpl_->temp_bullets[index];
586 Bullet & BufferParams::user_defined_bullet(lyx::size_type const index)
588 LASSERT(index < 4, return pimpl_->temp_bullets[0]);
589 return pimpl_->user_defined_bullets[index];
593 Bullet const & BufferParams::user_defined_bullet(lyx::size_type const index) const
595 LASSERT(index < 4, return pimpl_->temp_bullets[0]);
596 return pimpl_->user_defined_bullets[index];
600 Spacing & BufferParams::spacing()
602 return pimpl_->spacing;
606 Spacing const & BufferParams::spacing() const
608 return pimpl_->spacing;
612 PDFOptions & BufferParams::pdfoptions()
614 return pimpl_->pdfoptions;
618 PDFOptions const & BufferParams::pdfoptions() const
620 return pimpl_->pdfoptions;
624 HSpace const & BufferParams::getIndentation() const
626 return pimpl_->indentation;
630 void BufferParams::setIndentation(HSpace const & indent)
632 pimpl_->indentation = indent;
636 VSpace const & BufferParams::getDefSkip() const
638 return pimpl_->defskip;
642 void BufferParams::setDefSkip(VSpace const & vs)
644 // DEFSKIP will cause an infinite loop
645 LASSERT(vs.kind() != VSpace::DEFSKIP, return);
646 pimpl_->defskip = vs;
650 string BufferParams::readToken(Lexer & lex, string const & token,
651 FileName const & filepath)
655 if (token == "\\textclass") {
657 string const classname = lex.getString();
658 // if there exists a local layout file, ignore the system one
659 // NOTE: in this case, the textclass (.cls file) is assumed to
662 LayoutFileList & bcl = LayoutFileList::get();
663 if (!filepath.empty()) {
664 // If classname is an absolute path, the document is
665 // using a local layout file which could not be accessed
666 // by a relative path. In this case the path is correct
667 // even if the document was moved to a different
668 // location. However, we will have a problem if the
669 // document was generated on a different platform.
670 bool isabsolute = FileName::isAbsolute(classname);
671 string const classpath = onlyPath(classname);
672 string const path = isabsolute ? classpath
673 : FileName(addPath(filepath.absFileName(),
674 classpath)).realPath();
675 string const oldpath = isabsolute ? string()
676 : FileName(addPath(origin, classpath)).realPath();
677 tcp = bcl.addLocalLayout(onlyFileName(classname), path, oldpath);
679 // that returns non-empty if a "local" layout file is found.
681 result = to_utf8(makeRelPath(from_utf8(onlyPath(tcp)),
682 from_utf8(filepath.absFileName())));
685 setBaseClass(onlyFileName(tcp));
687 setBaseClass(onlyFileName(classname));
688 // We assume that a tex class exists for local or unknown
689 // layouts so this warning, will only be given for system layouts.
690 if (!baseClass()->isTeXClassAvailable()) {
691 docstring const desc =
692 translateIfPossible(from_utf8(baseClass()->description()));
693 docstring const prereqs =
694 from_utf8(baseClass()->prerequisites());
695 docstring const msg =
696 bformat(_("The selected document class\n"
698 "requires external files that are not available.\n"
699 "The document class can still be used, but the\n"
700 "document cannot be compiled until the following\n"
701 "prerequisites are installed:\n"
703 "See section 3.1.2.2 (Class Availability) of the\n"
704 "User's Guide for more information."), desc, prereqs);
705 frontend::Alert::warning(_("Document class not available"),
708 } else if (token == "\\save_transient_properties") {
709 lex >> save_transient_properties;
710 } else if (token == "\\origin") {
712 origin = lex.getString();
713 string const sysdirprefix = "/systemlyxdir/";
714 if (prefixIs(origin, sysdirprefix)) {
716 if (inSystemDir(filepath, docsys))
717 origin.replace(0, sysdirprefix.length() - 1, docsys);
719 origin.replace(0, sysdirprefix.length() - 1,
720 package().system_support().absFileName());
722 } else if (token == "\\begin_preamble") {
724 } else if (token == "\\begin_local_layout") {
725 readLocalLayout(lex, false);
726 } else if (token == "\\begin_forced_local_layout") {
727 readLocalLayout(lex, true);
728 } else if (token == "\\begin_modules") {
730 } else if (token == "\\begin_removed_modules") {
731 readRemovedModules(lex);
732 } else if (token == "\\begin_includeonly") {
733 readIncludeonly(lex);
734 } else if (token == "\\maintain_unincluded_children") {
735 lex >> maintain_unincluded_children;
736 } else if (token == "\\options") {
738 options = lex.getString();
739 } else if (token == "\\use_default_options") {
740 lex >> use_default_options;
741 } else if (token == "\\master") {
743 master = lex.getString();
744 if (!filepath.empty() && FileName::isAbsolute(origin)) {
745 bool const isabs = FileName::isAbsolute(master);
746 FileName const abspath(isabs ? master : origin + master);
747 bool const moved = filepath != FileName(origin);
748 if (moved && abspath.exists()) {
749 docstring const path = isabs
751 : from_utf8(abspath.realPath());
752 docstring const refpath =
753 from_utf8(filepath.absFileName());
754 master = to_utf8(makeRelPath(path, refpath));
757 } else if (token == "\\suppress_date") {
758 lex >> suppress_date;
759 } else if (token == "\\justification") {
760 lex >> justification;
761 } else if (token == "\\language") {
763 } else if (token == "\\language_package") {
765 lang_package = lex.getString();
766 } else if (token == "\\inputencoding") {
768 } else if (token == "\\graphics") {
769 readGraphicsDriver(lex);
770 } else if (token == "\\default_output_format") {
771 lex >> default_output_format;
772 } else if (token == "\\bibtex_command") {
774 bibtex_command = lex.getString();
775 } else if (token == "\\index_command") {
777 index_command = lex.getString();
778 } else if (token == "\\fontencoding") {
780 fontenc = lex.getString();
781 } else if (token == "\\font_roman") {
782 lex >> fonts_roman[0];
783 lex >> fonts_roman[1];
784 } else if (token == "\\font_sans") {
785 lex >> fonts_sans[0];
786 lex >> fonts_sans[1];
787 } else if (token == "\\font_typewriter") {
788 lex >> fonts_typewriter[0];
789 lex >> fonts_typewriter[1];
790 } else if (token == "\\font_math") {
791 lex >> fonts_math[0];
792 lex >> fonts_math[1];
793 } else if (token == "\\font_default_family") {
794 lex >> fonts_default_family;
795 } else if (token == "\\use_non_tex_fonts") {
796 lex >> useNonTeXFonts;
797 } else if (token == "\\font_sc") {
798 lex >> fonts_expert_sc;
799 } else if (token == "\\font_osf") {
800 lex >> fonts_old_figures;
801 } else if (token == "\\font_sf_scale") {
802 lex >> fonts_sans_scale[0];
803 lex >> fonts_sans_scale[1];
804 } else if (token == "\\font_tt_scale") {
805 lex >> fonts_typewriter_scale[0];
806 lex >> fonts_typewriter_scale[1];
807 } else if (token == "\\font_cjk") {
809 } else if (token == "\\use_microtype") {
810 lex >> use_microtype;
811 } else if (token == "\\paragraph_separation") {
814 paragraph_separation = parseptranslator().find(parsep);
815 } else if (token == "\\paragraph_indentation") {
817 string indentation = lex.getString();
818 pimpl_->indentation = HSpace(indentation);
819 } else if (token == "\\defskip") {
821 string const defskip = lex.getString();
822 pimpl_->defskip = VSpace(defskip);
823 if (pimpl_->defskip.kind() == VSpace::DEFSKIP)
825 pimpl_->defskip = VSpace(VSpace::MEDSKIP);
826 } else if (token == "\\quotes_language") {
829 quotes_language = quoteslangtranslator().find(quotes_lang);
830 } else if (token == "\\papersize") {
833 papersize = papersizetranslator().find(ppsize);
834 } else if (token == "\\use_geometry") {
836 } else if (token == "\\use_package") {
841 use_package(package, packagetranslator().find(use));
842 } else if (token == "\\cite_engine") {
844 vector<string> engine = getVectorFromString(lex.getString());
845 setCiteEngine(engine);
846 } else if (token == "\\cite_engine_type") {
849 cite_engine_type_ = citeenginetypetranslator().find(engine_type);
850 } else if (token == "\\biblio_style") {
852 biblio_style = lex.getString();
853 } else if (token == "\\use_bibtopic") {
855 } else if (token == "\\use_indices") {
857 } else if (token == "\\tracking_changes") {
858 lex >> track_changes;
859 } else if (token == "\\output_changes") {
860 lex >> output_changes;
861 } else if (token == "\\branch") {
863 docstring branch = lex.getDocString();
864 branchlist().add(branch);
867 string const tok = lex.getString();
868 if (tok == "\\end_branch")
870 Branch * branch_ptr = branchlist().find(branch);
871 if (tok == "\\selected") {
874 branch_ptr->setSelected(lex.getInteger());
876 if (tok == "\\filename_suffix") {
879 branch_ptr->setFileNameSuffix(lex.getInteger());
881 if (tok == "\\color") {
883 string color = lex.getString();
885 branch_ptr->setColor(color);
886 // Update also the Color table:
888 color = lcolor.getX11Name(Color_background);
890 lcolor.setColor(to_utf8(branch), color);
893 } else if (token == "\\index") {
895 docstring index = lex.getDocString();
897 indiceslist().add(index);
900 string const tok = lex.getString();
901 if (tok == "\\end_index")
903 Index * index_ptr = indiceslist().find(index);
904 if (tok == "\\shortcut") {
906 shortcut = lex.getDocString();
908 index_ptr->setShortcut(shortcut);
910 if (tok == "\\color") {
912 string color = lex.getString();
914 index_ptr->setColor(color);
915 // Update also the Color table:
917 color = lcolor.getX11Name(Color_background);
919 if (!shortcut.empty())
920 lcolor.setColor(to_utf8(shortcut), color);
923 } else if (token == "\\author") {
925 istringstream ss(lex.getString());
929 } else if (token == "\\paperorientation") {
932 orientation = paperorientationtranslator().find(orient);
933 } else if (token == "\\backgroundcolor") {
935 backgroundcolor = lyx::rgbFromHexName(lex.getString());
936 isbackgroundcolor = true;
937 } else if (token == "\\fontcolor") {
939 fontcolor = lyx::rgbFromHexName(lex.getString());
941 } else if (token == "\\notefontcolor") {
943 string color = lex.getString();
944 notefontcolor = lyx::rgbFromHexName(color);
945 lcolor.setColor("notefontcolor", color);
946 } else if (token == "\\boxbgcolor") {
948 string color = lex.getString();
949 boxbgcolor = lyx::rgbFromHexName(color);
950 lcolor.setColor("boxbgcolor", color);
951 } else if (token == "\\paperwidth") {
953 } else if (token == "\\paperheight") {
955 } else if (token == "\\leftmargin") {
957 } else if (token == "\\topmargin") {
959 } else if (token == "\\rightmargin") {
961 } else if (token == "\\bottommargin") {
963 } else if (token == "\\headheight") {
965 } else if (token == "\\headsep") {
967 } else if (token == "\\footskip") {
969 } else if (token == "\\columnsep") {
971 } else if (token == "\\paperfontsize") {
973 } else if (token == "\\papercolumns") {
975 } else if (token == "\\listings_params") {
978 listings_params = InsetListingsParams(par).params();
979 } else if (token == "\\papersides") {
982 sides = sidestranslator().find(psides);
983 } else if (token == "\\paperpagestyle") {
985 } else if (token == "\\bullet") {
987 } else if (token == "\\bulletLaTeX") {
988 readBulletsLaTeX(lex);
989 } else if (token == "\\secnumdepth") {
991 } else if (token == "\\tocdepth") {
993 } else if (token == "\\spacing") {
997 if (nspacing == "other") {
1000 spacing().set(spacetranslator().find(nspacing), tmp_val);
1001 } else if (token == "\\float_placement") {
1002 lex >> float_placement;
1004 } else if (prefixIs(token, "\\pdf_") || token == "\\use_hyperref") {
1005 string toktmp = pdfoptions().readToken(lex, token);
1006 if (!toktmp.empty()) {
1007 lyxerr << "PDFOptions::readToken(): Unknown token: " <<
1011 } else if (token == "\\html_math_output") {
1014 html_math_output = static_cast<MathOutput>(temp);
1015 } else if (token == "\\html_be_strict") {
1016 lex >> html_be_strict;
1017 } else if (token == "\\html_css_as_file") {
1018 lex >> html_css_as_file;
1019 } else if (token == "\\html_math_img_scale") {
1020 lex >> html_math_img_scale;
1021 } else if (token == "\\html_latex_start") {
1023 html_latex_start = lex.getString();
1024 } else if (token == "\\html_latex_end") {
1026 html_latex_end = lex.getString();
1027 } else if (token == "\\output_sync") {
1029 } else if (token == "\\output_sync_macro") {
1030 lex >> output_sync_macro;
1031 } else if (token == "\\use_refstyle") {
1032 lex >> use_refstyle;
1034 lyxerr << "BufferParams::readToken(): Unknown token: " <<
1044 // Quote argument if it contains spaces
1045 string quoteIfNeeded(string const & str) {
1046 if (contains(str, ' '))
1047 return "\"" + str + "\"";
1053 void BufferParams::writeFile(ostream & os, Buffer const * buf) const
1055 // The top of the file is written by the buffer.
1056 // Prints out the buffer info into the .lyx file given by file
1058 os << "\\save_transient_properties "
1059 << convert<string>(save_transient_properties) << '\n';
1061 // the document directory (must end with a path separator)
1062 // realPath() is used to resolve symlinks, while addPath(..., "")
1063 // ensures a trailing path separator.
1065 string filepath = addPath(buf->fileName().onlyPath().realPath(), "");
1066 string const sysdir = inSystemDir(FileName(filepath), docsys) ? docsys
1067 : addPath(package().system_support().realPath(), "");
1068 string const relpath =
1069 to_utf8(makeRelPath(from_utf8(filepath), from_utf8(sysdir)));
1070 if (!prefixIs(relpath, "../") && !FileName::isAbsolute(relpath))
1071 filepath = addPath("/systemlyxdir", relpath);
1072 else if (!save_transient_properties || !lyxrc.save_origin)
1073 filepath = "unavailable";
1074 os << "\\origin " << quoteIfNeeded(filepath) << '\n';
1077 os << "\\textclass "
1078 << quoteIfNeeded(buf->includedFilePath(addName(buf->layoutPos(),
1079 baseClass()->name()), "layout"))
1082 // then the preamble
1083 if (!preamble.empty()) {
1084 // remove '\n' from the end of preamble
1085 docstring const tmppreamble = rtrim(preamble, "\n");
1086 os << "\\begin_preamble\n"
1087 << to_utf8(tmppreamble)
1088 << "\n\\end_preamble\n";
1092 if (!options.empty()) {
1093 os << "\\options " << options << '\n';
1096 // use the class options defined in the layout?
1097 os << "\\use_default_options "
1098 << convert<string>(use_default_options) << "\n";
1100 // the master document
1101 if (!master.empty()) {
1102 os << "\\master " << master << '\n';
1106 if (!removed_modules_.empty()) {
1107 os << "\\begin_removed_modules" << '\n';
1108 list<string>::const_iterator it = removed_modules_.begin();
1109 list<string>::const_iterator en = removed_modules_.end();
1110 for (; it != en; ++it)
1112 os << "\\end_removed_modules" << '\n';
1116 if (!layout_modules_.empty()) {
1117 os << "\\begin_modules" << '\n';
1118 LayoutModuleList::const_iterator it = layout_modules_.begin();
1119 LayoutModuleList::const_iterator en = layout_modules_.end();
1120 for (; it != en; ++it)
1122 os << "\\end_modules" << '\n';
1126 if (!included_children_.empty()) {
1127 os << "\\begin_includeonly" << '\n';
1128 list<string>::const_iterator it = included_children_.begin();
1129 list<string>::const_iterator en = included_children_.end();
1130 for (; it != en; ++it)
1132 os << "\\end_includeonly" << '\n';
1134 os << "\\maintain_unincluded_children "
1135 << convert<string>(maintain_unincluded_children) << '\n';
1137 // local layout information
1138 docstring const local_layout = getLocalLayout(false);
1139 if (!local_layout.empty()) {
1140 // remove '\n' from the end
1141 docstring const tmplocal = rtrim(local_layout, "\n");
1142 os << "\\begin_local_layout\n"
1143 << to_utf8(tmplocal)
1144 << "\n\\end_local_layout\n";
1146 docstring const forced_local_layout = getLocalLayout(true);
1147 if (!forced_local_layout.empty()) {
1148 // remove '\n' from the end
1149 docstring const tmplocal = rtrim(forced_local_layout, "\n");
1150 os << "\\begin_forced_local_layout\n"
1151 << to_utf8(tmplocal)
1152 << "\n\\end_forced_local_layout\n";
1155 // then the text parameters
1156 if (language != ignore_language)
1157 os << "\\language " << language->lang() << '\n';
1158 os << "\\language_package " << lang_package
1159 << "\n\\inputencoding " << inputenc
1160 << "\n\\fontencoding " << fontenc
1161 << "\n\\font_roman \"" << fonts_roman[0]
1162 << "\" \"" << fonts_roman[1] << '"'
1163 << "\n\\font_sans \"" << fonts_sans[0]
1164 << "\" \"" << fonts_sans[1] << '"'
1165 << "\n\\font_typewriter \"" << fonts_typewriter[0]
1166 << "\" \"" << fonts_typewriter[1] << '"'
1167 << "\n\\font_math \"" << fonts_math[0]
1168 << "\" \"" << fonts_math[1] << '"'
1169 << "\n\\font_default_family " << fonts_default_family
1170 << "\n\\use_non_tex_fonts " << convert<string>(useNonTeXFonts)
1171 << "\n\\font_sc " << convert<string>(fonts_expert_sc)
1172 << "\n\\font_osf " << convert<string>(fonts_old_figures)
1173 << "\n\\font_sf_scale " << fonts_sans_scale[0]
1174 << ' ' << fonts_sans_scale[1]
1175 << "\n\\font_tt_scale " << fonts_typewriter_scale[0]
1176 << ' ' << fonts_typewriter_scale[1]
1178 if (!fonts_cjk.empty()) {
1179 os << "\\font_cjk " << fonts_cjk << '\n';
1181 os << "\\use_microtype " << convert<string>(use_microtype) << '\n';
1182 os << "\\graphics " << graphics_driver << '\n';
1183 os << "\\default_output_format " << default_output_format << '\n';
1184 os << "\\output_sync " << output_sync << '\n';
1185 if (!output_sync_macro.empty())
1186 os << "\\output_sync_macro \"" << output_sync_macro << "\"\n";
1187 os << "\\bibtex_command " << bibtex_command << '\n';
1188 os << "\\index_command " << index_command << '\n';
1190 if (!float_placement.empty()) {
1191 os << "\\float_placement " << float_placement << '\n';
1193 os << "\\paperfontsize " << fontsize << '\n';
1195 spacing().writeFile(os);
1196 pdfoptions().writeFile(os);
1198 os << "\\papersize " << string_papersize[papersize]
1199 << "\n\\use_geometry " << convert<string>(use_geometry);
1200 map<string, string> const & packages = auto_packages();
1201 for (map<string, string>::const_iterator it = packages.begin();
1202 it != packages.end(); ++it)
1203 os << "\n\\use_package " << it->first << ' '
1204 << use_package(it->first);
1206 os << "\n\\cite_engine ";
1208 if (!cite_engine_.empty()) {
1209 LayoutModuleList::const_iterator be = cite_engine_.begin();
1210 LayoutModuleList::const_iterator en = cite_engine_.end();
1211 for (LayoutModuleList::const_iterator it = be; it != en; ++it) {
1220 os << "\n\\cite_engine_type " << citeenginetypetranslator().find(cite_engine_type_)
1221 << "\n\\biblio_style " << biblio_style
1222 << "\n\\use_bibtopic " << convert<string>(use_bibtopic)
1223 << "\n\\use_indices " << convert<string>(use_indices)
1224 << "\n\\paperorientation " << string_orientation[orientation]
1225 << "\n\\suppress_date " << convert<string>(suppress_date)
1226 << "\n\\justification " << convert<string>(justification)
1227 << "\n\\use_refstyle " << use_refstyle
1229 if (isbackgroundcolor == true)
1230 os << "\\backgroundcolor " << lyx::X11hexname(backgroundcolor) << '\n';
1231 if (isfontcolor == true)
1232 os << "\\fontcolor " << lyx::X11hexname(fontcolor) << '\n';
1233 if (notefontcolor != lyx::rgbFromHexName("#cccccc"))
1234 os << "\\notefontcolor " << lyx::X11hexname(notefontcolor) << '\n';
1235 if (boxbgcolor != lyx::rgbFromHexName("#ff0000"))
1236 os << "\\boxbgcolor " << lyx::X11hexname(boxbgcolor) << '\n';
1238 BranchList::const_iterator it = branchlist().begin();
1239 BranchList::const_iterator end = branchlist().end();
1240 for (; it != end; ++it) {
1241 os << "\\branch " << to_utf8(it->branch())
1242 << "\n\\selected " << it->isSelected()
1243 << "\n\\filename_suffix " << it->hasFileNameSuffix()
1244 << "\n\\color " << lyx::X11hexname(it->color())
1249 IndicesList::const_iterator iit = indiceslist().begin();
1250 IndicesList::const_iterator iend = indiceslist().end();
1251 for (; iit != iend; ++iit) {
1252 os << "\\index " << to_utf8(iit->index())
1253 << "\n\\shortcut " << to_utf8(iit->shortcut())
1254 << "\n\\color " << lyx::X11hexname(iit->color())
1259 if (!paperwidth.empty())
1260 os << "\\paperwidth "
1261 << VSpace(paperwidth).asLyXCommand() << '\n';
1262 if (!paperheight.empty())
1263 os << "\\paperheight "
1264 << VSpace(paperheight).asLyXCommand() << '\n';
1265 if (!leftmargin.empty())
1266 os << "\\leftmargin "
1267 << VSpace(leftmargin).asLyXCommand() << '\n';
1268 if (!topmargin.empty())
1269 os << "\\topmargin "
1270 << VSpace(topmargin).asLyXCommand() << '\n';
1271 if (!rightmargin.empty())
1272 os << "\\rightmargin "
1273 << VSpace(rightmargin).asLyXCommand() << '\n';
1274 if (!bottommargin.empty())
1275 os << "\\bottommargin "
1276 << VSpace(bottommargin).asLyXCommand() << '\n';
1277 if (!headheight.empty())
1278 os << "\\headheight "
1279 << VSpace(headheight).asLyXCommand() << '\n';
1280 if (!headsep.empty())
1282 << VSpace(headsep).asLyXCommand() << '\n';
1283 if (!footskip.empty())
1285 << VSpace(footskip).asLyXCommand() << '\n';
1286 if (!columnsep.empty())
1287 os << "\\columnsep "
1288 << VSpace(columnsep).asLyXCommand() << '\n';
1289 os << "\\secnumdepth " << secnumdepth
1290 << "\n\\tocdepth " << tocdepth
1291 << "\n\\paragraph_separation "
1292 << string_paragraph_separation[paragraph_separation];
1293 if (!paragraph_separation)
1294 os << "\n\\paragraph_indentation " << getIndentation().asLyXCommand();
1296 os << "\n\\defskip " << getDefSkip().asLyXCommand();
1297 os << "\n\\quotes_language "
1298 << string_quotes_language[quotes_language]
1299 << "\n\\papercolumns " << columns
1300 << "\n\\papersides " << sides
1301 << "\n\\paperpagestyle " << pagestyle << '\n';
1302 if (!listings_params.empty())
1303 os << "\\listings_params \"" <<
1304 InsetListingsParams(listings_params).encodedString() << "\"\n";
1305 for (int i = 0; i < 4; ++i) {
1306 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1307 if (user_defined_bullet(i).getFont() != -1) {
1308 os << "\\bullet " << i << " "
1309 << user_defined_bullet(i).getFont() << " "
1310 << user_defined_bullet(i).getCharacter() << " "
1311 << user_defined_bullet(i).getSize() << "\n";
1315 os << "\\bulletLaTeX " << i << " \""
1316 << lyx::to_ascii(user_defined_bullet(i).getText())
1322 os << "\\tracking_changes "
1323 << (save_transient_properties ? convert<string>(track_changes) : "false")
1326 os << "\\output_changes "
1327 << (save_transient_properties ? convert<string>(output_changes) : "false")
1330 os << "\\html_math_output " << html_math_output << '\n'
1331 << "\\html_css_as_file " << html_css_as_file << '\n'
1332 << "\\html_be_strict " << convert<string>(html_be_strict) << '\n';
1334 if (html_math_img_scale != 1.0)
1335 os << "\\html_math_img_scale " << convert<string>(html_math_img_scale) << '\n';
1336 if (!html_latex_start.empty())
1337 os << "\\html_latex_start " << html_latex_start << '\n';
1338 if (!html_latex_end.empty())
1339 os << "\\html_latex_end " << html_latex_end << '\n';
1341 os << pimpl_->authorlist;
1345 void BufferParams::validate(LaTeXFeatures & features) const
1347 features.require(documentClass().requires());
1349 if (columns > 1 && language->rightToLeft())
1350 features.require("rtloutputdblcol");
1352 if (output_changes) {
1353 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1354 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1355 LaTeXFeatures::isAvailable("xcolor");
1357 switch (features.runparams().flavor) {
1358 case OutputParams::LATEX:
1359 case OutputParams::DVILUATEX:
1361 features.require("ct-dvipost");
1362 features.require("dvipost");
1363 } else if (xcolorulem) {
1364 features.require("ct-xcolor-ulem");
1365 features.require("ulem");
1366 features.require("xcolor");
1368 features.require("ct-none");
1371 case OutputParams::LUATEX:
1372 case OutputParams::PDFLATEX:
1373 case OutputParams::XETEX:
1375 features.require("ct-xcolor-ulem");
1376 features.require("ulem");
1377 features.require("xcolor");
1378 // improves color handling in PDF output
1379 features.require("pdfcolmk");
1381 features.require("ct-none");
1389 // Floats with 'Here definitely' as default setting.
1390 if (float_placement.find('H') != string::npos)
1391 features.require("float");
1393 for (PackageMap::const_iterator it = use_packages.begin();
1394 it != use_packages.end(); ++it) {
1395 if (it->first == "amsmath") {
1396 // AMS Style is at document level
1397 if (it->second == package_on ||
1398 features.isProvided("amsmath"))
1399 features.require(it->first);
1400 } else if (it->second == package_on)
1401 features.require(it->first);
1404 // Document-level line spacing
1405 if (spacing().getSpace() != Spacing::Single && !spacing().isDefault())
1406 features.require("setspace");
1408 // the bullet shapes are buffer level not paragraph level
1409 // so they are tested here
1410 for (int i = 0; i < 4; ++i) {
1411 if (user_defined_bullet(i) == ITEMIZE_DEFAULTS[i])
1413 int const font = user_defined_bullet(i).getFont();
1415 int const c = user_defined_bullet(i).getCharacter();
1421 features.require("latexsym");
1423 } else if (font == 1) {
1424 features.require("amssymb");
1425 } else if (font >= 2 && font <= 5) {
1426 features.require("pifont");
1430 if (pdfoptions().use_hyperref) {
1431 features.require("hyperref");
1432 // due to interferences with babel and hyperref, the color package has to
1433 // be loaded after hyperref when hyperref is used with the colorlinks
1434 // option, see http://www.lyx.org/trac/ticket/5291
1435 if (pdfoptions().colorlinks)
1436 features.require("color");
1438 if (!listings_params.empty()) {
1439 // do not test validity because listings_params is
1440 // supposed to be valid
1442 InsetListingsParams(listings_params).separatedParams(true);
1443 // we can't support all packages, but we should load the color package
1444 if (par.find("\\color", 0) != string::npos)
1445 features.require("color");
1448 // some languages are only available via polyglossia
1449 if (features.hasPolyglossiaExclusiveLanguages())
1450 features.require("polyglossia");
1452 if (useNonTeXFonts && fontsMath() != "auto")
1453 features.require("unicode-math");
1456 features.require("microtype");
1458 if (!language->requires().empty())
1459 features.require(language->requires());
1463 bool BufferParams::writeLaTeX(otexstream & os, LaTeXFeatures & features,
1464 FileName const & filepath) const
1466 // http://www.tug.org/texmf-dist/doc/latex/base/fixltx2e.pdf
1467 // !! To use the Fix-cm package, load it before \documentclass, and use the command
1468 // \RequirePackage to do so, rather than the normal \usepackage
1469 // Do not try to load any other package before the document class, unless you
1470 // have a thorough understanding of the LATEX internals and know exactly what you
1472 if (features.mustProvide("fix-cm"))
1473 os << "\\RequirePackage{fix-cm}\n";
1474 // Likewise for fixltx2e. If other packages conflict with this policy,
1475 // treat it as a package bug (and report it!)
1476 // See http://www.latex-project.org/cgi-bin/ltxbugs2html?pr=latex/4407
1477 if (features.mustProvide("fixltx2e"))
1478 os << "\\RequirePackage{fixltx2e}\n";
1480 os << "\\documentclass";
1482 DocumentClass const & tclass = documentClass();
1484 ostringstream clsoptions; // the document class options.
1486 if (tokenPos(tclass.opt_fontsize(),
1487 '|', fontsize) >= 0) {
1488 // only write if existing in list (and not default)
1489 clsoptions << fontsize << "pt,";
1492 // all paper sizes except of A4, A5, B5 and the US sizes need the
1494 bool nonstandard_papersize = papersize != PAPER_DEFAULT
1495 && papersize != PAPER_USLETTER
1496 && papersize != PAPER_USLEGAL
1497 && papersize != PAPER_USEXECUTIVE
1498 && papersize != PAPER_A4
1499 && papersize != PAPER_A5
1500 && papersize != PAPER_B5;
1502 if (!use_geometry) {
1503 switch (papersize) {
1505 clsoptions << "a4paper,";
1507 case PAPER_USLETTER:
1508 clsoptions << "letterpaper,";
1511 clsoptions << "a5paper,";
1514 clsoptions << "b5paper,";
1516 case PAPER_USEXECUTIVE:
1517 clsoptions << "executivepaper,";
1520 clsoptions << "legalpaper,";
1554 if (sides != tclass.sides()) {
1557 clsoptions << "oneside,";
1560 clsoptions << "twoside,";
1566 if (columns != tclass.columns()) {
1568 clsoptions << "twocolumn,";
1570 clsoptions << "onecolumn,";
1574 && orientation == ORIENTATION_LANDSCAPE)
1575 clsoptions << "landscape,";
1577 // language should be a parameter to \documentclass
1578 if (language->babel() == "hebrew"
1579 && default_language->babel() != "hebrew")
1580 // This seems necessary
1581 features.useLanguage(default_language);
1583 ostringstream language_options;
1584 bool const use_babel = features.useBabel() && !features.isProvided("babel");
1585 bool const use_polyglossia = features.usePolyglossia();
1586 bool const global = lyxrc.language_global_options;
1587 if (use_babel || (use_polyglossia && global)) {
1588 language_options << features.getBabelLanguages();
1589 if (!language->babel().empty()) {
1590 if (!language_options.str().empty())
1591 language_options << ',';
1592 language_options << language->babel();
1594 if (global && !features.needBabelLangOptions()
1595 && !language_options.str().empty())
1596 clsoptions << language_options.str() << ',';
1599 // the predefined options from the layout
1600 if (use_default_options && !tclass.options().empty())
1601 clsoptions << tclass.options() << ',';
1603 // the user-defined options
1604 if (!options.empty()) {
1605 clsoptions << options << ',';
1608 string strOptions(clsoptions.str());
1609 if (!strOptions.empty()) {
1610 strOptions = rtrim(strOptions, ",");
1612 os << '[' << from_utf8(strOptions) << ']';
1615 os << '{' << from_ascii(tclass.latexname()) << "}\n";
1616 // end of \documentclass defs
1618 // if we use fontspec or newtxmath, we have to load the AMS packages here
1619 string const ams = features.loadAMSPackages();
1620 bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
1621 bool const use_newtxmath =
1622 theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getUsedPackage(
1623 ot1, false, false) == "newtxmath";
1624 if ((useNonTeXFonts || use_newtxmath) && !ams.empty())
1625 os << from_ascii(ams);
1627 if (useNonTeXFonts) {
1628 if (!features.isProvided("fontspec"))
1629 os << "\\usepackage{fontspec}\n";
1630 if (features.mustProvide("unicode-math")
1631 && features.isAvailable("unicode-math"))
1632 os << "\\usepackage{unicode-math}\n";
1635 // font selection must be done before loading fontenc.sty
1636 string const fonts = loadFonts(features);
1638 os << from_utf8(fonts);
1640 if (fonts_default_family != "default")
1641 os << "\\renewcommand{\\familydefault}{\\"
1642 << from_ascii(fonts_default_family) << "}\n";
1644 // set font encoding
1645 // XeTeX and LuaTeX (with OS fonts) do not need fontenc
1646 if (!useNonTeXFonts && !features.isProvided("fontenc")
1647 && font_encoding() != "default") {
1648 // get main font encodings
1649 vector<string> fontencs = font_encodings();
1650 // get font encodings of secondary languages
1651 features.getFontEncodings(fontencs);
1652 if (!fontencs.empty()) {
1653 os << "\\usepackage["
1654 << from_ascii(getStringFromVector(fontencs))
1659 // handle inputenc etc.
1660 writeEncodingPreamble(os, features);
1663 if (!features.runparams().includeall && !included_children_.empty()) {
1664 os << "\\includeonly{";
1665 list<string>::const_iterator it = included_children_.begin();
1666 list<string>::const_iterator en = included_children_.end();
1668 for (; it != en; ++it) {
1669 string incfile = *it;
1670 FileName inc = makeAbsPath(incfile, filepath.absFileName());
1671 string mangled = DocFileName(changeExtension(inc.absFileName(), ".tex")).
1673 if (!features.runparams().nice)
1675 // \includeonly doesn't want an extension
1676 incfile = changeExtension(incfile, string());
1677 incfile = support::latex_path(incfile);
1678 if (!incfile.empty()) {
1681 os << from_utf8(incfile);
1688 if (!features.isProvided("geometry")
1689 && (use_geometry || nonstandard_papersize)) {
1690 odocstringstream ods;
1691 if (!getGraphicsDriver("geometry").empty())
1692 ods << getGraphicsDriver("geometry");
1693 if (orientation == ORIENTATION_LANDSCAPE)
1694 ods << ",landscape";
1695 switch (papersize) {
1697 if (!paperwidth.empty())
1698 ods << ",paperwidth="
1699 << from_ascii(paperwidth);
1700 if (!paperheight.empty())
1701 ods << ",paperheight="
1702 << from_ascii(paperheight);
1704 case PAPER_USLETTER:
1705 ods << ",letterpaper";
1708 ods << ",legalpaper";
1710 case PAPER_USEXECUTIVE:
1711 ods << ",executivepaper";
1800 docstring const g_options = trim(ods.str(), ",");
1801 os << "\\usepackage";
1802 if (!g_options.empty())
1803 os << '[' << g_options << ']';
1804 os << "{geometry}\n";
1805 // output this only if use_geometry is true
1807 os << "\\geometry{verbose";
1808 if (!topmargin.empty())
1809 os << ",tmargin=" << from_ascii(Length(topmargin).asLatexString());
1810 if (!bottommargin.empty())
1811 os << ",bmargin=" << from_ascii(Length(bottommargin).asLatexString());
1812 if (!leftmargin.empty())
1813 os << ",lmargin=" << from_ascii(Length(leftmargin).asLatexString());
1814 if (!rightmargin.empty())
1815 os << ",rmargin=" << from_ascii(Length(rightmargin).asLatexString());
1816 if (!headheight.empty())
1817 os << ",headheight=" << from_ascii(Length(headheight).asLatexString());
1818 if (!headsep.empty())
1819 os << ",headsep=" << from_ascii(Length(headsep).asLatexString());
1820 if (!footskip.empty())
1821 os << ",footskip=" << from_ascii(Length(footskip).asLatexString());
1822 if (!columnsep.empty())
1823 os << ",columnsep=" << from_ascii(Length(columnsep).asLatexString());
1826 } else if (orientation == ORIENTATION_LANDSCAPE
1827 || papersize != PAPER_DEFAULT) {
1828 features.require("papersize");
1831 if (tokenPos(tclass.opt_pagestyle(), '|', pagestyle) >= 0) {
1832 if (pagestyle == "fancy")
1833 os << "\\usepackage{fancyhdr}\n";
1834 os << "\\pagestyle{" << from_ascii(pagestyle) << "}\n";
1837 // only output when the background color is not default
1838 if (isbackgroundcolor == true) {
1839 // only require color here, the background color will be defined
1840 // in LaTeXFeatures.cpp to avoid interferences with the LaTeX
1842 features.require("color");
1843 features.require("pagecolor");
1846 // only output when the font color is not default
1847 if (isfontcolor == true) {
1848 // only require color here, the font color will be defined
1849 // in LaTeXFeatures.cpp to avoid interferences with the LaTeX
1851 features.require("color");
1852 features.require("fontcolor");
1855 // Only if class has a ToC hierarchy
1856 if (tclass.hasTocLevels()) {
1857 if (secnumdepth != tclass.secnumdepth()) {
1858 os << "\\setcounter{secnumdepth}{"
1862 if (tocdepth != tclass.tocdepth()) {
1863 os << "\\setcounter{tocdepth}{"
1869 if (paragraph_separation) {
1870 // when skip separation
1871 switch (getDefSkip().kind()) {
1872 case VSpace::SMALLSKIP:
1873 os << "\\setlength{\\parskip}{\\smallskipamount}\n";
1875 case VSpace::MEDSKIP:
1876 os << "\\setlength{\\parskip}{\\medskipamount}\n";
1878 case VSpace::BIGSKIP:
1879 os << "\\setlength{\\parskip}{\\bigskipamount}\n";
1881 case VSpace::LENGTH:
1882 os << "\\setlength{\\parskip}{"
1883 << from_utf8(getDefSkip().length().asLatexString())
1886 default: // should never happen // Then delete it.
1887 os << "\\setlength{\\parskip}{\\medskipamount}\n";
1890 os << "\\setlength{\\parindent}{0pt}\n";
1892 // when separation by indentation
1893 // only output something when a width is given
1894 if (getIndentation().asLyXCommand() != "default") {
1895 os << "\\setlength{\\parindent}{"
1896 << from_utf8(getIndentation().asLatexCommand())
1901 // Now insert the LyX specific LaTeX commands...
1902 docstring lyxpreamble;
1903 features.resolveAlternatives();
1904 features.expandMultiples();
1907 if (!output_sync_macro.empty())
1908 lyxpreamble += from_utf8(output_sync_macro) +"\n";
1909 else if (features.runparams().flavor == OutputParams::LATEX)
1910 lyxpreamble += "\\usepackage[active]{srcltx}\n";
1911 else if (features.runparams().flavor == OutputParams::PDFLATEX)
1912 lyxpreamble += "\\synctex=-1\n";
1915 // The package options (via \PassOptionsToPackage)
1916 lyxpreamble += from_ascii(features.getPackageOptions());
1918 // due to interferences with babel and hyperref, the color package has to
1919 // be loaded (when it is not already loaded) before babel when hyperref
1920 // is used with the colorlinks option, see
1921 // http://www.lyx.org/trac/ticket/5291
1922 // we decided therefore to load color always before babel, see
1923 // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg144349.html
1924 lyxpreamble += from_ascii(features.getColorOptions());
1926 // If we use hyperref, jurabib, japanese, varioref or vietnamese,
1927 // we have to call babel before
1929 && (features.isRequired("jurabib")
1930 || features.isRequired("hyperref")
1931 || features.isRequired("varioref")
1932 || features.isRequired("vietnamese")
1933 || features.isRequired("japanese"))) {
1934 lyxpreamble += features.getBabelPresettings();
1936 lyxpreamble += from_utf8(babelCall(language_options.str(),
1937 features.needBabelLangOptions())) + '\n';
1938 lyxpreamble += features.getBabelPostsettings();
1941 // The optional packages;
1942 lyxpreamble += from_ascii(features.getPackages());
1944 // Additional Indices
1945 if (features.isRequired("splitidx")) {
1946 IndicesList::const_iterator iit = indiceslist().begin();
1947 IndicesList::const_iterator iend = indiceslist().end();
1948 for (; iit != iend; ++iit) {
1949 pair<docstring, docstring> indexname_latex =
1950 features.runparams().encoding->latexString(iit->index(),
1951 features.runparams().dryrun);
1952 if (!indexname_latex.second.empty()) {
1953 // issue a warning about omitted characters
1954 // FIXME: should be passed to the error dialog
1955 frontend::Alert::warning(_("Uncodable characters"),
1956 bformat(_("The following characters that are used in an index name are not\n"
1957 "representable in the current encoding and therefore have been omitted:\n%1$s."),
1958 indexname_latex.second));
1960 lyxpreamble += "\\newindex[";
1961 lyxpreamble += indexname_latex.first;
1962 lyxpreamble += "]{";
1963 lyxpreamble += escape(iit->shortcut());
1964 lyxpreamble += "}\n";
1969 lyxpreamble += from_utf8(spacing().writePreamble(features.isProvided("SetSpace")));
1972 // * Hyperref manual: "Make sure it comes last of your loaded
1973 // packages, to give it a fighting chance of not being over-written,
1974 // since its job is to redefine many LaTeX commands."
1975 // * Email from Heiko Oberdiek: "It is usually better to load babel
1976 // before hyperref. Then hyperref has a chance to detect babel.
1977 // * Has to be loaded before the "LyX specific LaTeX commands" to
1978 // avoid errors with algorithm floats.
1979 // use hyperref explicitly if it is required
1980 if (features.isRequired("hyperref")) {
1981 // pass what we have to stream here, since we need
1982 // to access the stream itself in PDFOptions.
1985 OutputParams tmp_params = features.runparams();
1986 pdfoptions().writeLaTeX(tmp_params, os,
1987 features.isProvided("hyperref"));
1988 // set back for the rest
1989 lyxpreamble.clear();
1990 // correctly break URLs with hyperref and dvi output
1991 if (features.runparams().flavor == OutputParams::LATEX
1992 && features.isAvailable("breakurl"))
1993 lyxpreamble += "\\usepackage{breakurl}\n";
1994 } else if (features.isRequired("nameref"))
1995 // hyperref loads this automatically
1996 lyxpreamble += "\\usepackage{nameref}\n";
1998 // bibtopic needs to be loaded after hyperref.
1999 // the dot provides the aux file naming which LyX can detect.
2000 if (features.mustProvide("bibtopic"))
2001 lyxpreamble += "\\usepackage[dot]{bibtopic}\n";
2003 // Will be surrounded by \makeatletter and \makeatother when not empty
2004 docstring atlyxpreamble;
2006 // Some macros LyX will need
2007 docstring tmppreamble(features.getMacros());
2009 if (!tmppreamble.empty())
2010 atlyxpreamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2011 "LyX specific LaTeX commands.\n"
2012 + tmppreamble + '\n';
2014 // the text class specific preamble
2015 tmppreamble = features.getTClassPreamble();
2016 if (!tmppreamble.empty())
2017 atlyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2018 "Textclass specific LaTeX commands.\n"
2019 + tmppreamble + '\n';
2021 // suppress date if selected
2022 // use \@ifundefined because we cannot be sure that every document class
2023 // has a \date command
2025 atlyxpreamble += "\\@ifundefined{date}{}{\\date{}}\n";
2027 /* the user-defined preamble */
2028 if (!containsOnly(preamble, " \n\t")) {
2030 atlyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2031 "User specified LaTeX commands.\n";
2033 // Check if the user preamble contains uncodable glyphs
2034 odocstringstream user_preamble;
2035 docstring uncodable_glyphs;
2036 Encoding const * const enc = features.runparams().encoding;
2038 for (size_t n = 0; n < preamble.size(); ++n) {
2039 char_type c = preamble[n];
2040 if (!enc->encodable(c)) {
2041 docstring const glyph(1, c);
2042 LYXERR0("Uncodable character '"
2044 << "' in user preamble!");
2045 uncodable_glyphs += glyph;
2046 if (features.runparams().dryrun) {
2047 user_preamble << "<" << _("LyX Warning: ")
2048 << _("uncodable character") << " '";
2049 user_preamble.put(c);
2050 user_preamble << "'>";
2053 user_preamble.put(c);
2056 user_preamble << preamble;
2058 // On BUFFER_VIEW|UPDATE, warn user if we found uncodable glyphs
2059 if (!features.runparams().dryrun && !uncodable_glyphs.empty()) {
2060 frontend::Alert::warning(
2061 _("Uncodable character in user preamble"),
2063 _("The user preamble of your document contains glyphs "
2064 "that are unknown in the current document encoding "
2065 "(namely %1$s).\nThese glyphs are omitted "
2066 " from the output, which may result in "
2067 "incomplete output."
2068 "\n\nPlease select an appropriate "
2069 "document encoding\n"
2070 "(such as utf8) or change the "
2071 "preamble code accordingly."),
2074 atlyxpreamble += user_preamble.str() + '\n';
2077 // footmisc must be loaded after setspace
2078 // Load it here to avoid clashes with footmisc loaded in the user
2079 // preamble. For that reason we also pass the options via
2080 // \PassOptionsToPackage in getPreamble() and not here.
2081 if (features.mustProvide("footmisc"))
2082 atlyxpreamble += "\\usepackage{footmisc}\n";
2084 // subfig loads internally the LaTeX package "caption". As
2085 // caption is a very popular package, users will load it in
2086 // the preamble. Therefore we must load subfig behind the
2087 // user-defined preamble and check if the caption package was
2088 // loaded or not. For the case that caption is loaded before
2089 // subfig, there is the subfig option "caption=false". This
2090 // option also works when a koma-script class is used and
2091 // koma's own caption commands are used instead of caption. We
2092 // use \PassOptionsToPackage here because the user could have
2093 // already loaded subfig in the preamble.
2094 if (features.mustProvide("subfig")) {
2095 atlyxpreamble += "\\@ifundefined{showcaptionsetup}{}{%\n"
2096 " \\PassOptionsToPackage{caption=false}{subfig}}\n"
2097 "\\usepackage{subfig}\n";
2100 // Itemize bullet settings need to be last in case the user
2101 // defines their own bullets that use a package included
2102 // in the user-defined preamble -- ARRae
2103 // Actually it has to be done much later than that
2104 // since some packages like frenchb make modifications
2105 // at \begin{document} time -- JMarc
2106 docstring bullets_def;
2107 for (int i = 0; i < 4; ++i) {
2108 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
2109 if (bullets_def.empty())
2110 bullets_def += "\\AtBeginDocument{\n";
2111 bullets_def += " \\def\\labelitemi";
2113 // `i' is one less than the item to modify
2120 bullets_def += "ii";
2126 bullets_def += '{' +
2127 user_defined_bullet(i).getText()
2132 if (!bullets_def.empty())
2133 atlyxpreamble += bullets_def + "}\n\n";
2135 if (!atlyxpreamble.empty())
2136 lyxpreamble += "\n\\makeatletter\n"
2137 + atlyxpreamble + "\\makeatother\n\n";
2139 // We try to load babel late, in case it interferes with other packages.
2140 // Jurabib, hyperref, varioref, bicaption and listings (bug 8995) have to be
2141 // called after babel, though.
2142 if (use_babel && !features.isRequired("jurabib")
2143 && !features.isRequired("hyperref")
2144 && !features.isRequired("varioref")
2145 && !features.isRequired("vietnamese")
2146 && !features.isRequired("japanese")) {
2147 lyxpreamble += features.getBabelPresettings();
2149 lyxpreamble += from_utf8(babelCall(language_options.str(),
2150 features.needBabelLangOptions())) + '\n';
2151 lyxpreamble += features.getBabelPostsettings();
2153 if (features.isRequired("bicaption"))
2154 lyxpreamble += "\\usepackage{bicaption}\n";
2155 if (!listings_params.empty() || features.mustProvide("listings"))
2156 lyxpreamble += "\\usepackage{listings}\n";
2157 if (!listings_params.empty()) {
2158 lyxpreamble += "\\lstset{";
2159 // do not test validity because listings_params is
2160 // supposed to be valid
2162 InsetListingsParams(listings_params).separatedParams(true);
2163 lyxpreamble += from_utf8(par);
2164 lyxpreamble += "}\n";
2167 // xunicode needs to be loaded at least after amsmath, amssymb,
2168 // esint and the other packages that provide special glyphs
2169 // The package only supports XeTeX currently.
2170 if (features.runparams().flavor == OutputParams::XETEX
2172 lyxpreamble += "\\usepackage{xunicode}\n";
2174 // Polyglossia must be loaded last
2175 if (use_polyglossia) {
2177 lyxpreamble += "\\usepackage{polyglossia}\n";
2178 // set the main language
2179 lyxpreamble += "\\setdefaultlanguage";
2180 if (!language->polyglossiaOpts().empty())
2181 lyxpreamble += "[" + from_ascii(language->polyglossiaOpts()) + "]";
2182 lyxpreamble += "{" + from_ascii(language->polyglossia()) + "}\n";
2183 // now setup the other languages
2184 std::map<std::string, std::string> const polylangs =
2185 features.getPolyglossiaLanguages();
2186 for (std::map<std::string, std::string>::const_iterator mit = polylangs.begin();
2187 mit != polylangs.end() ; ++mit) {
2188 lyxpreamble += "\\setotherlanguage";
2189 if (!mit->second.empty())
2190 lyxpreamble += "[" + from_ascii(mit->second) + "]";
2191 lyxpreamble += "{" + from_ascii(mit->first) + "}\n";
2195 // Load custom language package here
2196 if (features.langPackage() == LaTeXFeatures::LANG_PACK_CUSTOM) {
2197 if (lang_package == "default")
2198 lyxpreamble += from_utf8(lyxrc.language_custom_package);
2200 lyxpreamble += from_utf8(lang_package);
2201 lyxpreamble += '\n';
2204 docstring const i18npreamble =
2205 features.getTClassI18nPreamble(use_babel, use_polyglossia);
2206 if (!i18npreamble.empty())
2207 lyxpreamble += i18npreamble + '\n';
2215 void BufferParams::useClassDefaults()
2217 DocumentClass const & tclass = documentClass();
2219 sides = tclass.sides();
2220 columns = tclass.columns();
2221 pagestyle = tclass.pagestyle();
2222 use_default_options = true;
2223 // Only if class has a ToC hierarchy
2224 if (tclass.hasTocLevels()) {
2225 secnumdepth = tclass.secnumdepth();
2226 tocdepth = tclass.tocdepth();
2231 bool BufferParams::hasClassDefaults() const
2233 DocumentClass const & tclass = documentClass();
2235 return sides == tclass.sides()
2236 && columns == tclass.columns()
2237 && pagestyle == tclass.pagestyle()
2238 && use_default_options
2239 && secnumdepth == tclass.secnumdepth()
2240 && tocdepth == tclass.tocdepth();
2244 DocumentClass const & BufferParams::documentClass() const
2250 DocumentClassConstPtr BufferParams::documentClassPtr() const
2256 void BufferParams::setDocumentClass(DocumentClassConstPtr tc)
2258 // evil, but this function is evil
2259 doc_class_ = const_pointer_cast<DocumentClass>(tc);
2263 bool BufferParams::setBaseClass(string const & classname)
2265 LYXERR(Debug::TCLASS, "setBaseClass: " << classname);
2266 LayoutFileList & bcl = LayoutFileList::get();
2267 if (!bcl.haveClass(classname)) {
2269 bformat(_("The layout file:\n"
2271 "could not be found. A default textclass with default\n"
2272 "layouts will be used. LyX will not be able to produce\n"
2274 from_utf8(classname));
2275 frontend::Alert::error(_("Document class not found"), s);
2276 bcl.addEmptyClass(classname);
2279 bool const success = bcl[classname].load();
2282 bformat(_("Due to some error in it, the layout file:\n"
2284 "could not be loaded. A default textclass with default\n"
2285 "layouts will be used. LyX will not be able to produce\n"
2287 from_utf8(classname));
2288 frontend::Alert::error(_("Could not load class"), s);
2289 bcl.addEmptyClass(classname);
2292 pimpl_->baseClass_ = classname;
2293 layout_modules_.adaptToBaseClass(baseClass(), removed_modules_);
2298 LayoutFile const * BufferParams::baseClass() const
2300 if (LayoutFileList::get().haveClass(pimpl_->baseClass_))
2301 return &(LayoutFileList::get()[pimpl_->baseClass_]);
2307 LayoutFileIndex const & BufferParams::baseClassID() const
2309 return pimpl_->baseClass_;
2313 void BufferParams::makeDocumentClass(bool const clone)
2318 LayoutModuleList mods;
2319 LayoutModuleList::iterator it = layout_modules_.begin();
2320 LayoutModuleList::iterator en = layout_modules_.end();
2321 for (; it != en; ++it)
2322 mods.push_back(*it);
2324 it = cite_engine_.begin();
2325 en = cite_engine_.end();
2326 for (; it != en; ++it)
2327 mods.push_back(*it);
2329 doc_class_ = getDocumentClass(*baseClass(), mods, clone);
2331 TextClass::ReturnValues success = TextClass::OK;
2332 if (!forced_local_layout_.empty())
2333 success = doc_class_->read(to_utf8(forced_local_layout_),
2335 if (!local_layout_.empty() &&
2336 (success == TextClass::OK || success == TextClass::OK_OLDFORMAT))
2337 success = doc_class_->read(to_utf8(local_layout_), TextClass::MODULE);
2338 if (success != TextClass::OK && success != TextClass::OK_OLDFORMAT) {
2339 docstring const msg = _("Error reading internal layout information");
2340 frontend::Alert::warning(_("Read Error"), msg);
2345 bool BufferParams::layoutModuleCanBeAdded(string const & modName) const
2347 return layout_modules_.moduleCanBeAdded(modName, baseClass());
2351 bool BufferParams::citationModuleCanBeAdded(string const & modName) const
2353 return cite_engine_.moduleCanBeAdded(modName, baseClass());
2357 docstring BufferParams::getLocalLayout(bool forced) const
2360 return from_utf8(doc_class_->forcedLayouts());
2362 return local_layout_;
2366 void BufferParams::setLocalLayout(docstring const & layout, bool forced)
2369 forced_local_layout_ = layout;
2371 local_layout_ = layout;
2375 bool BufferParams::addLayoutModule(string const & modName)
2377 LayoutModuleList::const_iterator it = layout_modules_.begin();
2378 LayoutModuleList::const_iterator end = layout_modules_.end();
2379 for (; it != end; ++it)
2382 layout_modules_.push_back(modName);
2387 string BufferParams::bufferFormat() const
2389 return documentClass().outputFormat();
2393 bool BufferParams::isExportable(string const & format) const
2395 vector<string> backs = backends();
2396 for (vector<string>::const_iterator it = backs.begin();
2397 it != backs.end(); ++it)
2398 if (theConverters().isReachable(*it, format))
2404 vector<Format const *> BufferParams::exportableFormats(bool only_viewable) const
2406 vector<string> const backs = backends();
2407 set<string> excludes;
2408 if (useNonTeXFonts) {
2409 excludes.insert("latex");
2410 excludes.insert("pdflatex");
2412 vector<Format const *> result =
2413 theConverters().getReachable(backs[0], only_viewable, true, excludes);
2414 for (vector<string>::const_iterator it = backs.begin() + 1;
2415 it != backs.end(); ++it) {
2416 vector<Format const *> r =
2417 theConverters().getReachable(*it, only_viewable, false, excludes);
2418 result.insert(result.end(), r.begin(), r.end());
2424 bool BufferParams::isExportableFormat(string const & format) const
2426 typedef vector<Format const *> Formats;
2428 formats = exportableFormats(true);
2429 Formats::const_iterator fit = formats.begin();
2430 Formats::const_iterator end = formats.end();
2431 for (; fit != end ; ++fit) {
2432 if ((*fit)->name() == format)
2439 vector<string> BufferParams::backends() const
2442 string const buffmt = bufferFormat();
2444 // FIXME: Don't hardcode format names here, but use a flag
2445 if (buffmt == "latex") {
2446 if (encoding().package() == Encoding::japanese)
2447 v.push_back("platex");
2449 if (!useNonTeXFonts) {
2450 v.push_back("pdflatex");
2451 v.push_back("latex");
2453 v.push_back("xetex");
2454 v.push_back("luatex");
2455 v.push_back("dviluatex");
2458 v.push_back(buffmt);
2460 v.push_back("xhtml");
2461 v.push_back("text");
2467 OutputParams::FLAVOR BufferParams::getOutputFlavor(string const & format) const
2469 string const dformat = (format.empty() || format == "default") ?
2470 getDefaultOutputFormat() : format;
2471 DefaultFlavorCache::const_iterator it =
2472 default_flavors_.find(dformat);
2474 if (it != default_flavors_.end())
2477 OutputParams::FLAVOR result = OutputParams::LATEX;
2479 // FIXME It'd be better not to hardcode this, but to do
2480 // something with formats.
2481 if (dformat == "xhtml")
2482 result = OutputParams::HTML;
2483 else if (dformat == "text")
2484 result = OutputParams::TEXT;
2485 else if (dformat == "lyx")
2486 result = OutputParams::LYX;
2487 else if (dformat == "pdflatex")
2488 result = OutputParams::PDFLATEX;
2489 else if (dformat == "xetex")
2490 result = OutputParams::XETEX;
2491 else if (dformat == "luatex")
2492 result = OutputParams::LUATEX;
2493 else if (dformat == "dviluatex")
2494 result = OutputParams::DVILUATEX;
2496 // Try to determine flavor of default output format
2497 vector<string> backs = backends();
2498 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
2499 // Get shortest path to format
2500 Graph::EdgePath path;
2501 for (vector<string>::const_iterator it = backs.begin();
2502 it != backs.end(); ++it) {
2503 Graph::EdgePath p = theConverters().getPath(*it, dformat);
2504 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2509 result = theConverters().getFlavor(path);
2512 // cache this flavor
2513 default_flavors_[dformat] = result;
2518 string BufferParams::getDefaultOutputFormat() const
2520 if (!default_output_format.empty()
2521 && default_output_format != "default")
2522 return default_output_format;
2524 || encoding().package() == Encoding::japanese) {
2525 vector<Format const *> const formats = exportableFormats(true);
2526 if (formats.empty())
2528 // return the first we find
2529 return formats.front()->name();
2532 return lyxrc.default_otf_view_format;
2533 return lyxrc.default_view_format;
2536 Font const BufferParams::getFont() const
2538 FontInfo f = documentClass().defaultfont();
2539 if (fonts_default_family == "rmdefault")
2540 f.setFamily(ROMAN_FAMILY);
2541 else if (fonts_default_family == "sfdefault")
2542 f.setFamily(SANS_FAMILY);
2543 else if (fonts_default_family == "ttdefault")
2544 f.setFamily(TYPEWRITER_FAMILY);
2545 return Font(f, language);
2549 InsetQuotes::QuoteLanguage BufferParams::getQuoteStyle(string const & qs) const
2551 return quoteslangtranslator().find(qs);
2555 bool BufferParams::isLatex() const
2557 return documentClass().outputType() == LATEX;
2561 bool BufferParams::isLiterate() const
2563 return documentClass().outputType() == LITERATE;
2567 bool BufferParams::isDocBook() const
2569 return documentClass().outputType() == DOCBOOK;
2573 void BufferParams::readPreamble(Lexer & lex)
2575 if (lex.getString() != "\\begin_preamble")
2576 lyxerr << "Error (BufferParams::readPreamble):"
2577 "consistency check failed." << endl;
2579 preamble = lex.getLongString(from_ascii("\\end_preamble"));
2583 void BufferParams::readLocalLayout(Lexer & lex, bool forced)
2585 string const expected = forced ? "\\begin_forced_local_layout" :
2586 "\\begin_local_layout";
2587 if (lex.getString() != expected)
2588 lyxerr << "Error (BufferParams::readLocalLayout):"
2589 "consistency check failed." << endl;
2592 forced_local_layout_ =
2593 lex.getLongString(from_ascii("\\end_forced_local_layout"));
2595 local_layout_ = lex.getLongString(from_ascii("\\end_local_layout"));
2599 bool BufferParams::setLanguage(string const & lang)
2601 Language const *new_language = languages.getLanguage(lang);
2602 if (!new_language) {
2603 // Language lang was not found
2606 language = new_language;
2611 void BufferParams::readLanguage(Lexer & lex)
2613 if (!lex.next()) return;
2615 string const tmptok = lex.getString();
2617 // check if tmptok is part of tex_babel in tex-defs.h
2618 if (!setLanguage(tmptok)) {
2619 // Language tmptok was not found
2620 language = default_language;
2621 lyxerr << "Warning: Setting language `"
2622 << tmptok << "' to `" << language->lang()
2628 void BufferParams::readGraphicsDriver(Lexer & lex)
2633 string const tmptok = lex.getString();
2634 // check if tmptok is part of tex_graphics in tex_defs.h
2637 string const test = tex_graphics[n++];
2639 if (test == tmptok) {
2640 graphics_driver = tmptok;
2645 "Warning: graphics driver `$$Token' not recognized!\n"
2646 " Setting graphics driver to `default'.\n");
2647 graphics_driver = "default";
2654 void BufferParams::readBullets(Lexer & lex)
2659 int const index = lex.getInteger();
2661 int temp_int = lex.getInteger();
2662 user_defined_bullet(index).setFont(temp_int);
2663 temp_bullet(index).setFont(temp_int);
2665 user_defined_bullet(index).setCharacter(temp_int);
2666 temp_bullet(index).setCharacter(temp_int);
2668 user_defined_bullet(index).setSize(temp_int);
2669 temp_bullet(index).setSize(temp_int);
2673 void BufferParams::readBulletsLaTeX(Lexer & lex)
2675 // The bullet class should be able to read this.
2678 int const index = lex.getInteger();
2680 docstring const temp_str = lex.getDocString();
2682 user_defined_bullet(index).setText(temp_str);
2683 temp_bullet(index).setText(temp_str);
2687 void BufferParams::readModules(Lexer & lex)
2689 if (!lex.eatLine()) {
2690 lyxerr << "Error (BufferParams::readModules):"
2691 "Unexpected end of input." << endl;
2695 string mod = lex.getString();
2696 if (mod == "\\end_modules")
2698 addLayoutModule(mod);
2704 void BufferParams::readRemovedModules(Lexer & lex)
2706 if (!lex.eatLine()) {
2707 lyxerr << "Error (BufferParams::readRemovedModules):"
2708 "Unexpected end of input." << endl;
2712 string mod = lex.getString();
2713 if (mod == "\\end_removed_modules")
2715 removed_modules_.push_back(mod);
2718 // now we want to remove any removed modules that were previously
2719 // added. normally, that will be because default modules were added in
2720 // setBaseClass(), which gets called when \textclass is read at the
2721 // start of the read.
2722 list<string>::const_iterator rit = removed_modules_.begin();
2723 list<string>::const_iterator const ren = removed_modules_.end();
2724 for (; rit != ren; ++rit) {
2725 LayoutModuleList::iterator const mit = layout_modules_.begin();
2726 LayoutModuleList::iterator const men = layout_modules_.end();
2727 LayoutModuleList::iterator found = find(mit, men, *rit);
2730 layout_modules_.erase(found);
2735 void BufferParams::readIncludeonly(Lexer & lex)
2737 if (!lex.eatLine()) {
2738 lyxerr << "Error (BufferParams::readIncludeonly):"
2739 "Unexpected end of input." << endl;
2743 string child = lex.getString();
2744 if (child == "\\end_includeonly")
2746 included_children_.push_back(child);
2752 string BufferParams::paperSizeName(PapersizePurpose purpose) const
2754 switch (papersize) {
2756 // could be anything, so don't guess
2758 case PAPER_CUSTOM: {
2759 if (purpose == XDVI && !paperwidth.empty() &&
2760 !paperheight.empty()) {
2761 // heightxwidth<unit>
2762 string first = paperwidth;
2763 string second = paperheight;
2764 if (orientation == ORIENTATION_LANDSCAPE)
2767 return first.erase(first.length() - 2)
2773 // dvips and dvipdfm do not know this
2774 if (purpose == DVIPS || purpose == DVIPDFM)
2778 if (purpose == DVIPS || purpose == DVIPDFM)
2782 if (purpose == DVIPS || purpose == DVIPDFM)
2792 if (purpose == DVIPS || purpose == DVIPDFM)
2796 if (purpose == DVIPS || purpose == DVIPDFM)
2800 if (purpose == DVIPS || purpose == DVIPDFM)
2804 if (purpose == DVIPS || purpose == DVIPDFM)
2808 if (purpose == DVIPS || purpose == DVIPDFM)
2812 // dvipdfm does not know this
2813 if (purpose == DVIPDFM)
2817 if (purpose == DVIPDFM)
2821 if (purpose == DVIPS || purpose == DVIPDFM)
2825 if (purpose == DVIPS || purpose == DVIPDFM)
2829 if (purpose == DVIPS || purpose == DVIPDFM)
2833 if (purpose == DVIPS || purpose == DVIPDFM)
2837 if (purpose == DVIPS || purpose == DVIPDFM)
2841 if (purpose == DVIPS || purpose == DVIPDFM)
2845 if (purpose == DVIPS || purpose == DVIPDFM)
2849 if (purpose == DVIPS || purpose == DVIPDFM)
2853 if (purpose == DVIPS || purpose == DVIPDFM)
2857 if (purpose == DVIPS || purpose == DVIPDFM)
2861 if (purpose == DVIPS || purpose == DVIPDFM)
2865 if (purpose == DVIPS || purpose == DVIPDFM)
2869 if (purpose == DVIPS || purpose == DVIPDFM)
2873 if (purpose == DVIPS || purpose == DVIPDFM)
2877 if (purpose == DVIPS || purpose == DVIPDFM)
2880 case PAPER_USEXECUTIVE:
2881 // dvipdfm does not know this
2882 if (purpose == DVIPDFM)
2887 case PAPER_USLETTER:
2889 if (purpose == XDVI)
2896 string const BufferParams::dvips_options() const
2900 // If the class loads the geometry package, we do not know which
2901 // paper size is used, since we do not set it (bug 7013).
2902 // Therefore we must not specify any argument here.
2903 // dvips gets the correct paper size via DVI specials in this case
2904 // (if the class uses the geometry package correctly).
2905 if (documentClass().provides("geometry"))
2909 && papersize == PAPER_CUSTOM
2910 && !lyxrc.print_paper_dimension_flag.empty()
2911 && !paperwidth.empty()
2912 && !paperheight.empty()) {
2913 // using a custom papersize
2914 result = lyxrc.print_paper_dimension_flag;
2915 result += ' ' + paperwidth;
2916 result += ',' + paperheight;
2918 string const paper_option = paperSizeName(DVIPS);
2919 if (!paper_option.empty() && (paper_option != "letter" ||
2920 orientation != ORIENTATION_LANDSCAPE)) {
2921 // dvips won't accept -t letter -t landscape.
2922 // In all other cases, include the paper size
2924 result = lyxrc.print_paper_flag;
2925 result += ' ' + paper_option;
2928 if (orientation == ORIENTATION_LANDSCAPE &&
2929 papersize != PAPER_CUSTOM)
2930 result += ' ' + lyxrc.print_landscape_flag;
2935 string const BufferParams::font_encoding() const
2937 return font_encodings().empty() ? "default" : font_encodings().back();
2941 vector<string> const BufferParams::font_encodings() const
2943 string doc_fontenc = (fontenc == "global") ? lyxrc.fontenc : fontenc;
2945 vector<string> fontencs;
2947 // "default" means "no explicit font encoding"
2948 if (doc_fontenc != "default") {
2949 fontencs = getVectorFromString(doc_fontenc);
2950 if (!language->fontenc().empty()
2951 && ascii_lowercase(language->fontenc()) != "none") {
2952 vector<string> fencs = getVectorFromString(language->fontenc());
2953 vector<string>::const_iterator fit = fencs.begin();
2954 for (; fit != fencs.end(); ++fit) {
2955 if (find(fontencs.begin(), fontencs.end(), *fit) == fontencs.end())
2956 fontencs.push_back(*fit);
2965 string BufferParams::babelCall(string const & lang_opts, bool const langoptions) const
2967 // suppress the babel call if there is no BabelName defined
2968 // for the document language in the lib/languages file and if no
2969 // other languages are used (lang_opts is then empty)
2970 if (lang_opts.empty())
2972 // either a specific language (AsBabelOptions setting in
2973 // lib/languages) or the prefs require the languages to
2974 // be submitted to babel itself (not the class).
2976 return "\\usepackage[" + lang_opts + "]{babel}";
2977 return "\\usepackage{babel}";
2981 docstring BufferParams::getGraphicsDriver(string const & package) const
2985 if (package == "geometry") {
2986 if (graphics_driver == "dvips"
2987 || graphics_driver == "dvipdfm"
2988 || graphics_driver == "pdftex"
2989 || graphics_driver == "vtex")
2990 result = from_ascii(graphics_driver);
2991 else if (graphics_driver == "dvipdfmx")
2992 result = from_ascii("dvipdfm");
2999 void BufferParams::writeEncodingPreamble(otexstream & os,
3000 LaTeXFeatures & features) const
3002 // XeTeX/LuaTeX: (see also #9740)
3003 // With Unicode fonts we use utf8-plain without encoding package.
3004 // With TeX fonts, we cannot use utf8-plain, but "inputenc" fails.
3005 // XeTeX must use ASCII encoding (see Buffer.cpp),
3006 // for LuaTeX, we load "luainputenc" (see below).
3007 if (useNonTeXFonts || features.runparams().flavor == OutputParams::XETEX)
3010 if (inputenc == "auto") {
3011 string const doc_encoding =
3012 language->encoding()->latexName();
3013 Encoding::Package const package =
3014 language->encoding()->package();
3016 // Create list of inputenc options:
3017 set<string> encodings;
3018 // luainputenc fails with more than one encoding
3019 if (!features.runparams().isFullUnicode()) // if we reach this point, this means LuaTeX with TeX fonts
3020 // list all input encodings used in the document
3021 encodings = features.getEncodingSet(doc_encoding);
3023 // If the "japanese" package (i.e. pLaTeX) is used,
3024 // inputenc must be omitted.
3025 // see http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg129680.html
3026 if ((!encodings.empty() || package == Encoding::inputenc)
3027 && !features.isRequired("japanese")
3028 && !features.isProvided("inputenc")) {
3029 os << "\\usepackage[";
3030 set<string>::const_iterator it = encodings.begin();
3031 set<string>::const_iterator const end = encodings.end();
3033 os << from_ascii(*it);
3036 for (; it != end; ++it)
3037 os << ',' << from_ascii(*it);
3038 if (package == Encoding::inputenc) {
3039 if (!encodings.empty())
3041 os << from_ascii(doc_encoding);
3043 if (features.runparams().flavor == OutputParams::LUATEX
3044 || features.runparams().flavor == OutputParams::DVILUATEX)
3045 os << "]{luainputenc}\n";
3047 os << "]{inputenc}\n";
3049 if (package == Encoding::CJK || features.mustProvide("CJK")) {
3050 if (language->encoding()->name() == "utf8-cjk"
3051 && LaTeXFeatures::isAvailable("CJKutf8"))
3052 os << "\\usepackage{CJKutf8}\n";
3054 os << "\\usepackage{CJK}\n";
3056 } else if (inputenc != "default") {
3057 switch (encoding().package()) {
3058 case Encoding::none:
3059 case Encoding::japanese:
3061 case Encoding::inputenc:
3062 // do not load inputenc if japanese is used
3063 // or if the class provides inputenc
3064 if (features.isRequired("japanese")
3065 || features.isProvided("inputenc"))
3067 os << "\\usepackage[" << from_ascii(encoding().latexName());
3068 if (features.runparams().flavor == OutputParams::LUATEX
3069 || features.runparams().flavor == OutputParams::DVILUATEX)
3070 os << "]{luainputenc}\n";
3072 os << "]{inputenc}\n";
3075 if (encoding().name() == "utf8-cjk"
3076 && LaTeXFeatures::isAvailable("CJKutf8"))
3077 os << "\\usepackage{CJKutf8}\n";
3079 os << "\\usepackage{CJK}\n";
3082 // Load the CJK package if needed by a secondary language.
3083 // If the main encoding is some variant of UTF8, use CJKutf8.
3084 if (encoding().package() != Encoding::CJK && features.mustProvide("CJK")) {
3085 if (encoding().iconvName() == "UTF-8"
3086 && LaTeXFeatures::isAvailable("CJKutf8"))
3087 os << "\\usepackage{CJKutf8}\n";
3089 os << "\\usepackage{CJK}\n";
3095 string const BufferParams::parseFontName(string const & name) const
3097 string mangled = name;
3098 size_t const idx = mangled.find('[');
3099 if (idx == string::npos || idx == 0)
3102 return mangled.substr(0, idx - 1);
3106 string const BufferParams::loadFonts(LaTeXFeatures & features) const
3108 if (fontsRoman() == "default" && fontsSans() == "default"
3109 && fontsTypewriter() == "default"
3110 && (fontsMath() == "default" || fontsMath() == "auto"))
3116 /* Fontspec (XeTeX, LuaTeX): we provide GUI support for oldstyle
3117 * numbers (Numbers=OldStyle) and sf/tt scaling. The Ligatures=TeX/
3118 * Mapping=tex-text option assures TeX ligatures (such as "--")
3119 * are resolved. Note that tt does not use these ligatures.
3121 * -- add more GUI options?
3122 * -- add more fonts (fonts for other scripts)
3123 * -- if there's a way to find out if a font really supports
3124 * OldStyle, enable/disable the widget accordingly.
3126 if (useNonTeXFonts && features.isAvailable("fontspec")) {
3127 // "Mapping=tex-text" and "Ligatures=TeX" are equivalent.
3128 // However, until v.2 (2010/07/11) fontspec only knew
3129 // Mapping=tex-text (for XeTeX only); then "Ligatures=TeX"
3130 // was introduced for both XeTeX and LuaTeX (LuaTeX
3131 // didn't understand "Mapping=tex-text", while XeTeX
3132 // understood both. With most recent versions, both
3133 // variants are understood by both engines. However,
3134 // we want to provide support for at least TeXLive 2009
3135 // (for XeTeX; LuaTeX is only supported as of v.2)
3136 string const texmapping =
3137 (features.runparams().flavor == OutputParams::XETEX) ?
3138 "Mapping=tex-text" : "Ligatures=TeX";
3139 if (fontsRoman() != "default") {
3140 os << "\\setmainfont[" << texmapping;
3141 if (fonts_old_figures)
3142 os << ",Numbers=OldStyle";
3143 os << "]{" << parseFontName(fontsRoman()) << "}\n";
3145 if (fontsSans() != "default") {
3146 string const sans = parseFontName(fontsSans());
3147 if (fontsSansScale() != 100)
3148 os << "\\setsansfont[Scale="
3149 << float(fontsSansScale()) / 100
3150 << "," << texmapping << "]{"
3153 os << "\\setsansfont[" << texmapping << "]{"
3156 if (fontsTypewriter() != "default") {
3157 string const mono = parseFontName(fontsTypewriter());
3158 if (fontsTypewriterScale() != 100)
3159 os << "\\setmonofont[Scale="
3160 << float(fontsTypewriterScale()) / 100
3164 os << "\\setmonofont{"
3171 bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
3172 bool const dryrun = features.runparams().dryrun;
3173 bool const complete = (fontsSans() == "default" && fontsTypewriter() == "default");
3174 bool const nomath = (fontsMath() == "default");
3177 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsRoman())).getLaTeXCode(
3178 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3182 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsSans())).getLaTeXCode(
3183 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3184 nomath, fontsSansScale());
3186 // MONOSPACED/TYPEWRITER
3187 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsTypewriter())).getLaTeXCode(
3188 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3189 nomath, fontsTypewriterScale());
3192 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getLaTeXCode(
3193 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3200 Encoding const & BufferParams::encoding() const
3202 // Main encoding for LaTeX output.
3204 // Exception: XeTeX with 8-bit TeX fonts requires ASCII (see #9740).
3205 // As the "flavor" is only known once export started, this
3206 // cannot be handled here. Instead, runparams.encoding is set
3207 // to ASCII in Buffer::makeLaTeXFile (for export)
3208 // and Buffer::writeLaTeXSource (for preview).
3210 return *(encodings.fromLyXName("utf8-plain"));
3211 if (inputenc == "auto" || inputenc == "default")
3212 return *language->encoding();
3213 Encoding const * const enc = encodings.fromLyXName(inputenc);
3216 LYXERR0("Unknown inputenc value `" << inputenc
3217 << "'. Using `auto' instead.");
3218 return *language->encoding();
3222 bool BufferParams::addCiteEngine(string const & engine)
3224 LayoutModuleList::const_iterator it = cite_engine_.begin();
3225 LayoutModuleList::const_iterator en = cite_engine_.end();
3226 for (; it != en; ++it)
3229 cite_engine_.push_back(engine);
3234 bool BufferParams::addCiteEngine(vector<string> const & engine)
3236 vector<string>::const_iterator it = engine.begin();
3237 vector<string>::const_iterator en = engine.end();
3239 for (; it != en; ++it)
3240 if (!addCiteEngine(*it))
3246 string const & BufferParams::defaultBiblioStyle() const
3248 return documentClass().defaultBiblioStyle();
3252 bool const & BufferParams::fullAuthorList() const
3254 return documentClass().fullAuthorList();
3258 void BufferParams::setCiteEngine(string const & engine)
3261 addCiteEngine(engine);
3265 void BufferParams::setCiteEngine(vector<string> const & engine)
3268 addCiteEngine(engine);
3272 vector<string> BufferParams::citeCommands() const
3274 static CitationStyle const default_style;
3275 vector<string> commands =
3276 documentClass().citeCommands(citeEngineType());
3277 if (commands.empty())
3278 commands.push_back(default_style.cmd);
3283 vector<CitationStyle> BufferParams::citeStyles() const
3285 static CitationStyle const default_style;
3286 vector<CitationStyle> styles =
3287 documentClass().citeStyles(citeEngineType());
3289 styles.push_back(default_style);