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 otexstringstream atlyxpreamble;
1999 // Some macros LyX will need
2001 TexString tmppreamble = features.getMacros();
2002 if (!tmppreamble.str.empty())
2003 atlyxpreamble << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2004 "LyX specific LaTeX commands.\n"
2005 << move(tmppreamble)
2008 // the text class specific preamble
2010 docstring tmppreamble = features.getTClassPreamble();
2011 if (!tmppreamble.empty())
2012 atlyxpreamble << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2013 "Textclass specific LaTeX commands.\n"
2017 // suppress date if selected
2018 // use \@ifundefined because we cannot be sure that every document class
2019 // has a \date command
2021 atlyxpreamble << "\\@ifundefined{date}{}{\\date{}}\n";
2023 /* the user-defined preamble */
2024 if (!containsOnly(preamble, " \n\t")) {
2026 atlyxpreamble << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2027 "User specified LaTeX commands.\n";
2029 // Check if the user preamble contains uncodable glyphs
2030 odocstringstream user_preamble;
2031 docstring uncodable_glyphs;
2032 Encoding const * const enc = features.runparams().encoding;
2034 for (size_t n = 0; n < preamble.size(); ++n) {
2035 char_type c = preamble[n];
2036 if (!enc->encodable(c)) {
2037 docstring const glyph(1, c);
2038 LYXERR0("Uncodable character '"
2040 << "' in user preamble!");
2041 uncodable_glyphs += glyph;
2042 if (features.runparams().dryrun) {
2043 user_preamble << "<" << _("LyX Warning: ")
2044 << _("uncodable character") << " '";
2045 user_preamble.put(c);
2046 user_preamble << "'>";
2049 user_preamble.put(c);
2052 user_preamble << preamble;
2054 // On BUFFER_VIEW|UPDATE, warn user if we found uncodable glyphs
2055 if (!features.runparams().dryrun && !uncodable_glyphs.empty()) {
2056 frontend::Alert::warning(
2057 _("Uncodable character in user preamble"),
2059 _("The user preamble of your document contains glyphs "
2060 "that are unknown in the current document encoding "
2061 "(namely %1$s).\nThese glyphs are omitted "
2062 " from the output, which may result in "
2063 "incomplete output."
2064 "\n\nPlease select an appropriate "
2065 "document encoding\n"
2066 "(such as utf8) or change the "
2067 "preamble code accordingly."),
2070 atlyxpreamble << user_preamble.str() << '\n';
2073 // footmisc must be loaded after setspace
2074 // Load it here to avoid clashes with footmisc loaded in the user
2075 // preamble. For that reason we also pass the options via
2076 // \PassOptionsToPackage in getPreamble() and not here.
2077 if (features.mustProvide("footmisc"))
2078 atlyxpreamble << "\\usepackage{footmisc}\n";
2080 // subfig loads internally the LaTeX package "caption". As
2081 // caption is a very popular package, users will load it in
2082 // the preamble. Therefore we must load subfig behind the
2083 // user-defined preamble and check if the caption package was
2084 // loaded or not. For the case that caption is loaded before
2085 // subfig, there is the subfig option "caption=false". This
2086 // option also works when a koma-script class is used and
2087 // koma's own caption commands are used instead of caption. We
2088 // use \PassOptionsToPackage here because the user could have
2089 // already loaded subfig in the preamble.
2090 if (features.mustProvide("subfig"))
2091 atlyxpreamble << "\\@ifundefined{showcaptionsetup}{}{%\n"
2092 " \\PassOptionsToPackage{caption=false}{subfig}}\n"
2093 "\\usepackage{subfig}\n";
2095 // Itemize bullet settings need to be last in case the user
2096 // defines their own bullets that use a package included
2097 // in the user-defined preamble -- ARRae
2098 // Actually it has to be done much later than that
2099 // since some packages like frenchb make modifications
2100 // at \begin{document} time -- JMarc
2101 docstring bullets_def;
2102 for (int i = 0; i < 4; ++i) {
2103 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
2104 if (bullets_def.empty())
2105 bullets_def += "\\AtBeginDocument{\n";
2106 bullets_def += " \\def\\labelitemi";
2108 // `i' is one less than the item to modify
2115 bullets_def += "ii";
2121 bullets_def += '{' +
2122 user_defined_bullet(i).getText()
2127 if (!bullets_def.empty())
2128 atlyxpreamble << bullets_def << "}\n\n";
2130 if (!atlyxpreamble.empty())
2131 os << "\n\\makeatletter\n"
2132 << atlyxpreamble.release()
2133 << "\\makeatother\n\n";
2135 // We try to load babel late, in case it interferes with other packages.
2136 // Jurabib, hyperref, varioref, bicaption and listings (bug 8995) have to be
2137 // called after babel, though.
2138 if (use_babel && !features.isRequired("jurabib")
2139 && !features.isRequired("hyperref")
2140 && !features.isRequired("varioref")
2141 && !features.isRequired("vietnamese")
2142 && !features.isRequired("japanese")) {
2143 os << features.getBabelPresettings();
2145 os << from_utf8(babelCall(language_options.str(),
2146 features.needBabelLangOptions())) + '\n';
2147 os << features.getBabelPostsettings();
2149 if (features.isRequired("bicaption"))
2150 os << "\\usepackage{bicaption}\n";
2151 if (!listings_params.empty() || features.mustProvide("listings"))
2152 os << "\\usepackage{listings}\n";
2153 if (!listings_params.empty()) {
2155 // do not test validity because listings_params is
2156 // supposed to be valid
2158 InsetListingsParams(listings_params).separatedParams(true);
2159 os << from_utf8(par);
2163 // xunicode needs to be loaded at least after amsmath, amssymb,
2164 // esint and the other packages that provide special glyphs
2165 // The package only supports XeTeX currently.
2166 if (features.runparams().flavor == OutputParams::XETEX
2168 os << "\\usepackage{xunicode}\n";
2170 // Polyglossia must be loaded last
2171 if (use_polyglossia) {
2173 os << "\\usepackage{polyglossia}\n";
2174 // set the main language
2175 os << "\\setdefaultlanguage";
2176 if (!language->polyglossiaOpts().empty())
2177 os << "[" << from_ascii(language->polyglossiaOpts()) << "]";
2178 os << "{" << from_ascii(language->polyglossia()) << "}\n";
2179 // now setup the other languages
2180 std::map<std::string, std::string> const polylangs =
2181 features.getPolyglossiaLanguages();
2182 for (std::map<std::string, std::string>::const_iterator mit = polylangs.begin();
2183 mit != polylangs.end() ; ++mit) {
2184 os << "\\setotherlanguage";
2185 if (!mit->second.empty())
2186 os << "[" << from_ascii(mit->second) << "]";
2187 os << "{" << from_ascii(mit->first) << "}\n";
2191 // Load custom language package here
2192 if (features.langPackage() == LaTeXFeatures::LANG_PACK_CUSTOM) {
2193 if (lang_package == "default")
2194 os << from_utf8(lyxrc.language_custom_package);
2196 os << from_utf8(lang_package);
2200 docstring const i18npreamble =
2201 features.getTClassI18nPreamble(use_babel, use_polyglossia);
2202 if (!i18npreamble.empty())
2203 os << i18npreamble + '\n';
2209 void BufferParams::useClassDefaults()
2211 DocumentClass const & tclass = documentClass();
2213 sides = tclass.sides();
2214 columns = tclass.columns();
2215 pagestyle = tclass.pagestyle();
2216 use_default_options = true;
2217 // Only if class has a ToC hierarchy
2218 if (tclass.hasTocLevels()) {
2219 secnumdepth = tclass.secnumdepth();
2220 tocdepth = tclass.tocdepth();
2225 bool BufferParams::hasClassDefaults() const
2227 DocumentClass const & tclass = documentClass();
2229 return sides == tclass.sides()
2230 && columns == tclass.columns()
2231 && pagestyle == tclass.pagestyle()
2232 && use_default_options
2233 && secnumdepth == tclass.secnumdepth()
2234 && tocdepth == tclass.tocdepth();
2238 DocumentClass const & BufferParams::documentClass() const
2244 DocumentClassConstPtr BufferParams::documentClassPtr() const
2250 void BufferParams::setDocumentClass(DocumentClassConstPtr tc)
2252 // evil, but this function is evil
2253 doc_class_ = const_pointer_cast<DocumentClass>(tc);
2257 bool BufferParams::setBaseClass(string const & classname)
2259 LYXERR(Debug::TCLASS, "setBaseClass: " << classname);
2260 LayoutFileList & bcl = LayoutFileList::get();
2261 if (!bcl.haveClass(classname)) {
2263 bformat(_("The layout file:\n"
2265 "could not be found. A default textclass with default\n"
2266 "layouts will be used. LyX will not be able to produce\n"
2268 from_utf8(classname));
2269 frontend::Alert::error(_("Document class not found"), s);
2270 bcl.addEmptyClass(classname);
2273 bool const success = bcl[classname].load();
2276 bformat(_("Due to some error in it, the layout file:\n"
2278 "could not be loaded. A default textclass with default\n"
2279 "layouts will be used. LyX will not be able to produce\n"
2281 from_utf8(classname));
2282 frontend::Alert::error(_("Could not load class"), s);
2283 bcl.addEmptyClass(classname);
2286 pimpl_->baseClass_ = classname;
2287 layout_modules_.adaptToBaseClass(baseClass(), removed_modules_);
2292 LayoutFile const * BufferParams::baseClass() const
2294 if (LayoutFileList::get().haveClass(pimpl_->baseClass_))
2295 return &(LayoutFileList::get()[pimpl_->baseClass_]);
2301 LayoutFileIndex const & BufferParams::baseClassID() const
2303 return pimpl_->baseClass_;
2307 void BufferParams::makeDocumentClass(bool const clone)
2312 LayoutModuleList mods;
2313 LayoutModuleList::iterator it = layout_modules_.begin();
2314 LayoutModuleList::iterator en = layout_modules_.end();
2315 for (; it != en; ++it)
2316 mods.push_back(*it);
2318 it = cite_engine_.begin();
2319 en = cite_engine_.end();
2320 for (; it != en; ++it)
2321 mods.push_back(*it);
2323 doc_class_ = getDocumentClass(*baseClass(), mods, clone);
2325 TextClass::ReturnValues success = TextClass::OK;
2326 if (!forced_local_layout_.empty())
2327 success = doc_class_->read(to_utf8(forced_local_layout_),
2329 if (!local_layout_.empty() &&
2330 (success == TextClass::OK || success == TextClass::OK_OLDFORMAT))
2331 success = doc_class_->read(to_utf8(local_layout_), TextClass::MODULE);
2332 if (success != TextClass::OK && success != TextClass::OK_OLDFORMAT) {
2333 docstring const msg = _("Error reading internal layout information");
2334 frontend::Alert::warning(_("Read Error"), msg);
2339 bool BufferParams::layoutModuleCanBeAdded(string const & modName) const
2341 return layout_modules_.moduleCanBeAdded(modName, baseClass());
2345 bool BufferParams::citationModuleCanBeAdded(string const & modName) const
2347 return cite_engine_.moduleCanBeAdded(modName, baseClass());
2351 docstring BufferParams::getLocalLayout(bool forced) const
2354 return from_utf8(doc_class_->forcedLayouts());
2356 return local_layout_;
2360 void BufferParams::setLocalLayout(docstring const & layout, bool forced)
2363 forced_local_layout_ = layout;
2365 local_layout_ = layout;
2369 bool BufferParams::addLayoutModule(string const & modName)
2371 LayoutModuleList::const_iterator it = layout_modules_.begin();
2372 LayoutModuleList::const_iterator end = layout_modules_.end();
2373 for (; it != end; ++it)
2376 layout_modules_.push_back(modName);
2381 string BufferParams::bufferFormat() const
2383 return documentClass().outputFormat();
2387 bool BufferParams::isExportable(string const & format) const
2389 vector<string> backs = backends();
2390 for (vector<string>::const_iterator it = backs.begin();
2391 it != backs.end(); ++it)
2392 if (theConverters().isReachable(*it, format))
2398 vector<Format const *> BufferParams::exportableFormats(bool only_viewable) const
2400 vector<string> const backs = backends();
2401 set<string> excludes;
2402 if (useNonTeXFonts) {
2403 excludes.insert("latex");
2404 excludes.insert("pdflatex");
2406 vector<Format const *> result =
2407 theConverters().getReachable(backs[0], only_viewable, true, excludes);
2408 for (vector<string>::const_iterator it = backs.begin() + 1;
2409 it != backs.end(); ++it) {
2410 vector<Format const *> r =
2411 theConverters().getReachable(*it, only_viewable, false, excludes);
2412 result.insert(result.end(), r.begin(), r.end());
2418 bool BufferParams::isExportableFormat(string const & format) const
2420 typedef vector<Format const *> Formats;
2422 formats = exportableFormats(true);
2423 Formats::const_iterator fit = formats.begin();
2424 Formats::const_iterator end = formats.end();
2425 for (; fit != end ; ++fit) {
2426 if ((*fit)->name() == format)
2433 vector<string> BufferParams::backends() const
2436 string const buffmt = bufferFormat();
2438 // FIXME: Don't hardcode format names here, but use a flag
2439 if (buffmt == "latex") {
2440 if (encoding().package() == Encoding::japanese)
2441 v.push_back("platex");
2443 if (!useNonTeXFonts) {
2444 v.push_back("pdflatex");
2445 v.push_back("latex");
2447 v.push_back("xetex");
2448 v.push_back("luatex");
2449 v.push_back("dviluatex");
2452 v.push_back(buffmt);
2454 v.push_back("xhtml");
2455 v.push_back("text");
2461 OutputParams::FLAVOR BufferParams::getOutputFlavor(string const & format) const
2463 string const dformat = (format.empty() || format == "default") ?
2464 getDefaultOutputFormat() : format;
2465 DefaultFlavorCache::const_iterator it =
2466 default_flavors_.find(dformat);
2468 if (it != default_flavors_.end())
2471 OutputParams::FLAVOR result = OutputParams::LATEX;
2473 // FIXME It'd be better not to hardcode this, but to do
2474 // something with formats.
2475 if (dformat == "xhtml")
2476 result = OutputParams::HTML;
2477 else if (dformat == "text")
2478 result = OutputParams::TEXT;
2479 else if (dformat == "lyx")
2480 result = OutputParams::LYX;
2481 else if (dformat == "pdflatex")
2482 result = OutputParams::PDFLATEX;
2483 else if (dformat == "xetex")
2484 result = OutputParams::XETEX;
2485 else if (dformat == "luatex")
2486 result = OutputParams::LUATEX;
2487 else if (dformat == "dviluatex")
2488 result = OutputParams::DVILUATEX;
2490 // Try to determine flavor of default output format
2491 vector<string> backs = backends();
2492 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
2493 // Get shortest path to format
2494 Graph::EdgePath path;
2495 for (vector<string>::const_iterator it = backs.begin();
2496 it != backs.end(); ++it) {
2497 Graph::EdgePath p = theConverters().getPath(*it, dformat);
2498 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2503 result = theConverters().getFlavor(path);
2506 // cache this flavor
2507 default_flavors_[dformat] = result;
2512 string BufferParams::getDefaultOutputFormat() const
2514 if (!default_output_format.empty()
2515 && default_output_format != "default")
2516 return default_output_format;
2518 || encoding().package() == Encoding::japanese) {
2519 vector<Format const *> const formats = exportableFormats(true);
2520 if (formats.empty())
2522 // return the first we find
2523 return formats.front()->name();
2526 return lyxrc.default_otf_view_format;
2527 return lyxrc.default_view_format;
2530 Font const BufferParams::getFont() const
2532 FontInfo f = documentClass().defaultfont();
2533 if (fonts_default_family == "rmdefault")
2534 f.setFamily(ROMAN_FAMILY);
2535 else if (fonts_default_family == "sfdefault")
2536 f.setFamily(SANS_FAMILY);
2537 else if (fonts_default_family == "ttdefault")
2538 f.setFamily(TYPEWRITER_FAMILY);
2539 return Font(f, language);
2543 InsetQuotes::QuoteLanguage BufferParams::getQuoteStyle(string const & qs) const
2545 return quoteslangtranslator().find(qs);
2549 bool BufferParams::isLatex() const
2551 return documentClass().outputType() == LATEX;
2555 bool BufferParams::isLiterate() const
2557 return documentClass().outputType() == LITERATE;
2561 bool BufferParams::isDocBook() const
2563 return documentClass().outputType() == DOCBOOK;
2567 void BufferParams::readPreamble(Lexer & lex)
2569 if (lex.getString() != "\\begin_preamble")
2570 lyxerr << "Error (BufferParams::readPreamble):"
2571 "consistency check failed." << endl;
2573 preamble = lex.getLongString(from_ascii("\\end_preamble"));
2577 void BufferParams::readLocalLayout(Lexer & lex, bool forced)
2579 string const expected = forced ? "\\begin_forced_local_layout" :
2580 "\\begin_local_layout";
2581 if (lex.getString() != expected)
2582 lyxerr << "Error (BufferParams::readLocalLayout):"
2583 "consistency check failed." << endl;
2586 forced_local_layout_ =
2587 lex.getLongString(from_ascii("\\end_forced_local_layout"));
2589 local_layout_ = lex.getLongString(from_ascii("\\end_local_layout"));
2593 bool BufferParams::setLanguage(string const & lang)
2595 Language const *new_language = languages.getLanguage(lang);
2596 if (!new_language) {
2597 // Language lang was not found
2600 language = new_language;
2605 void BufferParams::readLanguage(Lexer & lex)
2607 if (!lex.next()) return;
2609 string const tmptok = lex.getString();
2611 // check if tmptok is part of tex_babel in tex-defs.h
2612 if (!setLanguage(tmptok)) {
2613 // Language tmptok was not found
2614 language = default_language;
2615 lyxerr << "Warning: Setting language `"
2616 << tmptok << "' to `" << language->lang()
2622 void BufferParams::readGraphicsDriver(Lexer & lex)
2627 string const tmptok = lex.getString();
2628 // check if tmptok is part of tex_graphics in tex_defs.h
2631 string const test = tex_graphics[n++];
2633 if (test == tmptok) {
2634 graphics_driver = tmptok;
2639 "Warning: graphics driver `$$Token' not recognized!\n"
2640 " Setting graphics driver to `default'.\n");
2641 graphics_driver = "default";
2648 void BufferParams::readBullets(Lexer & lex)
2653 int const index = lex.getInteger();
2655 int temp_int = lex.getInteger();
2656 user_defined_bullet(index).setFont(temp_int);
2657 temp_bullet(index).setFont(temp_int);
2659 user_defined_bullet(index).setCharacter(temp_int);
2660 temp_bullet(index).setCharacter(temp_int);
2662 user_defined_bullet(index).setSize(temp_int);
2663 temp_bullet(index).setSize(temp_int);
2667 void BufferParams::readBulletsLaTeX(Lexer & lex)
2669 // The bullet class should be able to read this.
2672 int const index = lex.getInteger();
2674 docstring const temp_str = lex.getDocString();
2676 user_defined_bullet(index).setText(temp_str);
2677 temp_bullet(index).setText(temp_str);
2681 void BufferParams::readModules(Lexer & lex)
2683 if (!lex.eatLine()) {
2684 lyxerr << "Error (BufferParams::readModules):"
2685 "Unexpected end of input." << endl;
2689 string mod = lex.getString();
2690 if (mod == "\\end_modules")
2692 addLayoutModule(mod);
2698 void BufferParams::readRemovedModules(Lexer & lex)
2700 if (!lex.eatLine()) {
2701 lyxerr << "Error (BufferParams::readRemovedModules):"
2702 "Unexpected end of input." << endl;
2706 string mod = lex.getString();
2707 if (mod == "\\end_removed_modules")
2709 removed_modules_.push_back(mod);
2712 // now we want to remove any removed modules that were previously
2713 // added. normally, that will be because default modules were added in
2714 // setBaseClass(), which gets called when \textclass is read at the
2715 // start of the read.
2716 list<string>::const_iterator rit = removed_modules_.begin();
2717 list<string>::const_iterator const ren = removed_modules_.end();
2718 for (; rit != ren; ++rit) {
2719 LayoutModuleList::iterator const mit = layout_modules_.begin();
2720 LayoutModuleList::iterator const men = layout_modules_.end();
2721 LayoutModuleList::iterator found = find(mit, men, *rit);
2724 layout_modules_.erase(found);
2729 void BufferParams::readIncludeonly(Lexer & lex)
2731 if (!lex.eatLine()) {
2732 lyxerr << "Error (BufferParams::readIncludeonly):"
2733 "Unexpected end of input." << endl;
2737 string child = lex.getString();
2738 if (child == "\\end_includeonly")
2740 included_children_.push_back(child);
2746 string BufferParams::paperSizeName(PapersizePurpose purpose) const
2748 switch (papersize) {
2750 // could be anything, so don't guess
2752 case PAPER_CUSTOM: {
2753 if (purpose == XDVI && !paperwidth.empty() &&
2754 !paperheight.empty()) {
2755 // heightxwidth<unit>
2756 string first = paperwidth;
2757 string second = paperheight;
2758 if (orientation == ORIENTATION_LANDSCAPE)
2761 return first.erase(first.length() - 2)
2767 // dvips and dvipdfm do not know this
2768 if (purpose == DVIPS || purpose == DVIPDFM)
2772 if (purpose == DVIPS || purpose == DVIPDFM)
2776 if (purpose == DVIPS || purpose == DVIPDFM)
2786 if (purpose == DVIPS || purpose == DVIPDFM)
2790 if (purpose == DVIPS || purpose == DVIPDFM)
2794 if (purpose == DVIPS || purpose == DVIPDFM)
2798 if (purpose == DVIPS || purpose == DVIPDFM)
2802 if (purpose == DVIPS || purpose == DVIPDFM)
2806 // dvipdfm does not know this
2807 if (purpose == DVIPDFM)
2811 if (purpose == DVIPDFM)
2815 if (purpose == DVIPS || purpose == DVIPDFM)
2819 if (purpose == DVIPS || purpose == DVIPDFM)
2823 if (purpose == DVIPS || purpose == DVIPDFM)
2827 if (purpose == DVIPS || purpose == DVIPDFM)
2831 if (purpose == DVIPS || purpose == DVIPDFM)
2835 if (purpose == DVIPS || purpose == DVIPDFM)
2839 if (purpose == DVIPS || purpose == DVIPDFM)
2843 if (purpose == DVIPS || purpose == DVIPDFM)
2847 if (purpose == DVIPS || purpose == DVIPDFM)
2851 if (purpose == DVIPS || purpose == DVIPDFM)
2855 if (purpose == DVIPS || purpose == DVIPDFM)
2859 if (purpose == DVIPS || purpose == DVIPDFM)
2863 if (purpose == DVIPS || purpose == DVIPDFM)
2867 if (purpose == DVIPS || purpose == DVIPDFM)
2871 if (purpose == DVIPS || purpose == DVIPDFM)
2874 case PAPER_USEXECUTIVE:
2875 // dvipdfm does not know this
2876 if (purpose == DVIPDFM)
2881 case PAPER_USLETTER:
2883 if (purpose == XDVI)
2890 string const BufferParams::dvips_options() const
2894 // If the class loads the geometry package, we do not know which
2895 // paper size is used, since we do not set it (bug 7013).
2896 // Therefore we must not specify any argument here.
2897 // dvips gets the correct paper size via DVI specials in this case
2898 // (if the class uses the geometry package correctly).
2899 if (documentClass().provides("geometry"))
2903 && papersize == PAPER_CUSTOM
2904 && !lyxrc.print_paper_dimension_flag.empty()
2905 && !paperwidth.empty()
2906 && !paperheight.empty()) {
2907 // using a custom papersize
2908 result = lyxrc.print_paper_dimension_flag;
2909 result += ' ' + paperwidth;
2910 result += ',' + paperheight;
2912 string const paper_option = paperSizeName(DVIPS);
2913 if (!paper_option.empty() && (paper_option != "letter" ||
2914 orientation != ORIENTATION_LANDSCAPE)) {
2915 // dvips won't accept -t letter -t landscape.
2916 // In all other cases, include the paper size
2918 result = lyxrc.print_paper_flag;
2919 result += ' ' + paper_option;
2922 if (orientation == ORIENTATION_LANDSCAPE &&
2923 papersize != PAPER_CUSTOM)
2924 result += ' ' + lyxrc.print_landscape_flag;
2929 string const BufferParams::font_encoding() const
2931 return font_encodings().empty() ? "default" : font_encodings().back();
2935 vector<string> const BufferParams::font_encodings() const
2937 string doc_fontenc = (fontenc == "global") ? lyxrc.fontenc : fontenc;
2939 vector<string> fontencs;
2941 // "default" means "no explicit font encoding"
2942 if (doc_fontenc != "default") {
2943 fontencs = getVectorFromString(doc_fontenc);
2944 if (!language->fontenc().empty()
2945 && ascii_lowercase(language->fontenc()) != "none") {
2946 vector<string> fencs = getVectorFromString(language->fontenc());
2947 vector<string>::const_iterator fit = fencs.begin();
2948 for (; fit != fencs.end(); ++fit) {
2949 if (find(fontencs.begin(), fontencs.end(), *fit) == fontencs.end())
2950 fontencs.push_back(*fit);
2959 string BufferParams::babelCall(string const & lang_opts, bool const langoptions) const
2961 // suppress the babel call if there is no BabelName defined
2962 // for the document language in the lib/languages file and if no
2963 // other languages are used (lang_opts is then empty)
2964 if (lang_opts.empty())
2966 // either a specific language (AsBabelOptions setting in
2967 // lib/languages) or the prefs require the languages to
2968 // be submitted to babel itself (not the class).
2970 return "\\usepackage[" + lang_opts + "]{babel}";
2971 return "\\usepackage{babel}";
2975 docstring BufferParams::getGraphicsDriver(string const & package) const
2979 if (package == "geometry") {
2980 if (graphics_driver == "dvips"
2981 || graphics_driver == "dvipdfm"
2982 || graphics_driver == "pdftex"
2983 || graphics_driver == "vtex")
2984 result = from_ascii(graphics_driver);
2985 else if (graphics_driver == "dvipdfmx")
2986 result = from_ascii("dvipdfm");
2993 void BufferParams::writeEncodingPreamble(otexstream & os,
2994 LaTeXFeatures & features) const
2996 // XeTeX/LuaTeX: (see also #9740)
2997 // With Unicode fonts we use utf8-plain without encoding package.
2998 // With TeX fonts, we cannot use utf8-plain, but "inputenc" fails.
2999 // XeTeX must use ASCII encoding (see Buffer.cpp),
3000 // for LuaTeX, we load "luainputenc" (see below).
3001 if (useNonTeXFonts || features.runparams().flavor == OutputParams::XETEX)
3004 if (inputenc == "auto") {
3005 string const doc_encoding =
3006 language->encoding()->latexName();
3007 Encoding::Package const package =
3008 language->encoding()->package();
3010 // Create list of inputenc options:
3011 set<string> encodings;
3012 // luainputenc fails with more than one encoding
3013 if (!features.runparams().isFullUnicode()) // if we reach this point, this means LuaTeX with TeX fonts
3014 // list all input encodings used in the document
3015 encodings = features.getEncodingSet(doc_encoding);
3017 // If the "japanese" package (i.e. pLaTeX) is used,
3018 // inputenc must be omitted.
3019 // see http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg129680.html
3020 if ((!encodings.empty() || package == Encoding::inputenc)
3021 && !features.isRequired("japanese")
3022 && !features.isProvided("inputenc")) {
3023 os << "\\usepackage[";
3024 set<string>::const_iterator it = encodings.begin();
3025 set<string>::const_iterator const end = encodings.end();
3027 os << from_ascii(*it);
3030 for (; it != end; ++it)
3031 os << ',' << from_ascii(*it);
3032 if (package == Encoding::inputenc) {
3033 if (!encodings.empty())
3035 os << from_ascii(doc_encoding);
3037 if (features.runparams().flavor == OutputParams::LUATEX
3038 || features.runparams().flavor == OutputParams::DVILUATEX)
3039 os << "]{luainputenc}\n";
3041 os << "]{inputenc}\n";
3043 if (package == Encoding::CJK || features.mustProvide("CJK")) {
3044 if (language->encoding()->name() == "utf8-cjk"
3045 && LaTeXFeatures::isAvailable("CJKutf8"))
3046 os << "\\usepackage{CJKutf8}\n";
3048 os << "\\usepackage{CJK}\n";
3050 } else if (inputenc != "default") {
3051 switch (encoding().package()) {
3052 case Encoding::none:
3053 case Encoding::japanese:
3055 case Encoding::inputenc:
3056 // do not load inputenc if japanese is used
3057 // or if the class provides inputenc
3058 if (features.isRequired("japanese")
3059 || features.isProvided("inputenc"))
3061 os << "\\usepackage[" << from_ascii(encoding().latexName());
3062 if (features.runparams().flavor == OutputParams::LUATEX
3063 || features.runparams().flavor == OutputParams::DVILUATEX)
3064 os << "]{luainputenc}\n";
3066 os << "]{inputenc}\n";
3069 if (encoding().name() == "utf8-cjk"
3070 && LaTeXFeatures::isAvailable("CJKutf8"))
3071 os << "\\usepackage{CJKutf8}\n";
3073 os << "\\usepackage{CJK}\n";
3076 // Load the CJK package if needed by a secondary language.
3077 // If the main encoding is some variant of UTF8, use CJKutf8.
3078 if (encoding().package() != Encoding::CJK && features.mustProvide("CJK")) {
3079 if (encoding().iconvName() == "UTF-8"
3080 && LaTeXFeatures::isAvailable("CJKutf8"))
3081 os << "\\usepackage{CJKutf8}\n";
3083 os << "\\usepackage{CJK}\n";
3089 string const BufferParams::parseFontName(string const & name) const
3091 string mangled = name;
3092 size_t const idx = mangled.find('[');
3093 if (idx == string::npos || idx == 0)
3096 return mangled.substr(0, idx - 1);
3100 string const BufferParams::loadFonts(LaTeXFeatures & features) const
3102 if (fontsRoman() == "default" && fontsSans() == "default"
3103 && fontsTypewriter() == "default"
3104 && (fontsMath() == "default" || fontsMath() == "auto"))
3110 /* Fontspec (XeTeX, LuaTeX): we provide GUI support for oldstyle
3111 * numbers (Numbers=OldStyle) and sf/tt scaling. The Ligatures=TeX/
3112 * Mapping=tex-text option assures TeX ligatures (such as "--")
3113 * are resolved. Note that tt does not use these ligatures.
3115 * -- add more GUI options?
3116 * -- add more fonts (fonts for other scripts)
3117 * -- if there's a way to find out if a font really supports
3118 * OldStyle, enable/disable the widget accordingly.
3120 if (useNonTeXFonts && features.isAvailable("fontspec")) {
3121 // "Mapping=tex-text" and "Ligatures=TeX" are equivalent.
3122 // However, until v.2 (2010/07/11) fontspec only knew
3123 // Mapping=tex-text (for XeTeX only); then "Ligatures=TeX"
3124 // was introduced for both XeTeX and LuaTeX (LuaTeX
3125 // didn't understand "Mapping=tex-text", while XeTeX
3126 // understood both. With most recent versions, both
3127 // variants are understood by both engines. However,
3128 // we want to provide support for at least TeXLive 2009
3129 // (for XeTeX; LuaTeX is only supported as of v.2)
3130 string const texmapping =
3131 (features.runparams().flavor == OutputParams::XETEX) ?
3132 "Mapping=tex-text" : "Ligatures=TeX";
3133 if (fontsRoman() != "default") {
3134 os << "\\setmainfont[" << texmapping;
3135 if (fonts_old_figures)
3136 os << ",Numbers=OldStyle";
3137 os << "]{" << parseFontName(fontsRoman()) << "}\n";
3139 if (fontsSans() != "default") {
3140 string const sans = parseFontName(fontsSans());
3141 if (fontsSansScale() != 100)
3142 os << "\\setsansfont[Scale="
3143 << float(fontsSansScale()) / 100
3144 << "," << texmapping << "]{"
3147 os << "\\setsansfont[" << texmapping << "]{"
3150 if (fontsTypewriter() != "default") {
3151 string const mono = parseFontName(fontsTypewriter());
3152 if (fontsTypewriterScale() != 100)
3153 os << "\\setmonofont[Scale="
3154 << float(fontsTypewriterScale()) / 100
3158 os << "\\setmonofont{"
3165 bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
3166 bool const dryrun = features.runparams().dryrun;
3167 bool const complete = (fontsSans() == "default" && fontsTypewriter() == "default");
3168 bool const nomath = (fontsMath() == "default");
3171 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsRoman())).getLaTeXCode(
3172 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3176 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsSans())).getLaTeXCode(
3177 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3178 nomath, fontsSansScale());
3180 // MONOSPACED/TYPEWRITER
3181 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsTypewriter())).getLaTeXCode(
3182 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3183 nomath, fontsTypewriterScale());
3186 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getLaTeXCode(
3187 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3194 Encoding const & BufferParams::encoding() const
3196 // Main encoding for LaTeX output.
3198 // Exception: XeTeX with 8-bit TeX fonts requires ASCII (see #9740).
3199 // As the "flavor" is only known once export started, this
3200 // cannot be handled here. Instead, runparams.encoding is set
3201 // to ASCII in Buffer::makeLaTeXFile (for export)
3202 // and Buffer::writeLaTeXSource (for preview).
3204 return *(encodings.fromLyXName("utf8-plain"));
3205 if (inputenc == "auto" || inputenc == "default")
3206 return *language->encoding();
3207 Encoding const * const enc = encodings.fromLyXName(inputenc);
3210 LYXERR0("Unknown inputenc value `" << inputenc
3211 << "'. Using `auto' instead.");
3212 return *language->encoding();
3216 bool BufferParams::addCiteEngine(string const & engine)
3218 LayoutModuleList::const_iterator it = cite_engine_.begin();
3219 LayoutModuleList::const_iterator en = cite_engine_.end();
3220 for (; it != en; ++it)
3223 cite_engine_.push_back(engine);
3228 bool BufferParams::addCiteEngine(vector<string> const & engine)
3230 vector<string>::const_iterator it = engine.begin();
3231 vector<string>::const_iterator en = engine.end();
3233 for (; it != en; ++it)
3234 if (!addCiteEngine(*it))
3240 string const & BufferParams::defaultBiblioStyle() const
3242 return documentClass().defaultBiblioStyle();
3246 bool const & BufferParams::fullAuthorList() const
3248 return documentClass().fullAuthorList();
3252 void BufferParams::setCiteEngine(string const & engine)
3255 addCiteEngine(engine);
3259 void BufferParams::setCiteEngine(vector<string> const & engine)
3262 addCiteEngine(engine);
3266 vector<string> BufferParams::citeCommands() const
3268 static CitationStyle const default_style;
3269 vector<string> commands =
3270 documentClass().citeCommands(citeEngineType());
3271 if (commands.empty())
3272 commands.push_back(default_style.cmd);
3277 vector<CitationStyle> BufferParams::citeStyles() const
3279 static CitationStyle const default_style;
3280 vector<CitationStyle> styles =
3281 documentClass().citeStyles(citeEngineType());
3283 styles.push_back(default_style);