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_style[] = {
75 "english", "swedish", "german", "polish", "french", "danish", "plain", ""
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::QuoteStyle> QuotesStyleTranslator;
134 QuotesStyleTranslator const init_quotesstyletranslator()
136 QuotesStyleTranslator translator
137 (string_quotes_style[0], InsetQuotes::EnglishQuotes);
138 translator.addPair(string_quotes_style[1], InsetQuotes::SwedishQuotes);
139 translator.addPair(string_quotes_style[2], InsetQuotes::GermanQuotes);
140 translator.addPair(string_quotes_style[3], InsetQuotes::PolishQuotes);
141 translator.addPair(string_quotes_style[4], InsetQuotes::FrenchQuotes);
142 translator.addPair(string_quotes_style[5], InsetQuotes::DanishQuotes);
143 translator.addPair(string_quotes_style[6], InsetQuotes::PlainQuotes);
148 QuotesStyleTranslator const & quotesstyletranslator()
150 static QuotesStyleTranslator const translator =
151 init_quotesstyletranslator();
157 typedef Translator<string, PAPER_SIZE> PaperSizeTranslator;
160 static PaperSizeTranslator initPaperSizeTranslator()
162 PaperSizeTranslator translator(string_papersize[0], PAPER_DEFAULT);
163 translator.addPair(string_papersize[1], PAPER_CUSTOM);
164 translator.addPair(string_papersize[2], PAPER_USLETTER);
165 translator.addPair(string_papersize[3], PAPER_USLEGAL);
166 translator.addPair(string_papersize[4], PAPER_USEXECUTIVE);
167 translator.addPair(string_papersize[5], PAPER_A0);
168 translator.addPair(string_papersize[6], PAPER_A1);
169 translator.addPair(string_papersize[7], PAPER_A2);
170 translator.addPair(string_papersize[8], PAPER_A3);
171 translator.addPair(string_papersize[9], PAPER_A4);
172 translator.addPair(string_papersize[10], PAPER_A5);
173 translator.addPair(string_papersize[11], PAPER_A6);
174 translator.addPair(string_papersize[12], PAPER_B0);
175 translator.addPair(string_papersize[13], PAPER_B1);
176 translator.addPair(string_papersize[14], PAPER_B2);
177 translator.addPair(string_papersize[15], PAPER_B3);
178 translator.addPair(string_papersize[16], PAPER_B4);
179 translator.addPair(string_papersize[17], PAPER_B5);
180 translator.addPair(string_papersize[18], PAPER_B6);
181 translator.addPair(string_papersize[19], PAPER_C0);
182 translator.addPair(string_papersize[20], PAPER_C1);
183 translator.addPair(string_papersize[21], PAPER_C2);
184 translator.addPair(string_papersize[22], PAPER_C3);
185 translator.addPair(string_papersize[23], PAPER_C4);
186 translator.addPair(string_papersize[24], PAPER_C5);
187 translator.addPair(string_papersize[25], PAPER_C6);
188 translator.addPair(string_papersize[26], PAPER_JISB0);
189 translator.addPair(string_papersize[27], PAPER_JISB1);
190 translator.addPair(string_papersize[28], PAPER_JISB2);
191 translator.addPair(string_papersize[29], PAPER_JISB3);
192 translator.addPair(string_papersize[30], PAPER_JISB4);
193 translator.addPair(string_papersize[31], PAPER_JISB5);
194 translator.addPair(string_papersize[32], PAPER_JISB6);
199 PaperSizeTranslator const & papersizetranslator()
201 static PaperSizeTranslator const translator =
202 initPaperSizeTranslator();
208 typedef Translator<string, PAPER_ORIENTATION> PaperOrientationTranslator;
211 PaperOrientationTranslator const init_paperorientationtranslator()
213 PaperOrientationTranslator translator(string_orientation[0], ORIENTATION_PORTRAIT);
214 translator.addPair(string_orientation[1], ORIENTATION_LANDSCAPE);
219 PaperOrientationTranslator const & paperorientationtranslator()
221 static PaperOrientationTranslator const translator =
222 init_paperorientationtranslator();
228 typedef Translator<int, PageSides> SidesTranslator;
231 SidesTranslator const init_sidestranslator()
233 SidesTranslator translator(1, OneSide);
234 translator.addPair(2, TwoSides);
239 SidesTranslator const & sidestranslator()
241 static SidesTranslator const translator = init_sidestranslator();
247 typedef Translator<int, BufferParams::Package> PackageTranslator;
250 PackageTranslator const init_packagetranslator()
252 PackageTranslator translator(0, BufferParams::package_off);
253 translator.addPair(1, BufferParams::package_auto);
254 translator.addPair(2, BufferParams::package_on);
259 PackageTranslator const & packagetranslator()
261 static PackageTranslator const translator =
262 init_packagetranslator();
268 typedef Translator<string, CiteEngineType> CiteEngineTypeTranslator;
271 CiteEngineTypeTranslator const init_citeenginetypetranslator()
273 CiteEngineTypeTranslator translator("authoryear", ENGINE_TYPE_AUTHORYEAR);
274 translator.addPair("numerical", ENGINE_TYPE_NUMERICAL);
275 translator.addPair("default", ENGINE_TYPE_DEFAULT);
280 CiteEngineTypeTranslator const & citeenginetypetranslator()
282 static CiteEngineTypeTranslator const translator =
283 init_citeenginetypetranslator();
289 typedef Translator<string, Spacing::Space> SpaceTranslator;
292 SpaceTranslator const init_spacetranslator()
294 SpaceTranslator translator("default", Spacing::Default);
295 translator.addPair("single", Spacing::Single);
296 translator.addPair("onehalf", Spacing::Onehalf);
297 translator.addPair("double", Spacing::Double);
298 translator.addPair("other", Spacing::Other);
303 SpaceTranslator const & spacetranslator()
305 static SpaceTranslator const translator = init_spacetranslator();
310 bool inSystemDir(FileName const & document_dir, string & system_dir)
312 // A document is assumed to be in a system LyX directory (not
313 // necessarily the system directory of the running instance)
314 // if both "configure.py" and "chkconfig.ltx" are found in
315 // either document_dir/../ or document_dir/../../.
316 // If true, the system directory path is returned in system_dir
317 // with a trailing path separator.
319 string const msg = "Checking whether document is in a system dir...";
321 string dir = document_dir.absFileName();
323 for (int i = 0; i < 2; ++i) {
324 dir = addPath(dir, "..");
325 if (!fileSearch(dir, "configure.py").empty() &&
326 !fileSearch(dir, "chkconfig.ltx").empty()) {
327 LYXERR(Debug::FILES, msg << " yes");
328 system_dir = addPath(FileName(dir).realPath(), "");
333 LYXERR(Debug::FILES, msg << " no");
334 system_dir = string();
341 class BufferParams::Impl
346 AuthorList authorlist;
347 BranchList branchlist;
348 Bullet temp_bullets[4];
349 Bullet user_defined_bullets[4];
350 IndicesList indiceslist;
352 /** This is the amount of space used for paragraph_separation "skip",
353 * and for detached paragraphs in "indented" documents.
357 PDFOptions pdfoptions;
358 LayoutFileIndex baseClass_;
359 FormatList exportableFormatList;
360 FormatList 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_style = 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_style") {
835 quotes_style = quotesstyletranslator().find(qstyle);
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_style "
1304 << string_quotes_style[quotes_style]
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 set<string> const polylangs =
2187 features.getPolyglossiaLanguages();
2188 for (set<string>::const_iterator mit = polylangs.begin();
2189 mit != polylangs.end() ; ++mit) {
2190 // We do not output the options here; they are output in
2191 // the language switch commands. This is safer if multiple
2192 // varieties are used.
2193 if (*mit == language->polyglossia())
2195 os << "\\setotherlanguage";
2196 os << "{" << from_ascii(*mit) << "}\n";
2200 // Load custom language package here
2201 if (features.langPackage() == LaTeXFeatures::LANG_PACK_CUSTOM) {
2202 if (lang_package == "default")
2203 os << from_utf8(lyxrc.language_custom_package);
2205 os << from_utf8(lang_package);
2209 docstring const i18npreamble =
2210 features.getTClassI18nPreamble(use_babel, use_polyglossia);
2211 if (!i18npreamble.empty())
2212 os << i18npreamble + '\n';
2218 void BufferParams::useClassDefaults()
2220 DocumentClass const & tclass = documentClass();
2222 sides = tclass.sides();
2223 columns = tclass.columns();
2224 pagestyle = tclass.pagestyle();
2225 use_default_options = true;
2226 // Only if class has a ToC hierarchy
2227 if (tclass.hasTocLevels()) {
2228 secnumdepth = tclass.secnumdepth();
2229 tocdepth = tclass.tocdepth();
2234 bool BufferParams::hasClassDefaults() const
2236 DocumentClass const & tclass = documentClass();
2238 return sides == tclass.sides()
2239 && columns == tclass.columns()
2240 && pagestyle == tclass.pagestyle()
2241 && use_default_options
2242 && secnumdepth == tclass.secnumdepth()
2243 && tocdepth == tclass.tocdepth();
2247 DocumentClass const & BufferParams::documentClass() const
2253 DocumentClassConstPtr BufferParams::documentClassPtr() const
2259 void BufferParams::setDocumentClass(DocumentClassConstPtr tc)
2261 // evil, but this function is evil
2262 doc_class_ = const_pointer_cast<DocumentClass>(tc);
2263 invalidateConverterCache();
2267 bool BufferParams::setBaseClass(string const & classname)
2269 LYXERR(Debug::TCLASS, "setBaseClass: " << classname);
2270 LayoutFileList & bcl = LayoutFileList::get();
2271 if (!bcl.haveClass(classname)) {
2273 bformat(_("The layout file:\n"
2275 "could not be found. A default textclass with default\n"
2276 "layouts will be used. LyX will not be able to produce\n"
2278 from_utf8(classname));
2279 frontend::Alert::error(_("Document class not found"), s);
2280 bcl.addEmptyClass(classname);
2283 bool const success = bcl[classname].load();
2286 bformat(_("Due to some error in it, the layout file:\n"
2288 "could not be loaded. A default textclass with default\n"
2289 "layouts will be used. LyX will not be able to produce\n"
2291 from_utf8(classname));
2292 frontend::Alert::error(_("Could not load class"), s);
2293 bcl.addEmptyClass(classname);
2296 pimpl_->baseClass_ = classname;
2297 layout_modules_.adaptToBaseClass(baseClass(), removed_modules_);
2302 LayoutFile const * BufferParams::baseClass() const
2304 if (LayoutFileList::get().haveClass(pimpl_->baseClass_))
2305 return &(LayoutFileList::get()[pimpl_->baseClass_]);
2311 LayoutFileIndex const & BufferParams::baseClassID() const
2313 return pimpl_->baseClass_;
2317 void BufferParams::makeDocumentClass(bool const clone)
2322 invalidateConverterCache();
2323 LayoutModuleList mods;
2324 LayoutModuleList::iterator it = layout_modules_.begin();
2325 LayoutModuleList::iterator en = layout_modules_.end();
2326 for (; it != en; ++it)
2327 mods.push_back(*it);
2329 it = cite_engine_.begin();
2330 en = cite_engine_.end();
2331 for (; it != en; ++it)
2332 mods.push_back(*it);
2334 doc_class_ = getDocumentClass(*baseClass(), mods, clone);
2336 TextClass::ReturnValues success = TextClass::OK;
2337 if (!forced_local_layout_.empty())
2338 success = doc_class_->read(to_utf8(forced_local_layout_),
2340 if (!local_layout_.empty() &&
2341 (success == TextClass::OK || success == TextClass::OK_OLDFORMAT))
2342 success = doc_class_->read(to_utf8(local_layout_), TextClass::MODULE);
2343 if (success != TextClass::OK && success != TextClass::OK_OLDFORMAT) {
2344 docstring const msg = _("Error reading internal layout information");
2345 frontend::Alert::warning(_("Read Error"), msg);
2350 bool BufferParams::layoutModuleCanBeAdded(string const & modName) const
2352 return layout_modules_.moduleCanBeAdded(modName, baseClass());
2356 bool BufferParams::citationModuleCanBeAdded(string const & modName) const
2358 return cite_engine_.moduleCanBeAdded(modName, baseClass());
2362 docstring BufferParams::getLocalLayout(bool forced) const
2365 return from_utf8(doc_class_->forcedLayouts());
2367 return local_layout_;
2371 void BufferParams::setLocalLayout(docstring const & layout, bool forced)
2374 forced_local_layout_ = layout;
2376 local_layout_ = layout;
2380 bool BufferParams::addLayoutModule(string const & modName)
2382 LayoutModuleList::const_iterator it = layout_modules_.begin();
2383 LayoutModuleList::const_iterator end = layout_modules_.end();
2384 for (; it != end; ++it)
2387 layout_modules_.push_back(modName);
2392 string BufferParams::bufferFormat() const
2394 return documentClass().outputFormat();
2398 bool BufferParams::isExportable(string const & format, bool need_viewable) const
2400 FormatList const & formats = exportableFormats(need_viewable);
2401 FormatList::const_iterator fit = formats.begin();
2402 FormatList::const_iterator end = formats.end();
2403 for (; fit != end ; ++fit) {
2404 if ((*fit)->name() == format)
2411 FormatList const & BufferParams::exportableFormats(bool only_viewable) const
2413 FormatList & cached = only_viewable ?
2414 pimpl_->viewableFormatList : pimpl_->exportableFormatList;
2415 bool & valid = only_viewable ?
2416 pimpl_->isViewCacheValid : pimpl_->isExportCacheValid;
2420 vector<string> const backs = backends();
2421 set<string> excludes;
2422 if (useNonTeXFonts) {
2423 excludes.insert("latex");
2424 excludes.insert("pdflatex");
2427 theConverters().getReachable(backs[0], only_viewable, true, excludes);
2428 for (vector<string>::const_iterator it = backs.begin() + 1;
2429 it != backs.end(); ++it) {
2430 FormatList r = theConverters().getReachable(*it, only_viewable,
2432 result.insert(result.end(), r.begin(), r.end());
2434 sort(result.begin(), result.end(), Format::formatSorter);
2441 vector<string> BufferParams::backends() const
2444 string const buffmt = bufferFormat();
2446 // FIXME: Don't hardcode format names here, but use a flag
2447 if (buffmt == "latex") {
2448 if (encoding().package() == Encoding::japanese)
2449 v.push_back("platex");
2451 if (!useNonTeXFonts) {
2452 v.push_back("pdflatex");
2453 v.push_back("latex");
2455 v.push_back("xetex");
2456 v.push_back("luatex");
2457 v.push_back("dviluatex");
2460 v.push_back(buffmt);
2462 v.push_back("xhtml");
2463 v.push_back("text");
2469 OutputParams::FLAVOR BufferParams::getOutputFlavor(string const & format) const
2471 string const dformat = (format.empty() || format == "default") ?
2472 getDefaultOutputFormat() : format;
2473 DefaultFlavorCache::const_iterator it =
2474 default_flavors_.find(dformat);
2476 if (it != default_flavors_.end())
2479 OutputParams::FLAVOR result = OutputParams::LATEX;
2481 // FIXME It'd be better not to hardcode this, but to do
2482 // something with formats.
2483 if (dformat == "xhtml")
2484 result = OutputParams::HTML;
2485 else if (dformat == "text")
2486 result = OutputParams::TEXT;
2487 else if (dformat == "lyx")
2488 result = OutputParams::LYX;
2489 else if (dformat == "pdflatex")
2490 result = OutputParams::PDFLATEX;
2491 else if (dformat == "xetex")
2492 result = OutputParams::XETEX;
2493 else if (dformat == "luatex")
2494 result = OutputParams::LUATEX;
2495 else if (dformat == "dviluatex")
2496 result = OutputParams::DVILUATEX;
2498 // Try to determine flavor of default output format
2499 vector<string> backs = backends();
2500 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
2501 // Get shortest path to format
2502 Graph::EdgePath path;
2503 for (vector<string>::const_iterator it = backs.begin();
2504 it != backs.end(); ++it) {
2505 Graph::EdgePath p = theConverters().getPath(*it, dformat);
2506 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2511 result = theConverters().getFlavor(path);
2514 // cache this flavor
2515 default_flavors_[dformat] = result;
2520 string BufferParams::getDefaultOutputFormat() const
2522 if (!default_output_format.empty()
2523 && default_output_format != "default")
2524 return default_output_format;
2526 || encoding().package() == Encoding::japanese) {
2527 FormatList const & formats = exportableFormats(true);
2528 if (formats.empty())
2530 // return the first we find
2531 return formats.front()->name();
2534 return lyxrc.default_otf_view_format;
2535 return lyxrc.default_view_format;
2538 Font const BufferParams::getFont() const
2540 FontInfo f = documentClass().defaultfont();
2541 if (fonts_default_family == "rmdefault")
2542 f.setFamily(ROMAN_FAMILY);
2543 else if (fonts_default_family == "sfdefault")
2544 f.setFamily(SANS_FAMILY);
2545 else if (fonts_default_family == "ttdefault")
2546 f.setFamily(TYPEWRITER_FAMILY);
2547 return Font(f, language);
2551 InsetQuotes::QuoteStyle BufferParams::getQuoteStyle(string const & qs) const
2553 return quotesstyletranslator().find(qs);
2557 bool BufferParams::isLatex() const
2559 return documentClass().outputType() == LATEX;
2563 bool BufferParams::isLiterate() const
2565 return documentClass().outputType() == LITERATE;
2569 bool BufferParams::isDocBook() const
2571 return documentClass().outputType() == DOCBOOK;
2575 void BufferParams::readPreamble(Lexer & lex)
2577 if (lex.getString() != "\\begin_preamble")
2578 lyxerr << "Error (BufferParams::readPreamble):"
2579 "consistency check failed." << endl;
2581 preamble = lex.getLongString(from_ascii("\\end_preamble"));
2585 void BufferParams::readLocalLayout(Lexer & lex, bool forced)
2587 string const expected = forced ? "\\begin_forced_local_layout" :
2588 "\\begin_local_layout";
2589 if (lex.getString() != expected)
2590 lyxerr << "Error (BufferParams::readLocalLayout):"
2591 "consistency check failed." << endl;
2594 forced_local_layout_ =
2595 lex.getLongString(from_ascii("\\end_forced_local_layout"));
2597 local_layout_ = lex.getLongString(from_ascii("\\end_local_layout"));
2601 bool BufferParams::setLanguage(string const & lang)
2603 Language const *new_language = languages.getLanguage(lang);
2604 if (!new_language) {
2605 // Language lang was not found
2608 language = new_language;
2613 void BufferParams::readLanguage(Lexer & lex)
2615 if (!lex.next()) return;
2617 string const tmptok = lex.getString();
2619 // check if tmptok is part of tex_babel in tex-defs.h
2620 if (!setLanguage(tmptok)) {
2621 // Language tmptok was not found
2622 language = default_language;
2623 lyxerr << "Warning: Setting language `"
2624 << tmptok << "' to `" << language->lang()
2630 void BufferParams::readGraphicsDriver(Lexer & lex)
2635 string const tmptok = lex.getString();
2636 // check if tmptok is part of tex_graphics in tex_defs.h
2639 string const test = tex_graphics[n++];
2641 if (test == tmptok) {
2642 graphics_driver = tmptok;
2647 "Warning: graphics driver `$$Token' not recognized!\n"
2648 " Setting graphics driver to `default'.\n");
2649 graphics_driver = "default";
2656 void BufferParams::readBullets(Lexer & lex)
2661 int const index = lex.getInteger();
2663 int temp_int = lex.getInteger();
2664 user_defined_bullet(index).setFont(temp_int);
2665 temp_bullet(index).setFont(temp_int);
2667 user_defined_bullet(index).setCharacter(temp_int);
2668 temp_bullet(index).setCharacter(temp_int);
2670 user_defined_bullet(index).setSize(temp_int);
2671 temp_bullet(index).setSize(temp_int);
2675 void BufferParams::readBulletsLaTeX(Lexer & lex)
2677 // The bullet class should be able to read this.
2680 int const index = lex.getInteger();
2682 docstring const temp_str = lex.getDocString();
2684 user_defined_bullet(index).setText(temp_str);
2685 temp_bullet(index).setText(temp_str);
2689 void BufferParams::readModules(Lexer & lex)
2691 if (!lex.eatLine()) {
2692 lyxerr << "Error (BufferParams::readModules):"
2693 "Unexpected end of input." << endl;
2697 string mod = lex.getString();
2698 if (mod == "\\end_modules")
2700 addLayoutModule(mod);
2706 void BufferParams::readRemovedModules(Lexer & lex)
2708 if (!lex.eatLine()) {
2709 lyxerr << "Error (BufferParams::readRemovedModules):"
2710 "Unexpected end of input." << endl;
2714 string mod = lex.getString();
2715 if (mod == "\\end_removed_modules")
2717 removed_modules_.push_back(mod);
2720 // now we want to remove any removed modules that were previously
2721 // added. normally, that will be because default modules were added in
2722 // setBaseClass(), which gets called when \textclass is read at the
2723 // start of the read.
2724 list<string>::const_iterator rit = removed_modules_.begin();
2725 list<string>::const_iterator const ren = removed_modules_.end();
2726 for (; rit != ren; ++rit) {
2727 LayoutModuleList::iterator const mit = layout_modules_.begin();
2728 LayoutModuleList::iterator const men = layout_modules_.end();
2729 LayoutModuleList::iterator found = find(mit, men, *rit);
2732 layout_modules_.erase(found);
2737 void BufferParams::readIncludeonly(Lexer & lex)
2739 if (!lex.eatLine()) {
2740 lyxerr << "Error (BufferParams::readIncludeonly):"
2741 "Unexpected end of input." << endl;
2745 string child = lex.getString();
2746 if (child == "\\end_includeonly")
2748 included_children_.push_back(child);
2754 string BufferParams::paperSizeName(PapersizePurpose purpose) const
2756 switch (papersize) {
2758 // could be anything, so don't guess
2760 case PAPER_CUSTOM: {
2761 if (purpose == XDVI && !paperwidth.empty() &&
2762 !paperheight.empty()) {
2763 // heightxwidth<unit>
2764 string first = paperwidth;
2765 string second = paperheight;
2766 if (orientation == ORIENTATION_LANDSCAPE)
2769 return first.erase(first.length() - 2)
2775 // dvips and dvipdfm do not know this
2776 if (purpose == DVIPS || purpose == DVIPDFM)
2780 if (purpose == DVIPS || purpose == DVIPDFM)
2784 if (purpose == DVIPS || purpose == DVIPDFM)
2794 if (purpose == DVIPS || purpose == DVIPDFM)
2798 if (purpose == DVIPS || purpose == DVIPDFM)
2802 if (purpose == DVIPS || purpose == DVIPDFM)
2806 if (purpose == DVIPS || purpose == DVIPDFM)
2810 if (purpose == DVIPS || purpose == DVIPDFM)
2814 // dvipdfm does not know this
2815 if (purpose == DVIPDFM)
2819 if (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)
2875 if (purpose == DVIPS || purpose == DVIPDFM)
2879 if (purpose == DVIPS || purpose == DVIPDFM)
2882 case PAPER_USEXECUTIVE:
2883 // dvipdfm does not know this
2884 if (purpose == DVIPDFM)
2889 case PAPER_USLETTER:
2891 if (purpose == XDVI)
2898 string const BufferParams::dvips_options() const
2902 // If the class loads the geometry package, we do not know which
2903 // paper size is used, since we do not set it (bug 7013).
2904 // Therefore we must not specify any argument here.
2905 // dvips gets the correct paper size via DVI specials in this case
2906 // (if the class uses the geometry package correctly).
2907 if (documentClass().provides("geometry"))
2911 && papersize == PAPER_CUSTOM
2912 && !lyxrc.print_paper_dimension_flag.empty()
2913 && !paperwidth.empty()
2914 && !paperheight.empty()) {
2915 // using a custom papersize
2916 result = lyxrc.print_paper_dimension_flag;
2917 result += ' ' + paperwidth;
2918 result += ',' + paperheight;
2920 string const paper_option = paperSizeName(DVIPS);
2921 if (!paper_option.empty() && (paper_option != "letter" ||
2922 orientation != ORIENTATION_LANDSCAPE)) {
2923 // dvips won't accept -t letter -t landscape.
2924 // In all other cases, include the paper size
2926 result = lyxrc.print_paper_flag;
2927 result += ' ' + paper_option;
2930 if (orientation == ORIENTATION_LANDSCAPE &&
2931 papersize != PAPER_CUSTOM)
2932 result += ' ' + lyxrc.print_landscape_flag;
2937 string const BufferParams::font_encoding() const
2939 return font_encodings().empty() ? "default" : font_encodings().back();
2943 vector<string> const BufferParams::font_encodings() const
2945 string doc_fontenc = (fontenc == "global") ? lyxrc.fontenc : fontenc;
2947 vector<string> fontencs;
2949 // "default" means "no explicit font encoding"
2950 if (doc_fontenc != "default") {
2951 fontencs = getVectorFromString(doc_fontenc);
2952 if (!language->fontenc().empty()
2953 && ascii_lowercase(language->fontenc()) != "none") {
2954 vector<string> fencs = getVectorFromString(language->fontenc());
2955 vector<string>::const_iterator fit = fencs.begin();
2956 for (; fit != fencs.end(); ++fit) {
2957 if (find(fontencs.begin(), fontencs.end(), *fit) == fontencs.end())
2958 fontencs.push_back(*fit);
2967 string BufferParams::babelCall(string const & lang_opts, bool const langoptions) const
2969 // suppress the babel call if there is no BabelName defined
2970 // for the document language in the lib/languages file and if no
2971 // other languages are used (lang_opts is then empty)
2972 if (lang_opts.empty())
2974 // either a specific language (AsBabelOptions setting in
2975 // lib/languages) or the prefs require the languages to
2976 // be submitted to babel itself (not the class).
2978 return "\\usepackage[" + lang_opts + "]{babel}";
2979 return "\\usepackage{babel}";
2983 docstring BufferParams::getGraphicsDriver(string const & package) const
2987 if (package == "geometry") {
2988 if (graphics_driver == "dvips"
2989 || graphics_driver == "dvipdfm"
2990 || graphics_driver == "pdftex"
2991 || graphics_driver == "vtex")
2992 result = from_ascii(graphics_driver);
2993 else if (graphics_driver == "dvipdfmx")
2994 result = from_ascii("dvipdfm");
3001 void BufferParams::writeEncodingPreamble(otexstream & os,
3002 LaTeXFeatures & features) const
3004 // XeTeX/LuaTeX: (see also #9740)
3005 // With Unicode fonts we use utf8-plain without encoding package.
3006 // With TeX fonts, we cannot use utf8-plain, but "inputenc" fails.
3007 // XeTeX must use ASCII encoding (see Buffer.cpp),
3008 // for LuaTeX, we load "luainputenc" (see below).
3009 if (useNonTeXFonts || features.runparams().flavor == OutputParams::XETEX)
3012 if (inputenc == "auto") {
3013 string const doc_encoding =
3014 language->encoding()->latexName();
3015 Encoding::Package const package =
3016 language->encoding()->package();
3018 // Create list of inputenc options:
3019 set<string> encodings;
3020 // luainputenc fails with more than one encoding
3021 if (!features.runparams().isFullUnicode()) // if we reach this point, this means LuaTeX with TeX fonts
3022 // list all input encodings used in the document
3023 encodings = features.getEncodingSet(doc_encoding);
3025 // If the "japanese" package (i.e. pLaTeX) is used,
3026 // inputenc must be omitted.
3027 // see http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg129680.html
3028 if ((!encodings.empty() || package == Encoding::inputenc)
3029 && !features.isRequired("japanese")
3030 && !features.isProvided("inputenc")) {
3031 os << "\\usepackage[";
3032 set<string>::const_iterator it = encodings.begin();
3033 set<string>::const_iterator const end = encodings.end();
3035 os << from_ascii(*it);
3038 for (; it != end; ++it)
3039 os << ',' << from_ascii(*it);
3040 if (package == Encoding::inputenc) {
3041 if (!encodings.empty())
3043 os << from_ascii(doc_encoding);
3045 if (features.runparams().flavor == OutputParams::LUATEX
3046 || features.runparams().flavor == OutputParams::DVILUATEX)
3047 os << "]{luainputenc}\n";
3049 os << "]{inputenc}\n";
3051 if (package == Encoding::CJK || features.mustProvide("CJK")) {
3052 if (language->encoding()->name() == "utf8-cjk"
3053 && LaTeXFeatures::isAvailable("CJKutf8"))
3054 os << "\\usepackage{CJKutf8}\n";
3056 os << "\\usepackage{CJK}\n";
3058 } else if (inputenc != "default") {
3059 switch (encoding().package()) {
3060 case Encoding::none:
3061 case Encoding::japanese:
3063 case Encoding::inputenc:
3064 // do not load inputenc if japanese is used
3065 // or if the class provides inputenc
3066 if (features.isRequired("japanese")
3067 || features.isProvided("inputenc"))
3069 os << "\\usepackage[" << from_ascii(encoding().latexName());
3070 if (features.runparams().flavor == OutputParams::LUATEX
3071 || features.runparams().flavor == OutputParams::DVILUATEX)
3072 os << "]{luainputenc}\n";
3074 os << "]{inputenc}\n";
3077 if (encoding().name() == "utf8-cjk"
3078 && LaTeXFeatures::isAvailable("CJKutf8"))
3079 os << "\\usepackage{CJKutf8}\n";
3081 os << "\\usepackage{CJK}\n";
3084 // Load the CJK package if needed by a secondary language.
3085 // If the main encoding is some variant of UTF8, use CJKutf8.
3086 if (encoding().package() != Encoding::CJK && features.mustProvide("CJK")) {
3087 if (encoding().iconvName() == "UTF-8"
3088 && LaTeXFeatures::isAvailable("CJKutf8"))
3089 os << "\\usepackage{CJKutf8}\n";
3091 os << "\\usepackage{CJK}\n";
3097 string const BufferParams::parseFontName(string const & name) const
3099 string mangled = name;
3100 size_t const idx = mangled.find('[');
3101 if (idx == string::npos || idx == 0)
3104 return mangled.substr(0, idx - 1);
3108 string const BufferParams::loadFonts(LaTeXFeatures & features) const
3110 if (fontsRoman() == "default" && fontsSans() == "default"
3111 && fontsTypewriter() == "default"
3112 && (fontsMath() == "default" || fontsMath() == "auto"))
3118 /* Fontspec (XeTeX, LuaTeX): we provide GUI support for oldstyle
3119 * numbers (Numbers=OldStyle) and sf/tt scaling. The Ligatures=TeX/
3120 * Mapping=tex-text option assures TeX ligatures (such as "--")
3121 * are resolved. Note that tt does not use these ligatures.
3123 * -- add more GUI options?
3124 * -- add more fonts (fonts for other scripts)
3125 * -- if there's a way to find out if a font really supports
3126 * OldStyle, enable/disable the widget accordingly.
3128 if (useNonTeXFonts && features.isAvailable("fontspec")) {
3129 // "Mapping=tex-text" and "Ligatures=TeX" are equivalent.
3130 // However, until v.2 (2010/07/11) fontspec only knew
3131 // Mapping=tex-text (for XeTeX only); then "Ligatures=TeX"
3132 // was introduced for both XeTeX and LuaTeX (LuaTeX
3133 // didn't understand "Mapping=tex-text", while XeTeX
3134 // understood both. With most recent versions, both
3135 // variants are understood by both engines. However,
3136 // we want to provide support for at least TeXLive 2009
3137 // (for XeTeX; LuaTeX is only supported as of v.2)
3138 string const texmapping =
3139 (features.runparams().flavor == OutputParams::XETEX) ?
3140 "Mapping=tex-text" : "Ligatures=TeX";
3141 if (fontsRoman() != "default") {
3142 os << "\\setmainfont[" << texmapping;
3143 if (fonts_old_figures)
3144 os << ",Numbers=OldStyle";
3145 os << "]{" << parseFontName(fontsRoman()) << "}\n";
3147 if (fontsSans() != "default") {
3148 string const sans = parseFontName(fontsSans());
3149 if (fontsSansScale() != 100)
3150 os << "\\setsansfont[Scale="
3151 << float(fontsSansScale()) / 100
3152 << "," << texmapping << "]{"
3155 os << "\\setsansfont[" << texmapping << "]{"
3158 if (fontsTypewriter() != "default") {
3159 string const mono = parseFontName(fontsTypewriter());
3160 if (fontsTypewriterScale() != 100)
3161 os << "\\setmonofont[Scale="
3162 << float(fontsTypewriterScale()) / 100
3166 os << "\\setmonofont{"
3173 bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
3174 bool const dryrun = features.runparams().dryrun;
3175 bool const complete = (fontsSans() == "default" && fontsTypewriter() == "default");
3176 bool const nomath = (fontsMath() == "default");
3179 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsRoman())).getLaTeXCode(
3180 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3184 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsSans())).getLaTeXCode(
3185 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3186 nomath, fontsSansScale());
3188 // MONOSPACED/TYPEWRITER
3189 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsTypewriter())).getLaTeXCode(
3190 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3191 nomath, fontsTypewriterScale());
3194 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getLaTeXCode(
3195 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3202 Encoding const & BufferParams::encoding() const
3204 // Main encoding for LaTeX output.
3206 // Exception: XeTeX with 8-bit TeX fonts requires ASCII (see #9740).
3207 // As the "flavor" is only known once export started, this
3208 // cannot be handled here. Instead, runparams.encoding is set
3209 // to ASCII in Buffer::makeLaTeXFile (for export)
3210 // and Buffer::writeLaTeXSource (for preview).
3212 return *(encodings.fromLyXName("utf8-plain"));
3213 if (inputenc == "auto" || inputenc == "default")
3214 return *language->encoding();
3215 Encoding const * const enc = encodings.fromLyXName(inputenc);
3218 LYXERR0("Unknown inputenc value `" << inputenc
3219 << "'. Using `auto' instead.");
3220 return *language->encoding();
3224 bool BufferParams::addCiteEngine(string const & engine)
3226 LayoutModuleList::const_iterator it = cite_engine_.begin();
3227 LayoutModuleList::const_iterator en = cite_engine_.end();
3228 for (; it != en; ++it)
3231 cite_engine_.push_back(engine);
3236 bool BufferParams::addCiteEngine(vector<string> const & engine)
3238 vector<string>::const_iterator it = engine.begin();
3239 vector<string>::const_iterator en = engine.end();
3241 for (; it != en; ++it)
3242 if (!addCiteEngine(*it))
3248 string const & BufferParams::defaultBiblioStyle() const
3250 return documentClass().defaultBiblioStyle();
3254 bool const & BufferParams::fullAuthorList() const
3256 return documentClass().fullAuthorList();
3260 void BufferParams::setCiteEngine(string const & engine)
3263 addCiteEngine(engine);
3267 void BufferParams::setCiteEngine(vector<string> const & engine)
3270 addCiteEngine(engine);
3274 vector<string> BufferParams::citeCommands() const
3276 static CitationStyle const default_style;
3277 vector<string> commands =
3278 documentClass().citeCommands(citeEngineType());
3279 if (commands.empty())
3280 commands.push_back(default_style.cmd);
3285 vector<CitationStyle> BufferParams::citeStyles() const
3287 static CitationStyle const default_style;
3288 vector<CitationStyle> styles =
3289 documentClass().citeStyles(citeEngineType());
3291 styles.push_back(default_style);
3295 void BufferParams::invalidateConverterCache() const
3297 pimpl_->isExportCacheValid = false;
3298 pimpl_->isViewCacheValid = false;