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 features.resolveAlternatives();
1903 features.expandMultiples();
1906 if (!output_sync_macro.empty())
1907 os << from_utf8(output_sync_macro) +"\n";
1908 else if (features.runparams().flavor == OutputParams::LATEX)
1909 os << "\\usepackage[active]{srcltx}\n";
1910 else if (features.runparams().flavor == OutputParams::PDFLATEX)
1911 os << "\\synctex=-1\n";
1914 // The package options (via \PassOptionsToPackage)
1915 os << from_ascii(features.getPackageOptions());
1917 // due to interferences with babel and hyperref, the color package has to
1918 // be loaded (when it is not already loaded) before babel when hyperref
1919 // is used with the colorlinks option, see
1920 // http://www.lyx.org/trac/ticket/5291
1921 // we decided therefore to load color always before babel, see
1922 // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg144349.html
1923 os << from_ascii(features.getColorOptions());
1925 // If we use hyperref, jurabib, japanese, varioref or vietnamese,
1926 // we have to call babel before
1928 && (features.isRequired("jurabib")
1929 || features.isRequired("hyperref")
1930 || features.isRequired("varioref")
1931 || features.isRequired("vietnamese")
1932 || features.isRequired("japanese"))) {
1933 os << features.getBabelPresettings();
1935 os << from_utf8(babelCall(language_options.str(),
1936 features.needBabelLangOptions())) + '\n';
1937 os << features.getBabelPostsettings();
1940 // The optional packages;
1941 os << from_ascii(features.getPackages());
1943 // Additional Indices
1944 if (features.isRequired("splitidx")) {
1945 IndicesList::const_iterator iit = indiceslist().begin();
1946 IndicesList::const_iterator iend = indiceslist().end();
1947 for (; iit != iend; ++iit) {
1948 pair<docstring, docstring> indexname_latex =
1949 features.runparams().encoding->latexString(iit->index(),
1950 features.runparams().dryrun);
1951 if (!indexname_latex.second.empty()) {
1952 // issue a warning about omitted characters
1953 // FIXME: should be passed to the error dialog
1954 frontend::Alert::warning(_("Uncodable characters"),
1955 bformat(_("The following characters that are used in an index name are not\n"
1956 "representable in the current encoding and therefore have been omitted:\n%1$s."),
1957 indexname_latex.second));
1959 os << "\\newindex[";
1960 os << indexname_latex.first;
1962 os << escape(iit->shortcut());
1968 os << from_utf8(spacing().writePreamble(features.isProvided("SetSpace")));
1971 // * Hyperref manual: "Make sure it comes last of your loaded
1972 // packages, to give it a fighting chance of not being over-written,
1973 // since its job is to redefine many LaTeX commands."
1974 // * Email from Heiko Oberdiek: "It is usually better to load babel
1975 // before hyperref. Then hyperref has a chance to detect babel.
1976 // * Has to be loaded before the "LyX specific LaTeX commands" to
1977 // avoid errors with algorithm floats.
1978 // use hyperref explicitly if it is required
1979 if (features.isRequired("hyperref")) {
1980 OutputParams tmp_params = features.runparams();
1981 pdfoptions().writeLaTeX(tmp_params, os,
1982 features.isProvided("hyperref"));
1983 // correctly break URLs with hyperref and dvi output
1984 if (features.runparams().flavor == OutputParams::LATEX
1985 && features.isAvailable("breakurl"))
1986 os << "\\usepackage{breakurl}\n";
1987 } else if (features.isRequired("nameref"))
1988 // hyperref loads this automatically
1989 os << "\\usepackage{nameref}\n";
1991 // bibtopic needs to be loaded after hyperref.
1992 // the dot provides the aux file naming which LyX can detect.
1993 if (features.mustProvide("bibtopic"))
1994 os << "\\usepackage[dot]{bibtopic}\n";
1996 // Will be surrounded by \makeatletter and \makeatother when not empty
1997 docstring atlyxpreamble;
1999 // Some macros LyX will need
2000 docstring tmppreamble(features.getMacros());
2002 if (!tmppreamble.empty())
2003 atlyxpreamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2004 "LyX specific LaTeX commands.\n"
2005 + tmppreamble + '\n';
2007 // the text class specific preamble
2008 tmppreamble = features.getTClassPreamble();
2009 if (!tmppreamble.empty())
2010 atlyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2011 "Textclass specific LaTeX commands.\n"
2012 + tmppreamble + '\n';
2014 // suppress date if selected
2015 // use \@ifundefined because we cannot be sure that every document class
2016 // has a \date command
2018 atlyxpreamble += "\\@ifundefined{date}{}{\\date{}}\n";
2020 /* the user-defined preamble */
2021 if (!containsOnly(preamble, " \n\t")) {
2023 atlyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2024 "User specified LaTeX commands.\n";
2026 // Check if the user preamble contains uncodable glyphs
2027 odocstringstream user_preamble;
2028 docstring uncodable_glyphs;
2029 Encoding const * const enc = features.runparams().encoding;
2031 for (size_t n = 0; n < preamble.size(); ++n) {
2032 char_type c = preamble[n];
2033 if (!enc->encodable(c)) {
2034 docstring const glyph(1, c);
2035 LYXERR0("Uncodable character '"
2037 << "' in user preamble!");
2038 uncodable_glyphs += glyph;
2039 if (features.runparams().dryrun) {
2040 user_preamble << "<" << _("LyX Warning: ")
2041 << _("uncodable character") << " '";
2042 user_preamble.put(c);
2043 user_preamble << "'>";
2046 user_preamble.put(c);
2049 user_preamble << preamble;
2051 // On BUFFER_VIEW|UPDATE, warn user if we found uncodable glyphs
2052 if (!features.runparams().dryrun && !uncodable_glyphs.empty()) {
2053 frontend::Alert::warning(
2054 _("Uncodable character in user preamble"),
2056 _("The user preamble of your document contains glyphs "
2057 "that are unknown in the current document encoding "
2058 "(namely %1$s).\nThese glyphs are omitted "
2059 " from the output, which may result in "
2060 "incomplete output."
2061 "\n\nPlease select an appropriate "
2062 "document encoding\n"
2063 "(such as utf8) or change the "
2064 "preamble code accordingly."),
2067 atlyxpreamble += user_preamble.str() + '\n';
2070 // footmisc must be loaded after setspace
2071 // Load it here to avoid clashes with footmisc loaded in the user
2072 // preamble. For that reason we also pass the options via
2073 // \PassOptionsToPackage in getPreamble() and not here.
2074 if (features.mustProvide("footmisc"))
2075 atlyxpreamble += "\\usepackage{footmisc}\n";
2077 // subfig loads internally the LaTeX package "caption". As
2078 // caption is a very popular package, users will load it in
2079 // the preamble. Therefore we must load subfig behind the
2080 // user-defined preamble and check if the caption package was
2081 // loaded or not. For the case that caption is loaded before
2082 // subfig, there is the subfig option "caption=false". This
2083 // option also works when a koma-script class is used and
2084 // koma's own caption commands are used instead of caption. We
2085 // use \PassOptionsToPackage here because the user could have
2086 // already loaded subfig in the preamble.
2087 if (features.mustProvide("subfig")) {
2088 atlyxpreamble += "\\@ifundefined{showcaptionsetup}{}{%\n"
2089 " \\PassOptionsToPackage{caption=false}{subfig}}\n"
2090 "\\usepackage{subfig}\n";
2093 // Itemize bullet settings need to be last in case the user
2094 // defines their own bullets that use a package included
2095 // in the user-defined preamble -- ARRae
2096 // Actually it has to be done much later than that
2097 // since some packages like frenchb make modifications
2098 // at \begin{document} time -- JMarc
2099 docstring bullets_def;
2100 for (int i = 0; i < 4; ++i) {
2101 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
2102 if (bullets_def.empty())
2103 bullets_def += "\\AtBeginDocument{\n";
2104 bullets_def += " \\def\\labelitemi";
2106 // `i' is one less than the item to modify
2113 bullets_def += "ii";
2119 bullets_def += '{' +
2120 user_defined_bullet(i).getText()
2125 if (!bullets_def.empty())
2126 atlyxpreamble += bullets_def + "}\n\n";
2128 if (!atlyxpreamble.empty()) {
2129 os << "\n\\makeatletter\n"
2131 << "\\makeatother\n\n";
2134 // We try to load babel late, in case it interferes with other packages.
2135 // Jurabib, hyperref, varioref, bicaption and listings (bug 8995) have to be
2136 // called after babel, though.
2137 if (use_babel && !features.isRequired("jurabib")
2138 && !features.isRequired("hyperref")
2139 && !features.isRequired("varioref")
2140 && !features.isRequired("vietnamese")
2141 && !features.isRequired("japanese")) {
2142 os << features.getBabelPresettings();
2144 os << from_utf8(babelCall(language_options.str(),
2145 features.needBabelLangOptions())) + '\n';
2146 os << features.getBabelPostsettings();
2148 if (features.isRequired("bicaption"))
2149 os << "\\usepackage{bicaption}\n";
2150 if (!listings_params.empty() || features.mustProvide("listings"))
2151 os << "\\usepackage{listings}\n";
2152 if (!listings_params.empty()) {
2154 // do not test validity because listings_params is
2155 // supposed to be valid
2157 InsetListingsParams(listings_params).separatedParams(true);
2158 os << from_utf8(par);
2162 // xunicode needs to be loaded at least after amsmath, amssymb,
2163 // esint and the other packages that provide special glyphs
2164 // The package only supports XeTeX currently.
2165 if (features.runparams().flavor == OutputParams::XETEX
2167 os << "\\usepackage{xunicode}\n";
2169 // Polyglossia must be loaded last
2170 if (use_polyglossia) {
2172 os << "\\usepackage{polyglossia}\n";
2173 // set the main language
2174 os << "\\setdefaultlanguage";
2175 if (!language->polyglossiaOpts().empty())
2176 os << "[" << from_ascii(language->polyglossiaOpts()) << "]";
2177 os << "{" << from_ascii(language->polyglossia()) << "}\n";
2178 // now setup the other languages
2179 std::map<std::string, std::string> const polylangs =
2180 features.getPolyglossiaLanguages();
2181 for (std::map<std::string, std::string>::const_iterator mit = polylangs.begin();
2182 mit != polylangs.end() ; ++mit) {
2183 os << "\\setotherlanguage";
2184 if (!mit->second.empty())
2185 os << "[" << from_ascii(mit->second) << "]";
2186 os << "{" << from_ascii(mit->first) << "}\n";
2190 // Load custom language package here
2191 if (features.langPackage() == LaTeXFeatures::LANG_PACK_CUSTOM) {
2192 if (lang_package == "default")
2193 os << from_utf8(lyxrc.language_custom_package);
2195 os << from_utf8(lang_package);
2199 docstring const i18npreamble =
2200 features.getTClassI18nPreamble(use_babel, use_polyglossia);
2201 if (!i18npreamble.empty())
2202 os << i18npreamble + '\n';
2208 void BufferParams::useClassDefaults()
2210 DocumentClass const & tclass = documentClass();
2212 sides = tclass.sides();
2213 columns = tclass.columns();
2214 pagestyle = tclass.pagestyle();
2215 use_default_options = true;
2216 // Only if class has a ToC hierarchy
2217 if (tclass.hasTocLevels()) {
2218 secnumdepth = tclass.secnumdepth();
2219 tocdepth = tclass.tocdepth();
2224 bool BufferParams::hasClassDefaults() const
2226 DocumentClass const & tclass = documentClass();
2228 return sides == tclass.sides()
2229 && columns == tclass.columns()
2230 && pagestyle == tclass.pagestyle()
2231 && use_default_options
2232 && secnumdepth == tclass.secnumdepth()
2233 && tocdepth == tclass.tocdepth();
2237 DocumentClass const & BufferParams::documentClass() const
2243 DocumentClassConstPtr BufferParams::documentClassPtr() const
2249 void BufferParams::setDocumentClass(DocumentClassConstPtr tc)
2251 // evil, but this function is evil
2252 doc_class_ = const_pointer_cast<DocumentClass>(tc);
2256 bool BufferParams::setBaseClass(string const & classname)
2258 LYXERR(Debug::TCLASS, "setBaseClass: " << classname);
2259 LayoutFileList & bcl = LayoutFileList::get();
2260 if (!bcl.haveClass(classname)) {
2262 bformat(_("The layout file:\n"
2264 "could not be found. A default textclass with default\n"
2265 "layouts will be used. LyX will not be able to produce\n"
2267 from_utf8(classname));
2268 frontend::Alert::error(_("Document class not found"), s);
2269 bcl.addEmptyClass(classname);
2272 bool const success = bcl[classname].load();
2275 bformat(_("Due to some error in it, the layout file:\n"
2277 "could not be loaded. A default textclass with default\n"
2278 "layouts will be used. LyX will not be able to produce\n"
2280 from_utf8(classname));
2281 frontend::Alert::error(_("Could not load class"), s);
2282 bcl.addEmptyClass(classname);
2285 pimpl_->baseClass_ = classname;
2286 layout_modules_.adaptToBaseClass(baseClass(), removed_modules_);
2291 LayoutFile const * BufferParams::baseClass() const
2293 if (LayoutFileList::get().haveClass(pimpl_->baseClass_))
2294 return &(LayoutFileList::get()[pimpl_->baseClass_]);
2300 LayoutFileIndex const & BufferParams::baseClassID() const
2302 return pimpl_->baseClass_;
2306 void BufferParams::makeDocumentClass(bool const clone)
2311 LayoutModuleList mods;
2312 LayoutModuleList::iterator it = layout_modules_.begin();
2313 LayoutModuleList::iterator en = layout_modules_.end();
2314 for (; it != en; ++it)
2315 mods.push_back(*it);
2317 it = cite_engine_.begin();
2318 en = cite_engine_.end();
2319 for (; it != en; ++it)
2320 mods.push_back(*it);
2322 doc_class_ = getDocumentClass(*baseClass(), mods, clone);
2324 TextClass::ReturnValues success = TextClass::OK;
2325 if (!forced_local_layout_.empty())
2326 success = doc_class_->read(to_utf8(forced_local_layout_),
2328 if (!local_layout_.empty() &&
2329 (success == TextClass::OK || success == TextClass::OK_OLDFORMAT))
2330 success = doc_class_->read(to_utf8(local_layout_), TextClass::MODULE);
2331 if (success != TextClass::OK && success != TextClass::OK_OLDFORMAT) {
2332 docstring const msg = _("Error reading internal layout information");
2333 frontend::Alert::warning(_("Read Error"), msg);
2338 bool BufferParams::layoutModuleCanBeAdded(string const & modName) const
2340 return layout_modules_.moduleCanBeAdded(modName, baseClass());
2344 bool BufferParams::citationModuleCanBeAdded(string const & modName) const
2346 return cite_engine_.moduleCanBeAdded(modName, baseClass());
2350 docstring BufferParams::getLocalLayout(bool forced) const
2353 return from_utf8(doc_class_->forcedLayouts());
2355 return local_layout_;
2359 void BufferParams::setLocalLayout(docstring const & layout, bool forced)
2362 forced_local_layout_ = layout;
2364 local_layout_ = layout;
2368 bool BufferParams::addLayoutModule(string const & modName)
2370 LayoutModuleList::const_iterator it = layout_modules_.begin();
2371 LayoutModuleList::const_iterator end = layout_modules_.end();
2372 for (; it != end; ++it)
2375 layout_modules_.push_back(modName);
2380 string BufferParams::bufferFormat() const
2382 return documentClass().outputFormat();
2386 bool BufferParams::isExportable(string const & format) const
2388 vector<string> backs = backends();
2389 for (vector<string>::const_iterator it = backs.begin();
2390 it != backs.end(); ++it)
2391 if (theConverters().isReachable(*it, format))
2397 vector<Format const *> BufferParams::exportableFormats(bool only_viewable) const
2399 vector<string> const backs = backends();
2400 set<string> excludes;
2401 if (useNonTeXFonts) {
2402 excludes.insert("latex");
2403 excludes.insert("pdflatex");
2405 vector<Format const *> result =
2406 theConverters().getReachable(backs[0], only_viewable, true, excludes);
2407 for (vector<string>::const_iterator it = backs.begin() + 1;
2408 it != backs.end(); ++it) {
2409 vector<Format const *> r =
2410 theConverters().getReachable(*it, only_viewable, false, excludes);
2411 result.insert(result.end(), r.begin(), r.end());
2417 bool BufferParams::isExportableFormat(string const & format) const
2419 typedef vector<Format const *> Formats;
2421 formats = exportableFormats(true);
2422 Formats::const_iterator fit = formats.begin();
2423 Formats::const_iterator end = formats.end();
2424 for (; fit != end ; ++fit) {
2425 if ((*fit)->name() == format)
2432 vector<string> BufferParams::backends() const
2435 string const buffmt = bufferFormat();
2437 // FIXME: Don't hardcode format names here, but use a flag
2438 if (buffmt == "latex") {
2439 if (encoding().package() == Encoding::japanese)
2440 v.push_back("platex");
2442 if (!useNonTeXFonts) {
2443 v.push_back("pdflatex");
2444 v.push_back("latex");
2446 v.push_back("xetex");
2447 v.push_back("luatex");
2448 v.push_back("dviluatex");
2451 v.push_back(buffmt);
2453 v.push_back("xhtml");
2454 v.push_back("text");
2460 OutputParams::FLAVOR BufferParams::getOutputFlavor(string const & format) const
2462 string const dformat = (format.empty() || format == "default") ?
2463 getDefaultOutputFormat() : format;
2464 DefaultFlavorCache::const_iterator it =
2465 default_flavors_.find(dformat);
2467 if (it != default_flavors_.end())
2470 OutputParams::FLAVOR result = OutputParams::LATEX;
2472 // FIXME It'd be better not to hardcode this, but to do
2473 // something with formats.
2474 if (dformat == "xhtml")
2475 result = OutputParams::HTML;
2476 else if (dformat == "text")
2477 result = OutputParams::TEXT;
2478 else if (dformat == "lyx")
2479 result = OutputParams::LYX;
2480 else if (dformat == "pdflatex")
2481 result = OutputParams::PDFLATEX;
2482 else if (dformat == "xetex")
2483 result = OutputParams::XETEX;
2484 else if (dformat == "luatex")
2485 result = OutputParams::LUATEX;
2486 else if (dformat == "dviluatex")
2487 result = OutputParams::DVILUATEX;
2489 // Try to determine flavor of default output format
2490 vector<string> backs = backends();
2491 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
2492 // Get shortest path to format
2493 Graph::EdgePath path;
2494 for (vector<string>::const_iterator it = backs.begin();
2495 it != backs.end(); ++it) {
2496 Graph::EdgePath p = theConverters().getPath(*it, dformat);
2497 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2502 result = theConverters().getFlavor(path);
2505 // cache this flavor
2506 default_flavors_[dformat] = result;
2511 string BufferParams::getDefaultOutputFormat() const
2513 if (!default_output_format.empty()
2514 && default_output_format != "default")
2515 return default_output_format;
2517 || encoding().package() == Encoding::japanese) {
2518 vector<Format const *> const formats = exportableFormats(true);
2519 if (formats.empty())
2521 // return the first we find
2522 return formats.front()->name();
2525 return lyxrc.default_otf_view_format;
2526 return lyxrc.default_view_format;
2529 Font const BufferParams::getFont() const
2531 FontInfo f = documentClass().defaultfont();
2532 if (fonts_default_family == "rmdefault")
2533 f.setFamily(ROMAN_FAMILY);
2534 else if (fonts_default_family == "sfdefault")
2535 f.setFamily(SANS_FAMILY);
2536 else if (fonts_default_family == "ttdefault")
2537 f.setFamily(TYPEWRITER_FAMILY);
2538 return Font(f, language);
2542 InsetQuotes::QuoteLanguage BufferParams::getQuoteStyle(string const & qs) const
2544 return quoteslangtranslator().find(qs);
2548 bool BufferParams::isLatex() const
2550 return documentClass().outputType() == LATEX;
2554 bool BufferParams::isLiterate() const
2556 return documentClass().outputType() == LITERATE;
2560 bool BufferParams::isDocBook() const
2562 return documentClass().outputType() == DOCBOOK;
2566 void BufferParams::readPreamble(Lexer & lex)
2568 if (lex.getString() != "\\begin_preamble")
2569 lyxerr << "Error (BufferParams::readPreamble):"
2570 "consistency check failed." << endl;
2572 preamble = lex.getLongString(from_ascii("\\end_preamble"));
2576 void BufferParams::readLocalLayout(Lexer & lex, bool forced)
2578 string const expected = forced ? "\\begin_forced_local_layout" :
2579 "\\begin_local_layout";
2580 if (lex.getString() != expected)
2581 lyxerr << "Error (BufferParams::readLocalLayout):"
2582 "consistency check failed." << endl;
2585 forced_local_layout_ =
2586 lex.getLongString(from_ascii("\\end_forced_local_layout"));
2588 local_layout_ = lex.getLongString(from_ascii("\\end_local_layout"));
2592 bool BufferParams::setLanguage(string const & lang)
2594 Language const *new_language = languages.getLanguage(lang);
2595 if (!new_language) {
2596 // Language lang was not found
2599 language = new_language;
2604 void BufferParams::readLanguage(Lexer & lex)
2606 if (!lex.next()) return;
2608 string const tmptok = lex.getString();
2610 // check if tmptok is part of tex_babel in tex-defs.h
2611 if (!setLanguage(tmptok)) {
2612 // Language tmptok was not found
2613 language = default_language;
2614 lyxerr << "Warning: Setting language `"
2615 << tmptok << "' to `" << language->lang()
2621 void BufferParams::readGraphicsDriver(Lexer & lex)
2626 string const tmptok = lex.getString();
2627 // check if tmptok is part of tex_graphics in tex_defs.h
2630 string const test = tex_graphics[n++];
2632 if (test == tmptok) {
2633 graphics_driver = tmptok;
2638 "Warning: graphics driver `$$Token' not recognized!\n"
2639 " Setting graphics driver to `default'.\n");
2640 graphics_driver = "default";
2647 void BufferParams::readBullets(Lexer & lex)
2652 int const index = lex.getInteger();
2654 int temp_int = lex.getInteger();
2655 user_defined_bullet(index).setFont(temp_int);
2656 temp_bullet(index).setFont(temp_int);
2658 user_defined_bullet(index).setCharacter(temp_int);
2659 temp_bullet(index).setCharacter(temp_int);
2661 user_defined_bullet(index).setSize(temp_int);
2662 temp_bullet(index).setSize(temp_int);
2666 void BufferParams::readBulletsLaTeX(Lexer & lex)
2668 // The bullet class should be able to read this.
2671 int const index = lex.getInteger();
2673 docstring const temp_str = lex.getDocString();
2675 user_defined_bullet(index).setText(temp_str);
2676 temp_bullet(index).setText(temp_str);
2680 void BufferParams::readModules(Lexer & lex)
2682 if (!lex.eatLine()) {
2683 lyxerr << "Error (BufferParams::readModules):"
2684 "Unexpected end of input." << endl;
2688 string mod = lex.getString();
2689 if (mod == "\\end_modules")
2691 addLayoutModule(mod);
2697 void BufferParams::readRemovedModules(Lexer & lex)
2699 if (!lex.eatLine()) {
2700 lyxerr << "Error (BufferParams::readRemovedModules):"
2701 "Unexpected end of input." << endl;
2705 string mod = lex.getString();
2706 if (mod == "\\end_removed_modules")
2708 removed_modules_.push_back(mod);
2711 // now we want to remove any removed modules that were previously
2712 // added. normally, that will be because default modules were added in
2713 // setBaseClass(), which gets called when \textclass is read at the
2714 // start of the read.
2715 list<string>::const_iterator rit = removed_modules_.begin();
2716 list<string>::const_iterator const ren = removed_modules_.end();
2717 for (; rit != ren; ++rit) {
2718 LayoutModuleList::iterator const mit = layout_modules_.begin();
2719 LayoutModuleList::iterator const men = layout_modules_.end();
2720 LayoutModuleList::iterator found = find(mit, men, *rit);
2723 layout_modules_.erase(found);
2728 void BufferParams::readIncludeonly(Lexer & lex)
2730 if (!lex.eatLine()) {
2731 lyxerr << "Error (BufferParams::readIncludeonly):"
2732 "Unexpected end of input." << endl;
2736 string child = lex.getString();
2737 if (child == "\\end_includeonly")
2739 included_children_.push_back(child);
2745 string BufferParams::paperSizeName(PapersizePurpose purpose) const
2747 switch (papersize) {
2749 // could be anything, so don't guess
2751 case PAPER_CUSTOM: {
2752 if (purpose == XDVI && !paperwidth.empty() &&
2753 !paperheight.empty()) {
2754 // heightxwidth<unit>
2755 string first = paperwidth;
2756 string second = paperheight;
2757 if (orientation == ORIENTATION_LANDSCAPE)
2760 return first.erase(first.length() - 2)
2766 // dvips and dvipdfm do not know this
2767 if (purpose == DVIPS || purpose == DVIPDFM)
2771 if (purpose == DVIPS || purpose == DVIPDFM)
2775 if (purpose == DVIPS || purpose == DVIPDFM)
2785 if (purpose == DVIPS || purpose == DVIPDFM)
2789 if (purpose == DVIPS || purpose == DVIPDFM)
2793 if (purpose == DVIPS || purpose == DVIPDFM)
2797 if (purpose == DVIPS || purpose == DVIPDFM)
2801 if (purpose == DVIPS || purpose == DVIPDFM)
2805 // dvipdfm does not know this
2806 if (purpose == DVIPDFM)
2810 if (purpose == DVIPDFM)
2814 if (purpose == DVIPS || purpose == DVIPDFM)
2818 if (purpose == DVIPS || purpose == DVIPDFM)
2822 if (purpose == DVIPS || purpose == DVIPDFM)
2826 if (purpose == DVIPS || purpose == DVIPDFM)
2830 if (purpose == DVIPS || purpose == DVIPDFM)
2834 if (purpose == DVIPS || purpose == DVIPDFM)
2838 if (purpose == DVIPS || purpose == DVIPDFM)
2842 if (purpose == DVIPS || purpose == DVIPDFM)
2846 if (purpose == DVIPS || purpose == DVIPDFM)
2850 if (purpose == DVIPS || purpose == DVIPDFM)
2854 if (purpose == DVIPS || purpose == DVIPDFM)
2858 if (purpose == DVIPS || purpose == DVIPDFM)
2862 if (purpose == DVIPS || purpose == DVIPDFM)
2866 if (purpose == DVIPS || purpose == DVIPDFM)
2870 if (purpose == DVIPS || purpose == DVIPDFM)
2873 case PAPER_USEXECUTIVE:
2874 // dvipdfm does not know this
2875 if (purpose == DVIPDFM)
2880 case PAPER_USLETTER:
2882 if (purpose == XDVI)
2889 string const BufferParams::dvips_options() const
2893 // If the class loads the geometry package, we do not know which
2894 // paper size is used, since we do not set it (bug 7013).
2895 // Therefore we must not specify any argument here.
2896 // dvips gets the correct paper size via DVI specials in this case
2897 // (if the class uses the geometry package correctly).
2898 if (documentClass().provides("geometry"))
2902 && papersize == PAPER_CUSTOM
2903 && !lyxrc.print_paper_dimension_flag.empty()
2904 && !paperwidth.empty()
2905 && !paperheight.empty()) {
2906 // using a custom papersize
2907 result = lyxrc.print_paper_dimension_flag;
2908 result += ' ' + paperwidth;
2909 result += ',' + paperheight;
2911 string const paper_option = paperSizeName(DVIPS);
2912 if (!paper_option.empty() && (paper_option != "letter" ||
2913 orientation != ORIENTATION_LANDSCAPE)) {
2914 // dvips won't accept -t letter -t landscape.
2915 // In all other cases, include the paper size
2917 result = lyxrc.print_paper_flag;
2918 result += ' ' + paper_option;
2921 if (orientation == ORIENTATION_LANDSCAPE &&
2922 papersize != PAPER_CUSTOM)
2923 result += ' ' + lyxrc.print_landscape_flag;
2928 string const BufferParams::font_encoding() const
2930 return font_encodings().empty() ? "default" : font_encodings().back();
2934 vector<string> const BufferParams::font_encodings() const
2936 string doc_fontenc = (fontenc == "global") ? lyxrc.fontenc : fontenc;
2938 vector<string> fontencs;
2940 // "default" means "no explicit font encoding"
2941 if (doc_fontenc != "default") {
2942 fontencs = getVectorFromString(doc_fontenc);
2943 if (!language->fontenc().empty()
2944 && ascii_lowercase(language->fontenc()) != "none") {
2945 vector<string> fencs = getVectorFromString(language->fontenc());
2946 vector<string>::const_iterator fit = fencs.begin();
2947 for (; fit != fencs.end(); ++fit) {
2948 if (find(fontencs.begin(), fontencs.end(), *fit) == fontencs.end())
2949 fontencs.push_back(*fit);
2958 string BufferParams::babelCall(string const & lang_opts, bool const langoptions) const
2960 // suppress the babel call if there is no BabelName defined
2961 // for the document language in the lib/languages file and if no
2962 // other languages are used (lang_opts is then empty)
2963 if (lang_opts.empty())
2965 // either a specific language (AsBabelOptions setting in
2966 // lib/languages) or the prefs require the languages to
2967 // be submitted to babel itself (not the class).
2969 return "\\usepackage[" + lang_opts + "]{babel}";
2970 return "\\usepackage{babel}";
2974 docstring BufferParams::getGraphicsDriver(string const & package) const
2978 if (package == "geometry") {
2979 if (graphics_driver == "dvips"
2980 || graphics_driver == "dvipdfm"
2981 || graphics_driver == "pdftex"
2982 || graphics_driver == "vtex")
2983 result = from_ascii(graphics_driver);
2984 else if (graphics_driver == "dvipdfmx")
2985 result = from_ascii("dvipdfm");
2992 void BufferParams::writeEncodingPreamble(otexstream & os,
2993 LaTeXFeatures & features) const
2995 // XeTeX/LuaTeX: (see also #9740)
2996 // With Unicode fonts we use utf8-plain without encoding package.
2997 // With TeX fonts, we cannot use utf8-plain, but "inputenc" fails.
2998 // XeTeX must use ASCII encoding (see Buffer.cpp),
2999 // for LuaTeX, we load "luainputenc" (see below).
3000 if (useNonTeXFonts || features.runparams().flavor == OutputParams::XETEX)
3003 if (inputenc == "auto") {
3004 string const doc_encoding =
3005 language->encoding()->latexName();
3006 Encoding::Package const package =
3007 language->encoding()->package();
3009 // Create list of inputenc options:
3010 set<string> encodings;
3011 // luainputenc fails with more than one encoding
3012 if (!features.runparams().isFullUnicode()) // if we reach this point, this means LuaTeX with TeX fonts
3013 // list all input encodings used in the document
3014 encodings = features.getEncodingSet(doc_encoding);
3016 // If the "japanese" package (i.e. pLaTeX) is used,
3017 // inputenc must be omitted.
3018 // see http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg129680.html
3019 if ((!encodings.empty() || package == Encoding::inputenc)
3020 && !features.isRequired("japanese")
3021 && !features.isProvided("inputenc")) {
3022 os << "\\usepackage[";
3023 set<string>::const_iterator it = encodings.begin();
3024 set<string>::const_iterator const end = encodings.end();
3026 os << from_ascii(*it);
3029 for (; it != end; ++it)
3030 os << ',' << from_ascii(*it);
3031 if (package == Encoding::inputenc) {
3032 if (!encodings.empty())
3034 os << from_ascii(doc_encoding);
3036 if (features.runparams().flavor == OutputParams::LUATEX
3037 || features.runparams().flavor == OutputParams::DVILUATEX)
3038 os << "]{luainputenc}\n";
3040 os << "]{inputenc}\n";
3042 if (package == Encoding::CJK || features.mustProvide("CJK")) {
3043 if (language->encoding()->name() == "utf8-cjk"
3044 && LaTeXFeatures::isAvailable("CJKutf8"))
3045 os << "\\usepackage{CJKutf8}\n";
3047 os << "\\usepackage{CJK}\n";
3049 } else if (inputenc != "default") {
3050 switch (encoding().package()) {
3051 case Encoding::none:
3052 case Encoding::japanese:
3054 case Encoding::inputenc:
3055 // do not load inputenc if japanese is used
3056 // or if the class provides inputenc
3057 if (features.isRequired("japanese")
3058 || features.isProvided("inputenc"))
3060 os << "\\usepackage[" << from_ascii(encoding().latexName());
3061 if (features.runparams().flavor == OutputParams::LUATEX
3062 || features.runparams().flavor == OutputParams::DVILUATEX)
3063 os << "]{luainputenc}\n";
3065 os << "]{inputenc}\n";
3068 if (encoding().name() == "utf8-cjk"
3069 && LaTeXFeatures::isAvailable("CJKutf8"))
3070 os << "\\usepackage{CJKutf8}\n";
3072 os << "\\usepackage{CJK}\n";
3075 // Load the CJK package if needed by a secondary language.
3076 // If the main encoding is some variant of UTF8, use CJKutf8.
3077 if (encoding().package() != Encoding::CJK && features.mustProvide("CJK")) {
3078 if (encoding().iconvName() == "UTF-8"
3079 && LaTeXFeatures::isAvailable("CJKutf8"))
3080 os << "\\usepackage{CJKutf8}\n";
3082 os << "\\usepackage{CJK}\n";
3088 string const BufferParams::parseFontName(string const & name) const
3090 string mangled = name;
3091 size_t const idx = mangled.find('[');
3092 if (idx == string::npos || idx == 0)
3095 return mangled.substr(0, idx - 1);
3099 string const BufferParams::loadFonts(LaTeXFeatures & features) const
3101 if (fontsRoman() == "default" && fontsSans() == "default"
3102 && fontsTypewriter() == "default"
3103 && (fontsMath() == "default" || fontsMath() == "auto"))
3109 /* Fontspec (XeTeX, LuaTeX): we provide GUI support for oldstyle
3110 * numbers (Numbers=OldStyle) and sf/tt scaling. The Ligatures=TeX/
3111 * Mapping=tex-text option assures TeX ligatures (such as "--")
3112 * are resolved. Note that tt does not use these ligatures.
3114 * -- add more GUI options?
3115 * -- add more fonts (fonts for other scripts)
3116 * -- if there's a way to find out if a font really supports
3117 * OldStyle, enable/disable the widget accordingly.
3119 if (useNonTeXFonts && features.isAvailable("fontspec")) {
3120 // "Mapping=tex-text" and "Ligatures=TeX" are equivalent.
3121 // However, until v.2 (2010/07/11) fontspec only knew
3122 // Mapping=tex-text (for XeTeX only); then "Ligatures=TeX"
3123 // was introduced for both XeTeX and LuaTeX (LuaTeX
3124 // didn't understand "Mapping=tex-text", while XeTeX
3125 // understood both. With most recent versions, both
3126 // variants are understood by both engines. However,
3127 // we want to provide support for at least TeXLive 2009
3128 // (for XeTeX; LuaTeX is only supported as of v.2)
3129 string const texmapping =
3130 (features.runparams().flavor == OutputParams::XETEX) ?
3131 "Mapping=tex-text" : "Ligatures=TeX";
3132 if (fontsRoman() != "default") {
3133 os << "\\setmainfont[" << texmapping;
3134 if (fonts_old_figures)
3135 os << ",Numbers=OldStyle";
3136 os << "]{" << parseFontName(fontsRoman()) << "}\n";
3138 if (fontsSans() != "default") {
3139 string const sans = parseFontName(fontsSans());
3140 if (fontsSansScale() != 100)
3141 os << "\\setsansfont[Scale="
3142 << float(fontsSansScale()) / 100
3143 << "," << texmapping << "]{"
3146 os << "\\setsansfont[" << texmapping << "]{"
3149 if (fontsTypewriter() != "default") {
3150 string const mono = parseFontName(fontsTypewriter());
3151 if (fontsTypewriterScale() != 100)
3152 os << "\\setmonofont[Scale="
3153 << float(fontsTypewriterScale()) / 100
3157 os << "\\setmonofont{"
3164 bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
3165 bool const dryrun = features.runparams().dryrun;
3166 bool const complete = (fontsSans() == "default" && fontsTypewriter() == "default");
3167 bool const nomath = (fontsMath() == "default");
3170 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsRoman())).getLaTeXCode(
3171 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3175 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsSans())).getLaTeXCode(
3176 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3177 nomath, fontsSansScale());
3179 // MONOSPACED/TYPEWRITER
3180 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsTypewriter())).getLaTeXCode(
3181 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3182 nomath, fontsTypewriterScale());
3185 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getLaTeXCode(
3186 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3193 Encoding const & BufferParams::encoding() const
3195 // Main encoding for LaTeX output.
3197 // Exception: XeTeX with 8-bit TeX fonts requires ASCII (see #9740).
3198 // As the "flavor" is only known once export started, this
3199 // cannot be handled here. Instead, runparams.encoding is set
3200 // to ASCII in Buffer::makeLaTeXFile (for export)
3201 // and Buffer::writeLaTeXSource (for preview).
3203 return *(encodings.fromLyXName("utf8-plain"));
3204 if (inputenc == "auto" || inputenc == "default")
3205 return *language->encoding();
3206 Encoding const * const enc = encodings.fromLyXName(inputenc);
3209 LYXERR0("Unknown inputenc value `" << inputenc
3210 << "'. Using `auto' instead.");
3211 return *language->encoding();
3215 bool BufferParams::addCiteEngine(string const & engine)
3217 LayoutModuleList::const_iterator it = cite_engine_.begin();
3218 LayoutModuleList::const_iterator en = cite_engine_.end();
3219 for (; it != en; ++it)
3222 cite_engine_.push_back(engine);
3227 bool BufferParams::addCiteEngine(vector<string> const & engine)
3229 vector<string>::const_iterator it = engine.begin();
3230 vector<string>::const_iterator en = engine.end();
3232 for (; it != en; ++it)
3233 if (!addCiteEngine(*it))
3239 string const & BufferParams::defaultBiblioStyle() const
3241 return documentClass().defaultBiblioStyle();
3245 bool const & BufferParams::fullAuthorList() const
3247 return documentClass().fullAuthorList();
3251 void BufferParams::setCiteEngine(string const & engine)
3254 addCiteEngine(engine);
3258 void BufferParams::setCiteEngine(vector<string> const & engine)
3261 addCiteEngine(engine);
3265 vector<string> BufferParams::citeCommands() const
3267 static CitationStyle const default_style;
3268 vector<string> commands =
3269 documentClass().citeCommands(citeEngineType());
3270 if (commands.empty())
3271 commands.push_back(default_style.cmd);
3276 vector<CitationStyle> BufferParams::citeStyles() const
3278 static CitationStyle const default_style;
3279 vector<CitationStyle> styles =
3280 documentClass().citeStyles(citeEngineType());
3282 styles.push_back(default_style);