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_;
358 /// Caching for exportableFormats, which seems to be slow.
359 std::vector<Format const *> exportableFormatList;
360 std::vector<Format const *> viewableFormatList;
361 bool isViewCacheValid;
362 bool isExportCacheValid;
366 BufferParams::Impl::Impl()
367 : defskip(VSpace::MEDSKIP), baseClass_(string("")),
368 isViewCacheValid(false), isExportCacheValid(false)
370 // set initial author
372 authorlist.record(Author(from_utf8(lyxrc.user_name), from_utf8(lyxrc.user_email)));
377 BufferParams::MemoryTraits::clone(BufferParams::Impl const * ptr)
380 return new BufferParams::Impl(*ptr);
384 void BufferParams::MemoryTraits::destroy(BufferParams::Impl * ptr)
390 BufferParams::BufferParams()
393 setBaseClass(defaultBaseclass());
394 cite_engine_.push_back("basic");
395 cite_engine_type_ = ENGINE_TYPE_DEFAULT;
397 paragraph_separation = ParagraphIndentSeparation;
398 quotes_language = InsetQuotes::EnglishQuotes;
399 fontsize = "default";
402 papersize = PAPER_DEFAULT;
403 orientation = ORIENTATION_PORTRAIT;
404 use_geometry = false;
405 biblio_style = "plain";
406 use_bibtopic = false;
408 save_transient_properties = true;
409 track_changes = false;
410 output_changes = false;
411 use_default_options = true;
412 maintain_unincluded_children = false;
415 language = default_language;
417 fonts_roman[0] = "default";
418 fonts_roman[1] = "default";
419 fonts_sans[0] = "default";
420 fonts_sans[1] = "default";
421 fonts_typewriter[0] = "default";
422 fonts_typewriter[1] = "default";
423 fonts_math[0] = "auto";
424 fonts_math[1] = "auto";
425 fonts_default_family = "default";
426 useNonTeXFonts = false;
427 use_microtype = false;
428 fonts_expert_sc = false;
429 fonts_old_figures = false;
430 fonts_sans_scale[0] = 100;
431 fonts_sans_scale[1] = 100;
432 fonts_typewriter_scale[0] = 100;
433 fonts_typewriter_scale[1] = 100;
435 lang_package = "default";
436 graphics_driver = "default";
437 default_output_format = "default";
438 bibtex_command = "default";
439 index_command = "default";
442 listings_params = string();
443 pagestyle = "default";
444 suppress_date = false;
445 justification = true;
446 // no color is the default (white)
447 backgroundcolor = lyx::rgbFromHexName("#ffffff");
448 isbackgroundcolor = false;
449 // no color is the default (black)
450 fontcolor = lyx::rgbFromHexName("#000000");
452 // light gray is the default font color for greyed-out notes
453 notefontcolor = lyx::rgbFromHexName("#cccccc");
454 boxbgcolor = lyx::rgbFromHexName("#ff0000");
455 compressed = lyxrc.save_compressed;
456 for (int iter = 0; iter < 4; ++iter) {
457 user_defined_bullet(iter) = ITEMIZE_DEFAULTS[iter];
458 temp_bullet(iter) = ITEMIZE_DEFAULTS[iter];
461 indiceslist().addDefault(B_("Index"));
462 html_be_strict = false;
463 html_math_output = MathML;
464 html_math_img_scale = 1.0;
465 html_css_as_file = false;
466 display_pixel_ratio = 1.0;
471 // map current author
472 author_map_[pimpl_->authorlist.get(0).bufferId()] = 0;
476 docstring BufferParams::B_(string const & l10n) const
478 LASSERT(language, return from_utf8(l10n));
479 return getMessages(language->code()).get(l10n);
483 BufferParams::Package BufferParams::use_package(std::string const & p) const
485 PackageMap::const_iterator it = use_packages.find(p);
486 if (it == use_packages.end())
492 void BufferParams::use_package(std::string const & p, BufferParams::Package u)
498 map<string, string> const & BufferParams::auto_packages()
500 static map<string, string> packages;
501 if (packages.empty()) {
502 // We could have a race condition here that two threads
503 // discover an empty map at the same time and want to fill
504 // it, but that is no problem, since the same contents is
505 // filled in twice then. Having the locker inside the
506 // packages.empty() condition has the advantage that we
507 // don't need the mutex overhead for simple reading.
509 Mutex::Locker locker(&mutex);
510 // adding a package here implies a file format change!
511 packages["amsmath"] =
512 N_("The LaTeX package amsmath is only used if AMS formula types or symbols from the AMS math toolbars are inserted into formulas");
513 packages["amssymb"] =
514 N_("The LaTeX package amssymb is only used if symbols from the AMS math toolbars are inserted into formulas");
516 N_("The LaTeX package cancel is only used if \\cancel commands are used in formulas");
518 N_("The LaTeX package esint is only used if special integral symbols are inserted into formulas");
519 packages["mathdots"] =
520 N_("The LaTeX package mathdots is only used if the command \\iddots is inserted into formulas");
521 packages["mathtools"] =
522 N_("The LaTeX package mathtools is only used if some mathematical relations are inserted into formulas");
524 N_("The LaTeX package mhchem is only used if either the command \\ce or \\cf is inserted into formulas");
525 packages["stackrel"] =
526 N_("The LaTeX package stackrel is only used if the command \\stackrel with subscript is inserted into formulas");
527 packages["stmaryrd"] =
528 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");
529 packages["undertilde"] =
530 N_("The LaTeX package undertilde is only used if you use the math frame decoration 'utilde'");
536 AuthorList & BufferParams::authors()
538 return pimpl_->authorlist;
542 AuthorList const & BufferParams::authors() const
544 return pimpl_->authorlist;
548 void BufferParams::addAuthor(Author a)
550 author_map_[a.bufferId()] = pimpl_->authorlist.record(a);
554 BranchList & BufferParams::branchlist()
556 return pimpl_->branchlist;
560 BranchList const & BufferParams::branchlist() const
562 return pimpl_->branchlist;
566 IndicesList & BufferParams::indiceslist()
568 return pimpl_->indiceslist;
572 IndicesList const & BufferParams::indiceslist() const
574 return pimpl_->indiceslist;
578 Bullet & BufferParams::temp_bullet(lyx::size_type const index)
580 LASSERT(index < 4, return pimpl_->temp_bullets[0]);
581 return pimpl_->temp_bullets[index];
585 Bullet const & BufferParams::temp_bullet(lyx::size_type const index) const
587 LASSERT(index < 4, return pimpl_->temp_bullets[0]);
588 return pimpl_->temp_bullets[index];
592 Bullet & BufferParams::user_defined_bullet(lyx::size_type const index)
594 LASSERT(index < 4, return pimpl_->temp_bullets[0]);
595 return pimpl_->user_defined_bullets[index];
599 Bullet const & BufferParams::user_defined_bullet(lyx::size_type const index) const
601 LASSERT(index < 4, return pimpl_->temp_bullets[0]);
602 return pimpl_->user_defined_bullets[index];
606 Spacing & BufferParams::spacing()
608 return pimpl_->spacing;
612 Spacing const & BufferParams::spacing() const
614 return pimpl_->spacing;
618 PDFOptions & BufferParams::pdfoptions()
620 return pimpl_->pdfoptions;
624 PDFOptions const & BufferParams::pdfoptions() const
626 return pimpl_->pdfoptions;
630 HSpace const & BufferParams::getIndentation() const
632 return pimpl_->indentation;
636 void BufferParams::setIndentation(HSpace const & indent)
638 pimpl_->indentation = indent;
642 VSpace const & BufferParams::getDefSkip() const
644 return pimpl_->defskip;
648 void BufferParams::setDefSkip(VSpace const & vs)
650 // DEFSKIP will cause an infinite loop
651 LASSERT(vs.kind() != VSpace::DEFSKIP, return);
652 pimpl_->defskip = vs;
656 string BufferParams::readToken(Lexer & lex, string const & token,
657 FileName const & filepath)
661 if (token == "\\textclass") {
663 string const classname = lex.getString();
664 // if there exists a local layout file, ignore the system one
665 // NOTE: in this case, the textclass (.cls file) is assumed to
668 LayoutFileList & bcl = LayoutFileList::get();
669 if (!filepath.empty()) {
670 // If classname is an absolute path, the document is
671 // using a local layout file which could not be accessed
672 // by a relative path. In this case the path is correct
673 // even if the document was moved to a different
674 // location. However, we will have a problem if the
675 // document was generated on a different platform.
676 bool isabsolute = FileName::isAbsolute(classname);
677 string const classpath = onlyPath(classname);
678 string const path = isabsolute ? classpath
679 : FileName(addPath(filepath.absFileName(),
680 classpath)).realPath();
681 string const oldpath = isabsolute ? string()
682 : FileName(addPath(origin, classpath)).realPath();
683 tcp = bcl.addLocalLayout(onlyFileName(classname), path, oldpath);
685 // that returns non-empty if a "local" layout file is found.
687 result = to_utf8(makeRelPath(from_utf8(onlyPath(tcp)),
688 from_utf8(filepath.absFileName())));
691 setBaseClass(onlyFileName(tcp));
693 setBaseClass(onlyFileName(classname));
694 // We assume that a tex class exists for local or unknown
695 // layouts so this warning, will only be given for system layouts.
696 if (!baseClass()->isTeXClassAvailable()) {
697 docstring const desc =
698 translateIfPossible(from_utf8(baseClass()->description()));
699 docstring const prereqs =
700 from_utf8(baseClass()->prerequisites());
701 docstring const msg =
702 bformat(_("The selected document class\n"
704 "requires external files that are not available.\n"
705 "The document class can still be used, but the\n"
706 "document cannot be compiled until the following\n"
707 "prerequisites are installed:\n"
709 "See section 3.1.2.2 (Class Availability) of the\n"
710 "User's Guide for more information."), desc, prereqs);
711 frontend::Alert::warning(_("Document class not available"),
714 } else if (token == "\\save_transient_properties") {
715 lex >> save_transient_properties;
716 } else if (token == "\\origin") {
718 origin = lex.getString();
719 string const sysdirprefix = "/systemlyxdir/";
720 if (prefixIs(origin, sysdirprefix)) {
722 if (inSystemDir(filepath, docsys))
723 origin.replace(0, sysdirprefix.length() - 1, docsys);
725 origin.replace(0, sysdirprefix.length() - 1,
726 package().system_support().absFileName());
728 } else if (token == "\\begin_preamble") {
730 } else if (token == "\\begin_local_layout") {
731 readLocalLayout(lex, false);
732 } else if (token == "\\begin_forced_local_layout") {
733 readLocalLayout(lex, true);
734 } else if (token == "\\begin_modules") {
736 } else if (token == "\\begin_removed_modules") {
737 readRemovedModules(lex);
738 } else if (token == "\\begin_includeonly") {
739 readIncludeonly(lex);
740 } else if (token == "\\maintain_unincluded_children") {
741 lex >> maintain_unincluded_children;
742 } else if (token == "\\options") {
744 options = lex.getString();
745 } else if (token == "\\use_default_options") {
746 lex >> use_default_options;
747 } else if (token == "\\master") {
749 master = lex.getString();
750 if (!filepath.empty() && FileName::isAbsolute(origin)) {
751 bool const isabs = FileName::isAbsolute(master);
752 FileName const abspath(isabs ? master : origin + master);
753 bool const moved = filepath != FileName(origin);
754 if (moved && abspath.exists()) {
755 docstring const path = isabs
757 : from_utf8(abspath.realPath());
758 docstring const refpath =
759 from_utf8(filepath.absFileName());
760 master = to_utf8(makeRelPath(path, refpath));
763 } else if (token == "\\suppress_date") {
764 lex >> suppress_date;
765 } else if (token == "\\justification") {
766 lex >> justification;
767 } else if (token == "\\language") {
769 } else if (token == "\\language_package") {
771 lang_package = lex.getString();
772 } else if (token == "\\inputencoding") {
774 } else if (token == "\\graphics") {
775 readGraphicsDriver(lex);
776 } else if (token == "\\default_output_format") {
777 lex >> default_output_format;
778 } else if (token == "\\bibtex_command") {
780 bibtex_command = lex.getString();
781 } else if (token == "\\index_command") {
783 index_command = lex.getString();
784 } else if (token == "\\fontencoding") {
786 fontenc = lex.getString();
787 } else if (token == "\\font_roman") {
788 lex >> fonts_roman[0];
789 lex >> fonts_roman[1];
790 } else if (token == "\\font_sans") {
791 lex >> fonts_sans[0];
792 lex >> fonts_sans[1];
793 } else if (token == "\\font_typewriter") {
794 lex >> fonts_typewriter[0];
795 lex >> fonts_typewriter[1];
796 } else if (token == "\\font_math") {
797 lex >> fonts_math[0];
798 lex >> fonts_math[1];
799 } else if (token == "\\font_default_family") {
800 lex >> fonts_default_family;
801 } else if (token == "\\use_non_tex_fonts") {
802 lex >> useNonTeXFonts;
803 } else if (token == "\\font_sc") {
804 lex >> fonts_expert_sc;
805 } else if (token == "\\font_osf") {
806 lex >> fonts_old_figures;
807 } else if (token == "\\font_sf_scale") {
808 lex >> fonts_sans_scale[0];
809 lex >> fonts_sans_scale[1];
810 } else if (token == "\\font_tt_scale") {
811 lex >> fonts_typewriter_scale[0];
812 lex >> fonts_typewriter_scale[1];
813 } else if (token == "\\font_cjk") {
815 } else if (token == "\\use_microtype") {
816 lex >> use_microtype;
817 } else if (token == "\\paragraph_separation") {
820 paragraph_separation = parseptranslator().find(parsep);
821 } else if (token == "\\paragraph_indentation") {
823 string indentation = lex.getString();
824 pimpl_->indentation = HSpace(indentation);
825 } else if (token == "\\defskip") {
827 string const defskip = lex.getString();
828 pimpl_->defskip = VSpace(defskip);
829 if (pimpl_->defskip.kind() == VSpace::DEFSKIP)
831 pimpl_->defskip = VSpace(VSpace::MEDSKIP);
832 } else if (token == "\\quotes_language") {
835 quotes_language = quoteslangtranslator().find(quotes_lang);
836 } else if (token == "\\papersize") {
839 papersize = papersizetranslator().find(ppsize);
840 } else if (token == "\\use_geometry") {
842 } else if (token == "\\use_package") {
847 use_package(package, packagetranslator().find(use));
848 } else if (token == "\\cite_engine") {
850 vector<string> engine = getVectorFromString(lex.getString());
851 setCiteEngine(engine);
852 } else if (token == "\\cite_engine_type") {
855 cite_engine_type_ = citeenginetypetranslator().find(engine_type);
856 } else if (token == "\\biblio_style") {
858 biblio_style = lex.getString();
859 } else if (token == "\\use_bibtopic") {
861 } else if (token == "\\use_indices") {
863 } else if (token == "\\tracking_changes") {
864 lex >> track_changes;
865 } else if (token == "\\output_changes") {
866 lex >> output_changes;
867 } else if (token == "\\branch") {
869 docstring branch = lex.getDocString();
870 branchlist().add(branch);
873 string const tok = lex.getString();
874 if (tok == "\\end_branch")
876 Branch * branch_ptr = branchlist().find(branch);
877 if (tok == "\\selected") {
880 branch_ptr->setSelected(lex.getInteger());
882 if (tok == "\\filename_suffix") {
885 branch_ptr->setFileNameSuffix(lex.getInteger());
887 if (tok == "\\color") {
889 string color = lex.getString();
891 branch_ptr->setColor(color);
892 // Update also the Color table:
894 color = lcolor.getX11Name(Color_background);
896 lcolor.setColor(to_utf8(branch), color);
899 } else if (token == "\\index") {
901 docstring index = lex.getDocString();
903 indiceslist().add(index);
906 string const tok = lex.getString();
907 if (tok == "\\end_index")
909 Index * index_ptr = indiceslist().find(index);
910 if (tok == "\\shortcut") {
912 shortcut = lex.getDocString();
914 index_ptr->setShortcut(shortcut);
916 if (tok == "\\color") {
918 string color = lex.getString();
920 index_ptr->setColor(color);
921 // Update also the Color table:
923 color = lcolor.getX11Name(Color_background);
925 if (!shortcut.empty())
926 lcolor.setColor(to_utf8(shortcut), color);
929 } else if (token == "\\author") {
931 istringstream ss(lex.getString());
935 } else if (token == "\\paperorientation") {
938 orientation = paperorientationtranslator().find(orient);
939 } else if (token == "\\backgroundcolor") {
941 backgroundcolor = lyx::rgbFromHexName(lex.getString());
942 isbackgroundcolor = true;
943 } else if (token == "\\fontcolor") {
945 fontcolor = lyx::rgbFromHexName(lex.getString());
947 } else if (token == "\\notefontcolor") {
949 string color = lex.getString();
950 notefontcolor = lyx::rgbFromHexName(color);
951 lcolor.setColor("notefontcolor", color);
952 } else if (token == "\\boxbgcolor") {
954 string color = lex.getString();
955 boxbgcolor = lyx::rgbFromHexName(color);
956 lcolor.setColor("boxbgcolor", color);
957 } else if (token == "\\paperwidth") {
959 } else if (token == "\\paperheight") {
961 } else if (token == "\\leftmargin") {
963 } else if (token == "\\topmargin") {
965 } else if (token == "\\rightmargin") {
967 } else if (token == "\\bottommargin") {
969 } else if (token == "\\headheight") {
971 } else if (token == "\\headsep") {
973 } else if (token == "\\footskip") {
975 } else if (token == "\\columnsep") {
977 } else if (token == "\\paperfontsize") {
979 } else if (token == "\\papercolumns") {
981 } else if (token == "\\listings_params") {
984 listings_params = InsetListingsParams(par).params();
985 } else if (token == "\\papersides") {
988 sides = sidestranslator().find(psides);
989 } else if (token == "\\paperpagestyle") {
991 } else if (token == "\\bullet") {
993 } else if (token == "\\bulletLaTeX") {
994 readBulletsLaTeX(lex);
995 } else if (token == "\\secnumdepth") {
997 } else if (token == "\\tocdepth") {
999 } else if (token == "\\spacing") {
1003 if (nspacing == "other") {
1006 spacing().set(spacetranslator().find(nspacing), tmp_val);
1007 } else if (token == "\\float_placement") {
1008 lex >> float_placement;
1010 } else if (prefixIs(token, "\\pdf_") || token == "\\use_hyperref") {
1011 string toktmp = pdfoptions().readToken(lex, token);
1012 if (!toktmp.empty()) {
1013 lyxerr << "PDFOptions::readToken(): Unknown token: " <<
1017 } else if (token == "\\html_math_output") {
1020 html_math_output = static_cast<MathOutput>(temp);
1021 } else if (token == "\\html_be_strict") {
1022 lex >> html_be_strict;
1023 } else if (token == "\\html_css_as_file") {
1024 lex >> html_css_as_file;
1025 } else if (token == "\\html_math_img_scale") {
1026 lex >> html_math_img_scale;
1027 } else if (token == "\\html_latex_start") {
1029 html_latex_start = lex.getString();
1030 } else if (token == "\\html_latex_end") {
1032 html_latex_end = lex.getString();
1033 } else if (token == "\\output_sync") {
1035 } else if (token == "\\output_sync_macro") {
1036 lex >> output_sync_macro;
1037 } else if (token == "\\use_refstyle") {
1038 lex >> use_refstyle;
1040 lyxerr << "BufferParams::readToken(): Unknown token: " <<
1050 // Quote argument if it contains spaces
1051 string quoteIfNeeded(string const & str) {
1052 if (contains(str, ' '))
1053 return "\"" + str + "\"";
1059 void BufferParams::writeFile(ostream & os, Buffer const * buf) const
1061 // The top of the file is written by the buffer.
1062 // Prints out the buffer info into the .lyx file given by file
1064 os << "\\save_transient_properties "
1065 << convert<string>(save_transient_properties) << '\n';
1067 // the document directory (must end with a path separator)
1068 // realPath() is used to resolve symlinks, while addPath(..., "")
1069 // ensures a trailing path separator.
1071 string filepath = addPath(buf->fileName().onlyPath().realPath(), "");
1072 string const sysdir = inSystemDir(FileName(filepath), docsys) ? docsys
1073 : addPath(package().system_support().realPath(), "");
1074 string const relpath =
1075 to_utf8(makeRelPath(from_utf8(filepath), from_utf8(sysdir)));
1076 if (!prefixIs(relpath, "../") && !FileName::isAbsolute(relpath))
1077 filepath = addPath("/systemlyxdir", relpath);
1078 else if (!save_transient_properties || !lyxrc.save_origin)
1079 filepath = "unavailable";
1080 os << "\\origin " << quoteIfNeeded(filepath) << '\n';
1083 os << "\\textclass "
1084 << quoteIfNeeded(buf->includedFilePath(addName(buf->layoutPos(),
1085 baseClass()->name()), "layout"))
1088 // then the preamble
1089 if (!preamble.empty()) {
1090 // remove '\n' from the end of preamble
1091 docstring const tmppreamble = rtrim(preamble, "\n");
1092 os << "\\begin_preamble\n"
1093 << to_utf8(tmppreamble)
1094 << "\n\\end_preamble\n";
1098 if (!options.empty()) {
1099 os << "\\options " << options << '\n';
1102 // use the class options defined in the layout?
1103 os << "\\use_default_options "
1104 << convert<string>(use_default_options) << "\n";
1106 // the master document
1107 if (!master.empty()) {
1108 os << "\\master " << master << '\n';
1112 if (!removed_modules_.empty()) {
1113 os << "\\begin_removed_modules" << '\n';
1114 list<string>::const_iterator it = removed_modules_.begin();
1115 list<string>::const_iterator en = removed_modules_.end();
1116 for (; it != en; ++it)
1118 os << "\\end_removed_modules" << '\n';
1122 if (!layout_modules_.empty()) {
1123 os << "\\begin_modules" << '\n';
1124 LayoutModuleList::const_iterator it = layout_modules_.begin();
1125 LayoutModuleList::const_iterator en = layout_modules_.end();
1126 for (; it != en; ++it)
1128 os << "\\end_modules" << '\n';
1132 if (!included_children_.empty()) {
1133 os << "\\begin_includeonly" << '\n';
1134 list<string>::const_iterator it = included_children_.begin();
1135 list<string>::const_iterator en = included_children_.end();
1136 for (; it != en; ++it)
1138 os << "\\end_includeonly" << '\n';
1140 os << "\\maintain_unincluded_children "
1141 << convert<string>(maintain_unincluded_children) << '\n';
1143 // local layout information
1144 docstring const local_layout = getLocalLayout(false);
1145 if (!local_layout.empty()) {
1146 // remove '\n' from the end
1147 docstring const tmplocal = rtrim(local_layout, "\n");
1148 os << "\\begin_local_layout\n"
1149 << to_utf8(tmplocal)
1150 << "\n\\end_local_layout\n";
1152 docstring const forced_local_layout = getLocalLayout(true);
1153 if (!forced_local_layout.empty()) {
1154 // remove '\n' from the end
1155 docstring const tmplocal = rtrim(forced_local_layout, "\n");
1156 os << "\\begin_forced_local_layout\n"
1157 << to_utf8(tmplocal)
1158 << "\n\\end_forced_local_layout\n";
1161 // then the text parameters
1162 if (language != ignore_language)
1163 os << "\\language " << language->lang() << '\n';
1164 os << "\\language_package " << lang_package
1165 << "\n\\inputencoding " << inputenc
1166 << "\n\\fontencoding " << fontenc
1167 << "\n\\font_roman \"" << fonts_roman[0]
1168 << "\" \"" << fonts_roman[1] << '"'
1169 << "\n\\font_sans \"" << fonts_sans[0]
1170 << "\" \"" << fonts_sans[1] << '"'
1171 << "\n\\font_typewriter \"" << fonts_typewriter[0]
1172 << "\" \"" << fonts_typewriter[1] << '"'
1173 << "\n\\font_math \"" << fonts_math[0]
1174 << "\" \"" << fonts_math[1] << '"'
1175 << "\n\\font_default_family " << fonts_default_family
1176 << "\n\\use_non_tex_fonts " << convert<string>(useNonTeXFonts)
1177 << "\n\\font_sc " << convert<string>(fonts_expert_sc)
1178 << "\n\\font_osf " << convert<string>(fonts_old_figures)
1179 << "\n\\font_sf_scale " << fonts_sans_scale[0]
1180 << ' ' << fonts_sans_scale[1]
1181 << "\n\\font_tt_scale " << fonts_typewriter_scale[0]
1182 << ' ' << fonts_typewriter_scale[1]
1184 if (!fonts_cjk.empty()) {
1185 os << "\\font_cjk " << fonts_cjk << '\n';
1187 os << "\\use_microtype " << convert<string>(use_microtype) << '\n';
1188 os << "\\graphics " << graphics_driver << '\n';
1189 os << "\\default_output_format " << default_output_format << '\n';
1190 os << "\\output_sync " << output_sync << '\n';
1191 if (!output_sync_macro.empty())
1192 os << "\\output_sync_macro \"" << output_sync_macro << "\"\n";
1193 os << "\\bibtex_command " << bibtex_command << '\n';
1194 os << "\\index_command " << index_command << '\n';
1196 if (!float_placement.empty()) {
1197 os << "\\float_placement " << float_placement << '\n';
1199 os << "\\paperfontsize " << fontsize << '\n';
1201 spacing().writeFile(os);
1202 pdfoptions().writeFile(os);
1204 os << "\\papersize " << string_papersize[papersize]
1205 << "\n\\use_geometry " << convert<string>(use_geometry);
1206 map<string, string> const & packages = auto_packages();
1207 for (map<string, string>::const_iterator it = packages.begin();
1208 it != packages.end(); ++it)
1209 os << "\n\\use_package " << it->first << ' '
1210 << use_package(it->first);
1212 os << "\n\\cite_engine ";
1214 if (!cite_engine_.empty()) {
1215 LayoutModuleList::const_iterator be = cite_engine_.begin();
1216 LayoutModuleList::const_iterator en = cite_engine_.end();
1217 for (LayoutModuleList::const_iterator it = be; it != en; ++it) {
1226 os << "\n\\cite_engine_type " << citeenginetypetranslator().find(cite_engine_type_)
1227 << "\n\\biblio_style " << biblio_style
1228 << "\n\\use_bibtopic " << convert<string>(use_bibtopic)
1229 << "\n\\use_indices " << convert<string>(use_indices)
1230 << "\n\\paperorientation " << string_orientation[orientation]
1231 << "\n\\suppress_date " << convert<string>(suppress_date)
1232 << "\n\\justification " << convert<string>(justification)
1233 << "\n\\use_refstyle " << use_refstyle
1235 if (isbackgroundcolor == true)
1236 os << "\\backgroundcolor " << lyx::X11hexname(backgroundcolor) << '\n';
1237 if (isfontcolor == true)
1238 os << "\\fontcolor " << lyx::X11hexname(fontcolor) << '\n';
1239 if (notefontcolor != lyx::rgbFromHexName("#cccccc"))
1240 os << "\\notefontcolor " << lyx::X11hexname(notefontcolor) << '\n';
1241 if (boxbgcolor != lyx::rgbFromHexName("#ff0000"))
1242 os << "\\boxbgcolor " << lyx::X11hexname(boxbgcolor) << '\n';
1244 BranchList::const_iterator it = branchlist().begin();
1245 BranchList::const_iterator end = branchlist().end();
1246 for (; it != end; ++it) {
1247 os << "\\branch " << to_utf8(it->branch())
1248 << "\n\\selected " << it->isSelected()
1249 << "\n\\filename_suffix " << it->hasFileNameSuffix()
1250 << "\n\\color " << lyx::X11hexname(it->color())
1255 IndicesList::const_iterator iit = indiceslist().begin();
1256 IndicesList::const_iterator iend = indiceslist().end();
1257 for (; iit != iend; ++iit) {
1258 os << "\\index " << to_utf8(iit->index())
1259 << "\n\\shortcut " << to_utf8(iit->shortcut())
1260 << "\n\\color " << lyx::X11hexname(iit->color())
1265 if (!paperwidth.empty())
1266 os << "\\paperwidth "
1267 << VSpace(paperwidth).asLyXCommand() << '\n';
1268 if (!paperheight.empty())
1269 os << "\\paperheight "
1270 << VSpace(paperheight).asLyXCommand() << '\n';
1271 if (!leftmargin.empty())
1272 os << "\\leftmargin "
1273 << VSpace(leftmargin).asLyXCommand() << '\n';
1274 if (!topmargin.empty())
1275 os << "\\topmargin "
1276 << VSpace(topmargin).asLyXCommand() << '\n';
1277 if (!rightmargin.empty())
1278 os << "\\rightmargin "
1279 << VSpace(rightmargin).asLyXCommand() << '\n';
1280 if (!bottommargin.empty())
1281 os << "\\bottommargin "
1282 << VSpace(bottommargin).asLyXCommand() << '\n';
1283 if (!headheight.empty())
1284 os << "\\headheight "
1285 << VSpace(headheight).asLyXCommand() << '\n';
1286 if (!headsep.empty())
1288 << VSpace(headsep).asLyXCommand() << '\n';
1289 if (!footskip.empty())
1291 << VSpace(footskip).asLyXCommand() << '\n';
1292 if (!columnsep.empty())
1293 os << "\\columnsep "
1294 << VSpace(columnsep).asLyXCommand() << '\n';
1295 os << "\\secnumdepth " << secnumdepth
1296 << "\n\\tocdepth " << tocdepth
1297 << "\n\\paragraph_separation "
1298 << string_paragraph_separation[paragraph_separation];
1299 if (!paragraph_separation)
1300 os << "\n\\paragraph_indentation " << getIndentation().asLyXCommand();
1302 os << "\n\\defskip " << getDefSkip().asLyXCommand();
1303 os << "\n\\quotes_language "
1304 << string_quotes_language[quotes_language]
1305 << "\n\\papercolumns " << columns
1306 << "\n\\papersides " << sides
1307 << "\n\\paperpagestyle " << pagestyle << '\n';
1308 if (!listings_params.empty())
1309 os << "\\listings_params \"" <<
1310 InsetListingsParams(listings_params).encodedString() << "\"\n";
1311 for (int i = 0; i < 4; ++i) {
1312 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1313 if (user_defined_bullet(i).getFont() != -1) {
1314 os << "\\bullet " << i << " "
1315 << user_defined_bullet(i).getFont() << " "
1316 << user_defined_bullet(i).getCharacter() << " "
1317 << user_defined_bullet(i).getSize() << "\n";
1321 os << "\\bulletLaTeX " << i << " \""
1322 << lyx::to_ascii(user_defined_bullet(i).getText())
1328 os << "\\tracking_changes "
1329 << (save_transient_properties ? convert<string>(track_changes) : "false")
1332 os << "\\output_changes "
1333 << (save_transient_properties ? convert<string>(output_changes) : "false")
1336 os << "\\html_math_output " << html_math_output << '\n'
1337 << "\\html_css_as_file " << html_css_as_file << '\n'
1338 << "\\html_be_strict " << convert<string>(html_be_strict) << '\n';
1340 if (html_math_img_scale != 1.0)
1341 os << "\\html_math_img_scale " << convert<string>(html_math_img_scale) << '\n';
1342 if (!html_latex_start.empty())
1343 os << "\\html_latex_start " << html_latex_start << '\n';
1344 if (!html_latex_end.empty())
1345 os << "\\html_latex_end " << html_latex_end << '\n';
1347 os << pimpl_->authorlist;
1351 void BufferParams::validate(LaTeXFeatures & features) const
1353 features.require(documentClass().requires());
1355 if (columns > 1 && language->rightToLeft())
1356 features.require("rtloutputdblcol");
1358 if (output_changes) {
1359 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1360 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1361 LaTeXFeatures::isAvailable("xcolor");
1363 switch (features.runparams().flavor) {
1364 case OutputParams::LATEX:
1365 case OutputParams::DVILUATEX:
1367 features.require("ct-dvipost");
1368 features.require("dvipost");
1369 } else if (xcolorulem) {
1370 features.require("ct-xcolor-ulem");
1371 features.require("ulem");
1372 features.require("xcolor");
1374 features.require("ct-none");
1377 case OutputParams::LUATEX:
1378 case OutputParams::PDFLATEX:
1379 case OutputParams::XETEX:
1381 features.require("ct-xcolor-ulem");
1382 features.require("ulem");
1383 features.require("xcolor");
1384 // improves color handling in PDF output
1385 features.require("pdfcolmk");
1387 features.require("ct-none");
1395 // Floats with 'Here definitely' as default setting.
1396 if (float_placement.find('H') != string::npos)
1397 features.require("float");
1399 for (PackageMap::const_iterator it = use_packages.begin();
1400 it != use_packages.end(); ++it) {
1401 if (it->first == "amsmath") {
1402 // AMS Style is at document level
1403 if (it->second == package_on ||
1404 features.isProvided("amsmath"))
1405 features.require(it->first);
1406 } else if (it->second == package_on)
1407 features.require(it->first);
1410 // Document-level line spacing
1411 if (spacing().getSpace() != Spacing::Single && !spacing().isDefault())
1412 features.require("setspace");
1414 // the bullet shapes are buffer level not paragraph level
1415 // so they are tested here
1416 for (int i = 0; i < 4; ++i) {
1417 if (user_defined_bullet(i) == ITEMIZE_DEFAULTS[i])
1419 int const font = user_defined_bullet(i).getFont();
1421 int const c = user_defined_bullet(i).getCharacter();
1427 features.require("latexsym");
1429 } else if (font == 1) {
1430 features.require("amssymb");
1431 } else if (font >= 2 && font <= 5) {
1432 features.require("pifont");
1436 if (pdfoptions().use_hyperref) {
1437 features.require("hyperref");
1438 // due to interferences with babel and hyperref, the color package has to
1439 // be loaded after hyperref when hyperref is used with the colorlinks
1440 // option, see http://www.lyx.org/trac/ticket/5291
1441 if (pdfoptions().colorlinks)
1442 features.require("color");
1444 if (!listings_params.empty()) {
1445 // do not test validity because listings_params is
1446 // supposed to be valid
1448 InsetListingsParams(listings_params).separatedParams(true);
1449 // we can't support all packages, but we should load the color package
1450 if (par.find("\\color", 0) != string::npos)
1451 features.require("color");
1454 // some languages are only available via polyglossia
1455 if (features.hasPolyglossiaExclusiveLanguages())
1456 features.require("polyglossia");
1458 if (useNonTeXFonts && fontsMath() != "auto")
1459 features.require("unicode-math");
1462 features.require("microtype");
1464 if (!language->requires().empty())
1465 features.require(language->requires());
1469 bool BufferParams::writeLaTeX(otexstream & os, LaTeXFeatures & features,
1470 FileName const & filepath) const
1472 // http://www.tug.org/texmf-dist/doc/latex/base/fixltx2e.pdf
1473 // !! To use the Fix-cm package, load it before \documentclass, and use the command
1474 // \RequirePackage to do so, rather than the normal \usepackage
1475 // Do not try to load any other package before the document class, unless you
1476 // have a thorough understanding of the LATEX internals and know exactly what you
1478 if (features.mustProvide("fix-cm"))
1479 os << "\\RequirePackage{fix-cm}\n";
1480 // Likewise for fixltx2e. If other packages conflict with this policy,
1481 // treat it as a package bug (and report it!)
1482 // See http://www.latex-project.org/cgi-bin/ltxbugs2html?pr=latex/4407
1483 if (features.mustProvide("fixltx2e"))
1484 os << "\\RequirePackage{fixltx2e}\n";
1486 os << "\\documentclass";
1488 DocumentClass const & tclass = documentClass();
1490 ostringstream clsoptions; // the document class options.
1492 if (tokenPos(tclass.opt_fontsize(),
1493 '|', fontsize) >= 0) {
1494 // only write if existing in list (and not default)
1495 clsoptions << fontsize << "pt,";
1498 // all paper sizes except of A4, A5, B5 and the US sizes need the
1500 bool nonstandard_papersize = papersize != PAPER_DEFAULT
1501 && papersize != PAPER_USLETTER
1502 && papersize != PAPER_USLEGAL
1503 && papersize != PAPER_USEXECUTIVE
1504 && papersize != PAPER_A4
1505 && papersize != PAPER_A5
1506 && papersize != PAPER_B5;
1508 if (!use_geometry) {
1509 switch (papersize) {
1511 clsoptions << "a4paper,";
1513 case PAPER_USLETTER:
1514 clsoptions << "letterpaper,";
1517 clsoptions << "a5paper,";
1520 clsoptions << "b5paper,";
1522 case PAPER_USEXECUTIVE:
1523 clsoptions << "executivepaper,";
1526 clsoptions << "legalpaper,";
1560 if (sides != tclass.sides()) {
1563 clsoptions << "oneside,";
1566 clsoptions << "twoside,";
1572 if (columns != tclass.columns()) {
1574 clsoptions << "twocolumn,";
1576 clsoptions << "onecolumn,";
1580 && orientation == ORIENTATION_LANDSCAPE)
1581 clsoptions << "landscape,";
1583 // language should be a parameter to \documentclass
1584 if (language->babel() == "hebrew"
1585 && default_language->babel() != "hebrew")
1586 // This seems necessary
1587 features.useLanguage(default_language);
1589 ostringstream language_options;
1590 bool const use_babel = features.useBabel() && !features.isProvided("babel");
1591 bool const use_polyglossia = features.usePolyglossia();
1592 bool const global = lyxrc.language_global_options;
1593 if (use_babel || (use_polyglossia && global)) {
1594 language_options << features.getBabelLanguages();
1595 if (!language->babel().empty()) {
1596 if (!language_options.str().empty())
1597 language_options << ',';
1598 language_options << language->babel();
1600 if (global && !features.needBabelLangOptions()
1601 && !language_options.str().empty())
1602 clsoptions << language_options.str() << ',';
1605 // the predefined options from the layout
1606 if (use_default_options && !tclass.options().empty())
1607 clsoptions << tclass.options() << ',';
1609 // the user-defined options
1610 if (!options.empty()) {
1611 clsoptions << options << ',';
1614 string strOptions(clsoptions.str());
1615 if (!strOptions.empty()) {
1616 strOptions = rtrim(strOptions, ",");
1618 os << '[' << from_utf8(strOptions) << ']';
1621 os << '{' << from_ascii(tclass.latexname()) << "}\n";
1622 // end of \documentclass defs
1624 // if we use fontspec or newtxmath, we have to load the AMS packages here
1625 string const ams = features.loadAMSPackages();
1626 bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
1627 bool const use_newtxmath =
1628 theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getUsedPackage(
1629 ot1, false, false) == "newtxmath";
1630 if ((useNonTeXFonts || use_newtxmath) && !ams.empty())
1631 os << from_ascii(ams);
1633 if (useNonTeXFonts) {
1634 if (!features.isProvided("fontspec"))
1635 os << "\\usepackage{fontspec}\n";
1636 if (features.mustProvide("unicode-math")
1637 && features.isAvailable("unicode-math"))
1638 os << "\\usepackage{unicode-math}\n";
1641 // font selection must be done before loading fontenc.sty
1642 string const fonts = loadFonts(features);
1644 os << from_utf8(fonts);
1646 if (fonts_default_family != "default")
1647 os << "\\renewcommand{\\familydefault}{\\"
1648 << from_ascii(fonts_default_family) << "}\n";
1650 // set font encoding
1651 // XeTeX and LuaTeX (with OS fonts) do not need fontenc
1652 if (!useNonTeXFonts && !features.isProvided("fontenc")
1653 && font_encoding() != "default") {
1654 // get main font encodings
1655 vector<string> fontencs = font_encodings();
1656 // get font encodings of secondary languages
1657 features.getFontEncodings(fontencs);
1658 if (!fontencs.empty()) {
1659 os << "\\usepackage["
1660 << from_ascii(getStringFromVector(fontencs))
1665 // handle inputenc etc.
1666 writeEncodingPreamble(os, features);
1669 if (!features.runparams().includeall && !included_children_.empty()) {
1670 os << "\\includeonly{";
1671 list<string>::const_iterator it = included_children_.begin();
1672 list<string>::const_iterator en = included_children_.end();
1674 for (; it != en; ++it) {
1675 string incfile = *it;
1676 FileName inc = makeAbsPath(incfile, filepath.absFileName());
1677 string mangled = DocFileName(changeExtension(inc.absFileName(), ".tex")).
1679 if (!features.runparams().nice)
1681 // \includeonly doesn't want an extension
1682 incfile = changeExtension(incfile, string());
1683 incfile = support::latex_path(incfile);
1684 if (!incfile.empty()) {
1687 os << from_utf8(incfile);
1694 if (!features.isProvided("geometry")
1695 && (use_geometry || nonstandard_papersize)) {
1696 odocstringstream ods;
1697 if (!getGraphicsDriver("geometry").empty())
1698 ods << getGraphicsDriver("geometry");
1699 if (orientation == ORIENTATION_LANDSCAPE)
1700 ods << ",landscape";
1701 switch (papersize) {
1703 if (!paperwidth.empty())
1704 ods << ",paperwidth="
1705 << from_ascii(paperwidth);
1706 if (!paperheight.empty())
1707 ods << ",paperheight="
1708 << from_ascii(paperheight);
1710 case PAPER_USLETTER:
1711 ods << ",letterpaper";
1714 ods << ",legalpaper";
1716 case PAPER_USEXECUTIVE:
1717 ods << ",executivepaper";
1806 docstring const g_options = trim(ods.str(), ",");
1807 os << "\\usepackage";
1808 if (!g_options.empty())
1809 os << '[' << g_options << ']';
1810 os << "{geometry}\n";
1811 // output this only if use_geometry is true
1813 os << "\\geometry{verbose";
1814 if (!topmargin.empty())
1815 os << ",tmargin=" << from_ascii(Length(topmargin).asLatexString());
1816 if (!bottommargin.empty())
1817 os << ",bmargin=" << from_ascii(Length(bottommargin).asLatexString());
1818 if (!leftmargin.empty())
1819 os << ",lmargin=" << from_ascii(Length(leftmargin).asLatexString());
1820 if (!rightmargin.empty())
1821 os << ",rmargin=" << from_ascii(Length(rightmargin).asLatexString());
1822 if (!headheight.empty())
1823 os << ",headheight=" << from_ascii(Length(headheight).asLatexString());
1824 if (!headsep.empty())
1825 os << ",headsep=" << from_ascii(Length(headsep).asLatexString());
1826 if (!footskip.empty())
1827 os << ",footskip=" << from_ascii(Length(footskip).asLatexString());
1828 if (!columnsep.empty())
1829 os << ",columnsep=" << from_ascii(Length(columnsep).asLatexString());
1832 } else if (orientation == ORIENTATION_LANDSCAPE
1833 || papersize != PAPER_DEFAULT) {
1834 features.require("papersize");
1837 if (tokenPos(tclass.opt_pagestyle(), '|', pagestyle) >= 0) {
1838 if (pagestyle == "fancy")
1839 os << "\\usepackage{fancyhdr}\n";
1840 os << "\\pagestyle{" << from_ascii(pagestyle) << "}\n";
1843 // only output when the background color is not default
1844 if (isbackgroundcolor == true) {
1845 // only require color here, the background color will be defined
1846 // in LaTeXFeatures.cpp to avoid interferences with the LaTeX
1848 features.require("color");
1849 features.require("pagecolor");
1852 // only output when the font color is not default
1853 if (isfontcolor == true) {
1854 // only require color here, the font color will be defined
1855 // in LaTeXFeatures.cpp to avoid interferences with the LaTeX
1857 features.require("color");
1858 features.require("fontcolor");
1861 // Only if class has a ToC hierarchy
1862 if (tclass.hasTocLevels()) {
1863 if (secnumdepth != tclass.secnumdepth()) {
1864 os << "\\setcounter{secnumdepth}{"
1868 if (tocdepth != tclass.tocdepth()) {
1869 os << "\\setcounter{tocdepth}{"
1875 if (paragraph_separation) {
1876 // when skip separation
1877 switch (getDefSkip().kind()) {
1878 case VSpace::SMALLSKIP:
1879 os << "\\setlength{\\parskip}{\\smallskipamount}\n";
1881 case VSpace::MEDSKIP:
1882 os << "\\setlength{\\parskip}{\\medskipamount}\n";
1884 case VSpace::BIGSKIP:
1885 os << "\\setlength{\\parskip}{\\bigskipamount}\n";
1887 case VSpace::LENGTH:
1888 os << "\\setlength{\\parskip}{"
1889 << from_utf8(getDefSkip().length().asLatexString())
1892 default: // should never happen // Then delete it.
1893 os << "\\setlength{\\parskip}{\\medskipamount}\n";
1896 os << "\\setlength{\\parindent}{0pt}\n";
1898 // when separation by indentation
1899 // only output something when a width is given
1900 if (getIndentation().asLyXCommand() != "default") {
1901 os << "\\setlength{\\parindent}{"
1902 << from_utf8(getIndentation().asLatexCommand())
1907 // Now insert the LyX specific LaTeX commands...
1908 features.resolveAlternatives();
1909 features.expandMultiples();
1912 if (!output_sync_macro.empty())
1913 os << from_utf8(output_sync_macro) +"\n";
1914 else if (features.runparams().flavor == OutputParams::LATEX)
1915 os << "\\usepackage[active]{srcltx}\n";
1916 else if (features.runparams().flavor == OutputParams::PDFLATEX)
1917 os << "\\synctex=-1\n";
1920 // The package options (via \PassOptionsToPackage)
1921 os << from_ascii(features.getPackageOptions());
1923 // due to interferences with babel and hyperref, the color package has to
1924 // be loaded (when it is not already loaded) before babel when hyperref
1925 // is used with the colorlinks option, see
1926 // http://www.lyx.org/trac/ticket/5291
1927 // we decided therefore to load color always before babel, see
1928 // http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg144349.html
1929 os << from_ascii(features.getColorOptions());
1931 // If we use hyperref, jurabib, japanese, varioref or vietnamese,
1932 // we have to call babel before
1934 && (features.isRequired("jurabib")
1935 || features.isRequired("hyperref")
1936 || features.isRequired("varioref")
1937 || features.isRequired("vietnamese")
1938 || features.isRequired("japanese"))) {
1939 os << features.getBabelPresettings();
1941 os << from_utf8(babelCall(language_options.str(),
1942 features.needBabelLangOptions())) + '\n';
1943 os << features.getBabelPostsettings();
1946 // The optional packages;
1947 os << from_ascii(features.getPackages());
1949 // Additional Indices
1950 if (features.isRequired("splitidx")) {
1951 IndicesList::const_iterator iit = indiceslist().begin();
1952 IndicesList::const_iterator iend = indiceslist().end();
1953 for (; iit != iend; ++iit) {
1954 pair<docstring, docstring> indexname_latex =
1955 features.runparams().encoding->latexString(iit->index(),
1956 features.runparams().dryrun);
1957 if (!indexname_latex.second.empty()) {
1958 // issue a warning about omitted characters
1959 // FIXME: should be passed to the error dialog
1960 frontend::Alert::warning(_("Uncodable characters"),
1961 bformat(_("The following characters that are used in an index name are not\n"
1962 "representable in the current encoding and therefore have been omitted:\n%1$s."),
1963 indexname_latex.second));
1965 os << "\\newindex[";
1966 os << indexname_latex.first;
1968 os << escape(iit->shortcut());
1974 os << from_utf8(spacing().writePreamble(features.isProvided("SetSpace")));
1977 // * Hyperref manual: "Make sure it comes last of your loaded
1978 // packages, to give it a fighting chance of not being over-written,
1979 // since its job is to redefine many LaTeX commands."
1980 // * Email from Heiko Oberdiek: "It is usually better to load babel
1981 // before hyperref. Then hyperref has a chance to detect babel.
1982 // * Has to be loaded before the "LyX specific LaTeX commands" to
1983 // avoid errors with algorithm floats.
1984 // use hyperref explicitly if it is required
1985 if (features.isRequired("hyperref")) {
1986 OutputParams tmp_params = features.runparams();
1987 pdfoptions().writeLaTeX(tmp_params, os,
1988 features.isProvided("hyperref"));
1989 // correctly break URLs with hyperref and dvi output
1990 if (features.runparams().flavor == OutputParams::LATEX
1991 && features.isAvailable("breakurl"))
1992 os << "\\usepackage{breakurl}\n";
1993 } else if (features.isRequired("nameref"))
1994 // hyperref loads this automatically
1995 os << "\\usepackage{nameref}\n";
1997 // bibtopic needs to be loaded after hyperref.
1998 // the dot provides the aux file naming which LyX can detect.
1999 if (features.mustProvide("bibtopic"))
2000 os << "\\usepackage[dot]{bibtopic}\n";
2002 // Will be surrounded by \makeatletter and \makeatother when not empty
2003 otexstringstream atlyxpreamble;
2005 // Some macros LyX will need
2007 TexString tmppreamble = features.getMacros();
2008 if (!tmppreamble.str.empty())
2009 atlyxpreamble << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2010 "LyX specific LaTeX commands.\n"
2011 << move(tmppreamble)
2014 // the text class specific preamble
2016 docstring tmppreamble = features.getTClassPreamble();
2017 if (!tmppreamble.empty())
2018 atlyxpreamble << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2019 "Textclass specific LaTeX commands.\n"
2023 // suppress date if selected
2024 // use \@ifundefined because we cannot be sure that every document class
2025 // has a \date command
2027 atlyxpreamble << "\\@ifundefined{date}{}{\\date{}}\n";
2029 /* the user-defined preamble */
2030 if (!containsOnly(preamble, " \n\t")) {
2032 atlyxpreamble << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2033 "User specified LaTeX commands.\n";
2035 // Check if the user preamble contains uncodable glyphs
2036 odocstringstream user_preamble;
2037 docstring uncodable_glyphs;
2038 Encoding const * const enc = features.runparams().encoding;
2040 for (size_t n = 0; n < preamble.size(); ++n) {
2041 char_type c = preamble[n];
2042 if (!enc->encodable(c)) {
2043 docstring const glyph(1, c);
2044 LYXERR0("Uncodable character '"
2046 << "' in user preamble!");
2047 uncodable_glyphs += glyph;
2048 if (features.runparams().dryrun) {
2049 user_preamble << "<" << _("LyX Warning: ")
2050 << _("uncodable character") << " '";
2051 user_preamble.put(c);
2052 user_preamble << "'>";
2055 user_preamble.put(c);
2058 user_preamble << preamble;
2060 // On BUFFER_VIEW|UPDATE, warn user if we found uncodable glyphs
2061 if (!features.runparams().dryrun && !uncodable_glyphs.empty()) {
2062 frontend::Alert::warning(
2063 _("Uncodable character in user preamble"),
2065 _("The user preamble of your document contains glyphs "
2066 "that are unknown in the current document encoding "
2067 "(namely %1$s).\nThese glyphs are omitted "
2068 " from the output, which may result in "
2069 "incomplete output."
2070 "\n\nPlease select an appropriate "
2071 "document encoding\n"
2072 "(such as utf8) or change the "
2073 "preamble code accordingly."),
2076 atlyxpreamble << user_preamble.str() << '\n';
2079 // footmisc must be loaded after setspace
2080 // Load it here to avoid clashes with footmisc loaded in the user
2081 // preamble. For that reason we also pass the options via
2082 // \PassOptionsToPackage in getPreamble() and not here.
2083 if (features.mustProvide("footmisc"))
2084 atlyxpreamble << "\\usepackage{footmisc}\n";
2086 // subfig loads internally the LaTeX package "caption". As
2087 // caption is a very popular package, users will load it in
2088 // the preamble. Therefore we must load subfig behind the
2089 // user-defined preamble and check if the caption package was
2090 // loaded or not. For the case that caption is loaded before
2091 // subfig, there is the subfig option "caption=false". This
2092 // option also works when a koma-script class is used and
2093 // koma's own caption commands are used instead of caption. We
2094 // use \PassOptionsToPackage here because the user could have
2095 // already loaded subfig in the preamble.
2096 if (features.mustProvide("subfig"))
2097 atlyxpreamble << "\\@ifundefined{showcaptionsetup}{}{%\n"
2098 " \\PassOptionsToPackage{caption=false}{subfig}}\n"
2099 "\\usepackage{subfig}\n";
2101 // Itemize bullet settings need to be last in case the user
2102 // defines their own bullets that use a package included
2103 // in the user-defined preamble -- ARRae
2104 // Actually it has to be done much later than that
2105 // since some packages like frenchb make modifications
2106 // at \begin{document} time -- JMarc
2107 docstring bullets_def;
2108 for (int i = 0; i < 4; ++i) {
2109 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
2110 if (bullets_def.empty())
2111 bullets_def += "\\AtBeginDocument{\n";
2112 bullets_def += " \\def\\labelitemi";
2114 // `i' is one less than the item to modify
2121 bullets_def += "ii";
2127 bullets_def += '{' +
2128 user_defined_bullet(i).getText()
2133 if (!bullets_def.empty())
2134 atlyxpreamble << bullets_def << "}\n\n";
2136 if (!atlyxpreamble.empty())
2137 os << "\n\\makeatletter\n"
2138 << atlyxpreamble.release()
2139 << "\\makeatother\n\n";
2141 // We try to load babel late, in case it interferes with other packages.
2142 // Jurabib, hyperref, varioref, bicaption and listings (bug 8995) have to be
2143 // called after babel, though.
2144 if (use_babel && !features.isRequired("jurabib")
2145 && !features.isRequired("hyperref")
2146 && !features.isRequired("varioref")
2147 && !features.isRequired("vietnamese")
2148 && !features.isRequired("japanese")) {
2149 os << features.getBabelPresettings();
2151 os << from_utf8(babelCall(language_options.str(),
2152 features.needBabelLangOptions())) + '\n';
2153 os << features.getBabelPostsettings();
2155 if (features.isRequired("bicaption"))
2156 os << "\\usepackage{bicaption}\n";
2157 if (!listings_params.empty() || features.mustProvide("listings"))
2158 os << "\\usepackage{listings}\n";
2159 if (!listings_params.empty()) {
2161 // do not test validity because listings_params is
2162 // supposed to be valid
2164 InsetListingsParams(listings_params).separatedParams(true);
2165 os << from_utf8(par);
2169 // xunicode needs to be loaded at least after amsmath, amssymb,
2170 // esint and the other packages that provide special glyphs
2171 // The package only supports XeTeX currently.
2172 if (features.runparams().flavor == OutputParams::XETEX
2174 os << "\\usepackage{xunicode}\n";
2176 // Polyglossia must be loaded last
2177 if (use_polyglossia) {
2179 os << "\\usepackage{polyglossia}\n";
2180 // set the main language
2181 os << "\\setdefaultlanguage";
2182 if (!language->polyglossiaOpts().empty())
2183 os << "[" << from_ascii(language->polyglossiaOpts()) << "]";
2184 os << "{" << from_ascii(language->polyglossia()) << "}\n";
2185 // now setup the other languages
2186 std::map<std::string, std::string> const polylangs =
2187 features.getPolyglossiaLanguages();
2188 for (std::map<std::string, std::string>::const_iterator mit = polylangs.begin();
2189 mit != polylangs.end() ; ++mit) {
2190 os << "\\setotherlanguage";
2191 if (!mit->second.empty())
2192 os << "[" << from_ascii(mit->second) << "]";
2193 os << "{" << from_ascii(mit->first) << "}\n";
2197 // Load custom language package here
2198 if (features.langPackage() == LaTeXFeatures::LANG_PACK_CUSTOM) {
2199 if (lang_package == "default")
2200 os << from_utf8(lyxrc.language_custom_package);
2202 os << from_utf8(lang_package);
2206 docstring const i18npreamble =
2207 features.getTClassI18nPreamble(use_babel, use_polyglossia);
2208 if (!i18npreamble.empty())
2209 os << i18npreamble + '\n';
2215 void BufferParams::useClassDefaults()
2217 DocumentClass const & tclass = documentClass();
2219 sides = tclass.sides();
2220 columns = tclass.columns();
2221 pagestyle = tclass.pagestyle();
2222 use_default_options = true;
2223 // Only if class has a ToC hierarchy
2224 if (tclass.hasTocLevels()) {
2225 secnumdepth = tclass.secnumdepth();
2226 tocdepth = tclass.tocdepth();
2231 bool BufferParams::hasClassDefaults() const
2233 DocumentClass const & tclass = documentClass();
2235 return sides == tclass.sides()
2236 && columns == tclass.columns()
2237 && pagestyle == tclass.pagestyle()
2238 && use_default_options
2239 && secnumdepth == tclass.secnumdepth()
2240 && tocdepth == tclass.tocdepth();
2244 DocumentClass const & BufferParams::documentClass() const
2250 DocumentClassConstPtr BufferParams::documentClassPtr() const
2256 void BufferParams::setDocumentClass(DocumentClassConstPtr tc)
2258 // evil, but this function is evil
2259 doc_class_ = const_pointer_cast<DocumentClass>(tc);
2260 invalidateConverterCache();
2264 bool BufferParams::setBaseClass(string const & classname)
2266 LYXERR(Debug::TCLASS, "setBaseClass: " << classname);
2267 LayoutFileList & bcl = LayoutFileList::get();
2268 if (!bcl.haveClass(classname)) {
2270 bformat(_("The layout file:\n"
2272 "could not be found. A default textclass with default\n"
2273 "layouts will be used. LyX will not be able to produce\n"
2275 from_utf8(classname));
2276 frontend::Alert::error(_("Document class not found"), s);
2277 bcl.addEmptyClass(classname);
2280 bool const success = bcl[classname].load();
2283 bformat(_("Due to some error in it, the layout file:\n"
2285 "could not be loaded. A default textclass with default\n"
2286 "layouts will be used. LyX will not be able to produce\n"
2288 from_utf8(classname));
2289 frontend::Alert::error(_("Could not load class"), s);
2290 bcl.addEmptyClass(classname);
2293 pimpl_->baseClass_ = classname;
2294 layout_modules_.adaptToBaseClass(baseClass(), removed_modules_);
2299 LayoutFile const * BufferParams::baseClass() const
2301 if (LayoutFileList::get().haveClass(pimpl_->baseClass_))
2302 return &(LayoutFileList::get()[pimpl_->baseClass_]);
2308 LayoutFileIndex const & BufferParams::baseClassID() const
2310 return pimpl_->baseClass_;
2314 void BufferParams::makeDocumentClass(bool const clone)
2319 invalidateConverterCache();
2320 LayoutModuleList mods;
2321 LayoutModuleList::iterator it = layout_modules_.begin();
2322 LayoutModuleList::iterator en = layout_modules_.end();
2323 for (; it != en; ++it)
2324 mods.push_back(*it);
2326 it = cite_engine_.begin();
2327 en = cite_engine_.end();
2328 for (; it != en; ++it)
2329 mods.push_back(*it);
2331 doc_class_ = getDocumentClass(*baseClass(), mods, clone);
2333 TextClass::ReturnValues success = TextClass::OK;
2334 if (!forced_local_layout_.empty())
2335 success = doc_class_->read(to_utf8(forced_local_layout_),
2337 if (!local_layout_.empty() &&
2338 (success == TextClass::OK || success == TextClass::OK_OLDFORMAT))
2339 success = doc_class_->read(to_utf8(local_layout_), TextClass::MODULE);
2340 if (success != TextClass::OK && success != TextClass::OK_OLDFORMAT) {
2341 docstring const msg = _("Error reading internal layout information");
2342 frontend::Alert::warning(_("Read Error"), msg);
2347 bool BufferParams::layoutModuleCanBeAdded(string const & modName) const
2349 return layout_modules_.moduleCanBeAdded(modName, baseClass());
2353 bool BufferParams::citationModuleCanBeAdded(string const & modName) const
2355 return cite_engine_.moduleCanBeAdded(modName, baseClass());
2359 docstring BufferParams::getLocalLayout(bool forced) const
2362 return from_utf8(doc_class_->forcedLayouts());
2364 return local_layout_;
2368 void BufferParams::setLocalLayout(docstring const & layout, bool forced)
2371 forced_local_layout_ = layout;
2373 local_layout_ = layout;
2377 bool BufferParams::addLayoutModule(string const & modName)
2379 LayoutModuleList::const_iterator it = layout_modules_.begin();
2380 LayoutModuleList::const_iterator end = layout_modules_.end();
2381 for (; it != end; ++it)
2384 layout_modules_.push_back(modName);
2389 string BufferParams::bufferFormat() const
2391 return documentClass().outputFormat();
2395 bool BufferParams::isExportable(string const & format) const
2397 vector<string> backs = backends();
2398 for (vector<string>::const_iterator it = backs.begin();
2399 it != backs.end(); ++it)
2400 if (theConverters().isReachable(*it, format))
2406 vector<Format const *> const & BufferParams::exportableFormats(bool only_viewable) const
2408 vector<Format const *> & cached = only_viewable ?
2409 pimpl_->viewableFormatList : pimpl_->exportableFormatList;
2410 bool & valid = only_viewable ?
2411 pimpl_->isViewCacheValid : pimpl_->isExportCacheValid;
2415 vector<string> const backs = backends();
2416 set<string> excludes;
2417 if (useNonTeXFonts) {
2418 excludes.insert("latex");
2419 excludes.insert("pdflatex");
2421 vector<Format const *> result =
2422 theConverters().getReachable(backs[0], only_viewable, true, excludes);
2423 for (vector<string>::const_iterator it = backs.begin() + 1;
2424 it != backs.end(); ++it) {
2425 vector<Format const *> r =
2426 theConverters().getReachable(*it, only_viewable, false, excludes);
2427 result.insert(result.end(), r.begin(), r.end());
2429 sort(result.begin(), result.end(), Format::formatSorter);
2436 bool BufferParams::isExportableFormat(string const & format) const
2438 typedef vector<Format const *> Formats;
2439 Formats const & formats = exportableFormats(true);
2440 Formats::const_iterator fit = formats.begin();
2441 Formats::const_iterator end = formats.end();
2442 for (; fit != end ; ++fit) {
2443 if ((*fit)->name() == format)
2450 vector<string> BufferParams::backends() const
2453 string const buffmt = bufferFormat();
2455 // FIXME: Don't hardcode format names here, but use a flag
2456 if (buffmt == "latex") {
2457 if (encoding().package() == Encoding::japanese)
2458 v.push_back("platex");
2460 if (!useNonTeXFonts) {
2461 v.push_back("pdflatex");
2462 v.push_back("latex");
2464 v.push_back("xetex");
2465 v.push_back("luatex");
2466 v.push_back("dviluatex");
2469 v.push_back(buffmt);
2471 v.push_back("xhtml");
2472 v.push_back("text");
2478 OutputParams::FLAVOR BufferParams::getOutputFlavor(string const & format) const
2480 string const dformat = (format.empty() || format == "default") ?
2481 getDefaultOutputFormat() : format;
2482 DefaultFlavorCache::const_iterator it =
2483 default_flavors_.find(dformat);
2485 if (it != default_flavors_.end())
2488 OutputParams::FLAVOR result = OutputParams::LATEX;
2490 // FIXME It'd be better not to hardcode this, but to do
2491 // something with formats.
2492 if (dformat == "xhtml")
2493 result = OutputParams::HTML;
2494 else if (dformat == "text")
2495 result = OutputParams::TEXT;
2496 else if (dformat == "lyx")
2497 result = OutputParams::LYX;
2498 else if (dformat == "pdflatex")
2499 result = OutputParams::PDFLATEX;
2500 else if (dformat == "xetex")
2501 result = OutputParams::XETEX;
2502 else if (dformat == "luatex")
2503 result = OutputParams::LUATEX;
2504 else if (dformat == "dviluatex")
2505 result = OutputParams::DVILUATEX;
2507 // Try to determine flavor of default output format
2508 vector<string> backs = backends();
2509 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
2510 // Get shortest path to format
2511 Graph::EdgePath path;
2512 for (vector<string>::const_iterator it = backs.begin();
2513 it != backs.end(); ++it) {
2514 Graph::EdgePath p = theConverters().getPath(*it, dformat);
2515 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2520 result = theConverters().getFlavor(path);
2523 // cache this flavor
2524 default_flavors_[dformat] = result;
2529 string BufferParams::getDefaultOutputFormat() const
2531 if (!default_output_format.empty()
2532 && default_output_format != "default")
2533 return default_output_format;
2535 || encoding().package() == Encoding::japanese) {
2536 vector<Format const *> const & formats = exportableFormats(true);
2537 if (formats.empty())
2539 // return the first we find
2540 return formats.front()->name();
2543 return lyxrc.default_otf_view_format;
2544 return lyxrc.default_view_format;
2547 Font const BufferParams::getFont() const
2549 FontInfo f = documentClass().defaultfont();
2550 if (fonts_default_family == "rmdefault")
2551 f.setFamily(ROMAN_FAMILY);
2552 else if (fonts_default_family == "sfdefault")
2553 f.setFamily(SANS_FAMILY);
2554 else if (fonts_default_family == "ttdefault")
2555 f.setFamily(TYPEWRITER_FAMILY);
2556 return Font(f, language);
2560 InsetQuotes::QuoteLanguage BufferParams::getQuoteStyle(string const & qs) const
2562 return quoteslangtranslator().find(qs);
2566 bool BufferParams::isLatex() const
2568 return documentClass().outputType() == LATEX;
2572 bool BufferParams::isLiterate() const
2574 return documentClass().outputType() == LITERATE;
2578 bool BufferParams::isDocBook() const
2580 return documentClass().outputType() == DOCBOOK;
2584 void BufferParams::readPreamble(Lexer & lex)
2586 if (lex.getString() != "\\begin_preamble")
2587 lyxerr << "Error (BufferParams::readPreamble):"
2588 "consistency check failed." << endl;
2590 preamble = lex.getLongString(from_ascii("\\end_preamble"));
2594 void BufferParams::readLocalLayout(Lexer & lex, bool forced)
2596 string const expected = forced ? "\\begin_forced_local_layout" :
2597 "\\begin_local_layout";
2598 if (lex.getString() != expected)
2599 lyxerr << "Error (BufferParams::readLocalLayout):"
2600 "consistency check failed." << endl;
2603 forced_local_layout_ =
2604 lex.getLongString(from_ascii("\\end_forced_local_layout"));
2606 local_layout_ = lex.getLongString(from_ascii("\\end_local_layout"));
2610 bool BufferParams::setLanguage(string const & lang)
2612 Language const *new_language = languages.getLanguage(lang);
2613 if (!new_language) {
2614 // Language lang was not found
2617 language = new_language;
2622 void BufferParams::readLanguage(Lexer & lex)
2624 if (!lex.next()) return;
2626 string const tmptok = lex.getString();
2628 // check if tmptok is part of tex_babel in tex-defs.h
2629 if (!setLanguage(tmptok)) {
2630 // Language tmptok was not found
2631 language = default_language;
2632 lyxerr << "Warning: Setting language `"
2633 << tmptok << "' to `" << language->lang()
2639 void BufferParams::readGraphicsDriver(Lexer & lex)
2644 string const tmptok = lex.getString();
2645 // check if tmptok is part of tex_graphics in tex_defs.h
2648 string const test = tex_graphics[n++];
2650 if (test == tmptok) {
2651 graphics_driver = tmptok;
2656 "Warning: graphics driver `$$Token' not recognized!\n"
2657 " Setting graphics driver to `default'.\n");
2658 graphics_driver = "default";
2665 void BufferParams::readBullets(Lexer & lex)
2670 int const index = lex.getInteger();
2672 int temp_int = lex.getInteger();
2673 user_defined_bullet(index).setFont(temp_int);
2674 temp_bullet(index).setFont(temp_int);
2676 user_defined_bullet(index).setCharacter(temp_int);
2677 temp_bullet(index).setCharacter(temp_int);
2679 user_defined_bullet(index).setSize(temp_int);
2680 temp_bullet(index).setSize(temp_int);
2684 void BufferParams::readBulletsLaTeX(Lexer & lex)
2686 // The bullet class should be able to read this.
2689 int const index = lex.getInteger();
2691 docstring const temp_str = lex.getDocString();
2693 user_defined_bullet(index).setText(temp_str);
2694 temp_bullet(index).setText(temp_str);
2698 void BufferParams::readModules(Lexer & lex)
2700 if (!lex.eatLine()) {
2701 lyxerr << "Error (BufferParams::readModules):"
2702 "Unexpected end of input." << endl;
2706 string mod = lex.getString();
2707 if (mod == "\\end_modules")
2709 addLayoutModule(mod);
2715 void BufferParams::readRemovedModules(Lexer & lex)
2717 if (!lex.eatLine()) {
2718 lyxerr << "Error (BufferParams::readRemovedModules):"
2719 "Unexpected end of input." << endl;
2723 string mod = lex.getString();
2724 if (mod == "\\end_removed_modules")
2726 removed_modules_.push_back(mod);
2729 // now we want to remove any removed modules that were previously
2730 // added. normally, that will be because default modules were added in
2731 // setBaseClass(), which gets called when \textclass is read at the
2732 // start of the read.
2733 list<string>::const_iterator rit = removed_modules_.begin();
2734 list<string>::const_iterator const ren = removed_modules_.end();
2735 for (; rit != ren; ++rit) {
2736 LayoutModuleList::iterator const mit = layout_modules_.begin();
2737 LayoutModuleList::iterator const men = layout_modules_.end();
2738 LayoutModuleList::iterator found = find(mit, men, *rit);
2741 layout_modules_.erase(found);
2746 void BufferParams::readIncludeonly(Lexer & lex)
2748 if (!lex.eatLine()) {
2749 lyxerr << "Error (BufferParams::readIncludeonly):"
2750 "Unexpected end of input." << endl;
2754 string child = lex.getString();
2755 if (child == "\\end_includeonly")
2757 included_children_.push_back(child);
2763 string BufferParams::paperSizeName(PapersizePurpose purpose) const
2765 switch (papersize) {
2767 // could be anything, so don't guess
2769 case PAPER_CUSTOM: {
2770 if (purpose == XDVI && !paperwidth.empty() &&
2771 !paperheight.empty()) {
2772 // heightxwidth<unit>
2773 string first = paperwidth;
2774 string second = paperheight;
2775 if (orientation == ORIENTATION_LANDSCAPE)
2778 return first.erase(first.length() - 2)
2784 // dvips and dvipdfm do not know this
2785 if (purpose == DVIPS || purpose == DVIPDFM)
2789 if (purpose == DVIPS || purpose == DVIPDFM)
2793 if (purpose == DVIPS || purpose == DVIPDFM)
2803 if (purpose == DVIPS || purpose == DVIPDFM)
2807 if (purpose == DVIPS || purpose == DVIPDFM)
2811 if (purpose == DVIPS || purpose == DVIPDFM)
2815 if (purpose == DVIPS || purpose == DVIPDFM)
2819 if (purpose == DVIPS || purpose == DVIPDFM)
2823 // dvipdfm does not know this
2824 if (purpose == DVIPDFM)
2828 if (purpose == DVIPDFM)
2832 if (purpose == DVIPS || purpose == DVIPDFM)
2836 if (purpose == DVIPS || purpose == DVIPDFM)
2840 if (purpose == DVIPS || purpose == DVIPDFM)
2844 if (purpose == DVIPS || purpose == DVIPDFM)
2848 if (purpose == DVIPS || purpose == DVIPDFM)
2852 if (purpose == DVIPS || purpose == DVIPDFM)
2856 if (purpose == DVIPS || purpose == DVIPDFM)
2860 if (purpose == DVIPS || purpose == DVIPDFM)
2864 if (purpose == DVIPS || purpose == DVIPDFM)
2868 if (purpose == DVIPS || purpose == DVIPDFM)
2872 if (purpose == DVIPS || purpose == DVIPDFM)
2876 if (purpose == DVIPS || purpose == DVIPDFM)
2880 if (purpose == DVIPS || purpose == DVIPDFM)
2884 if (purpose == DVIPS || purpose == DVIPDFM)
2888 if (purpose == DVIPS || purpose == DVIPDFM)
2891 case PAPER_USEXECUTIVE:
2892 // dvipdfm does not know this
2893 if (purpose == DVIPDFM)
2898 case PAPER_USLETTER:
2900 if (purpose == XDVI)
2907 string const BufferParams::dvips_options() const
2911 // If the class loads the geometry package, we do not know which
2912 // paper size is used, since we do not set it (bug 7013).
2913 // Therefore we must not specify any argument here.
2914 // dvips gets the correct paper size via DVI specials in this case
2915 // (if the class uses the geometry package correctly).
2916 if (documentClass().provides("geometry"))
2920 && papersize == PAPER_CUSTOM
2921 && !lyxrc.print_paper_dimension_flag.empty()
2922 && !paperwidth.empty()
2923 && !paperheight.empty()) {
2924 // using a custom papersize
2925 result = lyxrc.print_paper_dimension_flag;
2926 result += ' ' + paperwidth;
2927 result += ',' + paperheight;
2929 string const paper_option = paperSizeName(DVIPS);
2930 if (!paper_option.empty() && (paper_option != "letter" ||
2931 orientation != ORIENTATION_LANDSCAPE)) {
2932 // dvips won't accept -t letter -t landscape.
2933 // In all other cases, include the paper size
2935 result = lyxrc.print_paper_flag;
2936 result += ' ' + paper_option;
2939 if (orientation == ORIENTATION_LANDSCAPE &&
2940 papersize != PAPER_CUSTOM)
2941 result += ' ' + lyxrc.print_landscape_flag;
2946 string const BufferParams::font_encoding() const
2948 return font_encodings().empty() ? "default" : font_encodings().back();
2952 vector<string> const BufferParams::font_encodings() const
2954 string doc_fontenc = (fontenc == "global") ? lyxrc.fontenc : fontenc;
2956 vector<string> fontencs;
2958 // "default" means "no explicit font encoding"
2959 if (doc_fontenc != "default") {
2960 fontencs = getVectorFromString(doc_fontenc);
2961 if (!language->fontenc().empty()
2962 && ascii_lowercase(language->fontenc()) != "none") {
2963 vector<string> fencs = getVectorFromString(language->fontenc());
2964 vector<string>::const_iterator fit = fencs.begin();
2965 for (; fit != fencs.end(); ++fit) {
2966 if (find(fontencs.begin(), fontencs.end(), *fit) == fontencs.end())
2967 fontencs.push_back(*fit);
2976 string BufferParams::babelCall(string const & lang_opts, bool const langoptions) const
2978 // suppress the babel call if there is no BabelName defined
2979 // for the document language in the lib/languages file and if no
2980 // other languages are used (lang_opts is then empty)
2981 if (lang_opts.empty())
2983 // either a specific language (AsBabelOptions setting in
2984 // lib/languages) or the prefs require the languages to
2985 // be submitted to babel itself (not the class).
2987 return "\\usepackage[" + lang_opts + "]{babel}";
2988 return "\\usepackage{babel}";
2992 docstring BufferParams::getGraphicsDriver(string const & package) const
2996 if (package == "geometry") {
2997 if (graphics_driver == "dvips"
2998 || graphics_driver == "dvipdfm"
2999 || graphics_driver == "pdftex"
3000 || graphics_driver == "vtex")
3001 result = from_ascii(graphics_driver);
3002 else if (graphics_driver == "dvipdfmx")
3003 result = from_ascii("dvipdfm");
3010 void BufferParams::writeEncodingPreamble(otexstream & os,
3011 LaTeXFeatures & features) const
3013 // XeTeX/LuaTeX: (see also #9740)
3014 // With Unicode fonts we use utf8-plain without encoding package.
3015 // With TeX fonts, we cannot use utf8-plain, but "inputenc" fails.
3016 // XeTeX must use ASCII encoding (see Buffer.cpp),
3017 // for LuaTeX, we load "luainputenc" (see below).
3018 if (useNonTeXFonts || features.runparams().flavor == OutputParams::XETEX)
3021 if (inputenc == "auto") {
3022 string const doc_encoding =
3023 language->encoding()->latexName();
3024 Encoding::Package const package =
3025 language->encoding()->package();
3027 // Create list of inputenc options:
3028 set<string> encodings;
3029 // luainputenc fails with more than one encoding
3030 if (!features.runparams().isFullUnicode()) // if we reach this point, this means LuaTeX with TeX fonts
3031 // list all input encodings used in the document
3032 encodings = features.getEncodingSet(doc_encoding);
3034 // If the "japanese" package (i.e. pLaTeX) is used,
3035 // inputenc must be omitted.
3036 // see http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg129680.html
3037 if ((!encodings.empty() || package == Encoding::inputenc)
3038 && !features.isRequired("japanese")
3039 && !features.isProvided("inputenc")) {
3040 os << "\\usepackage[";
3041 set<string>::const_iterator it = encodings.begin();
3042 set<string>::const_iterator const end = encodings.end();
3044 os << from_ascii(*it);
3047 for (; it != end; ++it)
3048 os << ',' << from_ascii(*it);
3049 if (package == Encoding::inputenc) {
3050 if (!encodings.empty())
3052 os << from_ascii(doc_encoding);
3054 if (features.runparams().flavor == OutputParams::LUATEX
3055 || features.runparams().flavor == OutputParams::DVILUATEX)
3056 os << "]{luainputenc}\n";
3058 os << "]{inputenc}\n";
3060 if (package == Encoding::CJK || features.mustProvide("CJK")) {
3061 if (language->encoding()->name() == "utf8-cjk"
3062 && LaTeXFeatures::isAvailable("CJKutf8"))
3063 os << "\\usepackage{CJKutf8}\n";
3065 os << "\\usepackage{CJK}\n";
3067 } else if (inputenc != "default") {
3068 switch (encoding().package()) {
3069 case Encoding::none:
3070 case Encoding::japanese:
3072 case Encoding::inputenc:
3073 // do not load inputenc if japanese is used
3074 // or if the class provides inputenc
3075 if (features.isRequired("japanese")
3076 || features.isProvided("inputenc"))
3078 os << "\\usepackage[" << from_ascii(encoding().latexName());
3079 if (features.runparams().flavor == OutputParams::LUATEX
3080 || features.runparams().flavor == OutputParams::DVILUATEX)
3081 os << "]{luainputenc}\n";
3083 os << "]{inputenc}\n";
3086 if (encoding().name() == "utf8-cjk"
3087 && LaTeXFeatures::isAvailable("CJKutf8"))
3088 os << "\\usepackage{CJKutf8}\n";
3090 os << "\\usepackage{CJK}\n";
3093 // Load the CJK package if needed by a secondary language.
3094 // If the main encoding is some variant of UTF8, use CJKutf8.
3095 if (encoding().package() != Encoding::CJK && features.mustProvide("CJK")) {
3096 if (encoding().iconvName() == "UTF-8"
3097 && LaTeXFeatures::isAvailable("CJKutf8"))
3098 os << "\\usepackage{CJKutf8}\n";
3100 os << "\\usepackage{CJK}\n";
3106 string const BufferParams::parseFontName(string const & name) const
3108 string mangled = name;
3109 size_t const idx = mangled.find('[');
3110 if (idx == string::npos || idx == 0)
3113 return mangled.substr(0, idx - 1);
3117 string const BufferParams::loadFonts(LaTeXFeatures & features) const
3119 if (fontsRoman() == "default" && fontsSans() == "default"
3120 && fontsTypewriter() == "default"
3121 && (fontsMath() == "default" || fontsMath() == "auto"))
3127 /* Fontspec (XeTeX, LuaTeX): we provide GUI support for oldstyle
3128 * numbers (Numbers=OldStyle) and sf/tt scaling. The Ligatures=TeX/
3129 * Mapping=tex-text option assures TeX ligatures (such as "--")
3130 * are resolved. Note that tt does not use these ligatures.
3132 * -- add more GUI options?
3133 * -- add more fonts (fonts for other scripts)
3134 * -- if there's a way to find out if a font really supports
3135 * OldStyle, enable/disable the widget accordingly.
3137 if (useNonTeXFonts && features.isAvailable("fontspec")) {
3138 // "Mapping=tex-text" and "Ligatures=TeX" are equivalent.
3139 // However, until v.2 (2010/07/11) fontspec only knew
3140 // Mapping=tex-text (for XeTeX only); then "Ligatures=TeX"
3141 // was introduced for both XeTeX and LuaTeX (LuaTeX
3142 // didn't understand "Mapping=tex-text", while XeTeX
3143 // understood both. With most recent versions, both
3144 // variants are understood by both engines. However,
3145 // we want to provide support for at least TeXLive 2009
3146 // (for XeTeX; LuaTeX is only supported as of v.2)
3147 string const texmapping =
3148 (features.runparams().flavor == OutputParams::XETEX) ?
3149 "Mapping=tex-text" : "Ligatures=TeX";
3150 if (fontsRoman() != "default") {
3151 os << "\\setmainfont[" << texmapping;
3152 if (fonts_old_figures)
3153 os << ",Numbers=OldStyle";
3154 os << "]{" << parseFontName(fontsRoman()) << "}\n";
3156 if (fontsSans() != "default") {
3157 string const sans = parseFontName(fontsSans());
3158 if (fontsSansScale() != 100)
3159 os << "\\setsansfont[Scale="
3160 << float(fontsSansScale()) / 100
3161 << "," << texmapping << "]{"
3164 os << "\\setsansfont[" << texmapping << "]{"
3167 if (fontsTypewriter() != "default") {
3168 string const mono = parseFontName(fontsTypewriter());
3169 if (fontsTypewriterScale() != 100)
3170 os << "\\setmonofont[Scale="
3171 << float(fontsTypewriterScale()) / 100
3175 os << "\\setmonofont{"
3182 bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
3183 bool const dryrun = features.runparams().dryrun;
3184 bool const complete = (fontsSans() == "default" && fontsTypewriter() == "default");
3185 bool const nomath = (fontsMath() == "default");
3188 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsRoman())).getLaTeXCode(
3189 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3193 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsSans())).getLaTeXCode(
3194 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3195 nomath, fontsSansScale());
3197 // MONOSPACED/TYPEWRITER
3198 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsTypewriter())).getLaTeXCode(
3199 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3200 nomath, fontsTypewriterScale());
3203 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getLaTeXCode(
3204 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3211 Encoding const & BufferParams::encoding() const
3213 // Main encoding for LaTeX output.
3215 // Exception: XeTeX with 8-bit TeX fonts requires ASCII (see #9740).
3216 // As the "flavor" is only known once export started, this
3217 // cannot be handled here. Instead, runparams.encoding is set
3218 // to ASCII in Buffer::makeLaTeXFile (for export)
3219 // and Buffer::writeLaTeXSource (for preview).
3221 return *(encodings.fromLyXName("utf8-plain"));
3222 if (inputenc == "auto" || inputenc == "default")
3223 return *language->encoding();
3224 Encoding const * const enc = encodings.fromLyXName(inputenc);
3227 LYXERR0("Unknown inputenc value `" << inputenc
3228 << "'. Using `auto' instead.");
3229 return *language->encoding();
3233 bool BufferParams::addCiteEngine(string const & engine)
3235 LayoutModuleList::const_iterator it = cite_engine_.begin();
3236 LayoutModuleList::const_iterator en = cite_engine_.end();
3237 for (; it != en; ++it)
3240 cite_engine_.push_back(engine);
3245 bool BufferParams::addCiteEngine(vector<string> const & engine)
3247 vector<string>::const_iterator it = engine.begin();
3248 vector<string>::const_iterator en = engine.end();
3250 for (; it != en; ++it)
3251 if (!addCiteEngine(*it))
3257 string const & BufferParams::defaultBiblioStyle() const
3259 return documentClass().defaultBiblioStyle();
3263 bool const & BufferParams::fullAuthorList() const
3265 return documentClass().fullAuthorList();
3269 void BufferParams::setCiteEngine(string const & engine)
3272 addCiteEngine(engine);
3276 void BufferParams::setCiteEngine(vector<string> const & engine)
3279 addCiteEngine(engine);
3283 vector<string> BufferParams::citeCommands() const
3285 static CitationStyle const default_style;
3286 vector<string> commands =
3287 documentClass().citeCommands(citeEngineType());
3288 if (commands.empty())
3289 commands.push_back(default_style.cmd);
3294 vector<CitationStyle> BufferParams::citeStyles() const
3296 static CitationStyle const default_style;
3297 vector<CitationStyle> styles =
3298 documentClass().citeStyles(citeEngineType());
3300 styles.push_back(default_style);
3304 void BufferParams::invalidateConverterCache() const
3306 pimpl_->isExportCacheValid = false;
3307 pimpl_->isViewCacheValid = false;