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());
2435 bool BufferParams::isExportableFormat(string const & format) const
2437 typedef vector<Format const *> Formats;
2438 Formats const & formats = exportableFormats(true);
2439 Formats::const_iterator fit = formats.begin();
2440 Formats::const_iterator end = formats.end();
2441 for (; fit != end ; ++fit) {
2442 if ((*fit)->name() == format)
2449 vector<string> BufferParams::backends() const
2452 string const buffmt = bufferFormat();
2454 // FIXME: Don't hardcode format names here, but use a flag
2455 if (buffmt == "latex") {
2456 if (encoding().package() == Encoding::japanese)
2457 v.push_back("platex");
2459 if (!useNonTeXFonts) {
2460 v.push_back("pdflatex");
2461 v.push_back("latex");
2463 v.push_back("xetex");
2464 v.push_back("luatex");
2465 v.push_back("dviluatex");
2468 v.push_back(buffmt);
2470 v.push_back("xhtml");
2471 v.push_back("text");
2477 OutputParams::FLAVOR BufferParams::getOutputFlavor(string const & format) const
2479 string const dformat = (format.empty() || format == "default") ?
2480 getDefaultOutputFormat() : format;
2481 DefaultFlavorCache::const_iterator it =
2482 default_flavors_.find(dformat);
2484 if (it != default_flavors_.end())
2487 OutputParams::FLAVOR result = OutputParams::LATEX;
2489 // FIXME It'd be better not to hardcode this, but to do
2490 // something with formats.
2491 if (dformat == "xhtml")
2492 result = OutputParams::HTML;
2493 else if (dformat == "text")
2494 result = OutputParams::TEXT;
2495 else if (dformat == "lyx")
2496 result = OutputParams::LYX;
2497 else if (dformat == "pdflatex")
2498 result = OutputParams::PDFLATEX;
2499 else if (dformat == "xetex")
2500 result = OutputParams::XETEX;
2501 else if (dformat == "luatex")
2502 result = OutputParams::LUATEX;
2503 else if (dformat == "dviluatex")
2504 result = OutputParams::DVILUATEX;
2506 // Try to determine flavor of default output format
2507 vector<string> backs = backends();
2508 if (find(backs.begin(), backs.end(), dformat) == backs.end()) {
2509 // Get shortest path to format
2510 Graph::EdgePath path;
2511 for (vector<string>::const_iterator it = backs.begin();
2512 it != backs.end(); ++it) {
2513 Graph::EdgePath p = theConverters().getPath(*it, dformat);
2514 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2519 result = theConverters().getFlavor(path);
2522 // cache this flavor
2523 default_flavors_[dformat] = result;
2528 string BufferParams::getDefaultOutputFormat() const
2530 if (!default_output_format.empty()
2531 && default_output_format != "default")
2532 return default_output_format;
2534 || encoding().package() == Encoding::japanese) {
2535 vector<Format const *> const & formats = exportableFormats(true);
2536 if (formats.empty())
2538 // return the first we find
2539 return formats.front()->name();
2542 return lyxrc.default_otf_view_format;
2543 return lyxrc.default_view_format;
2546 Font const BufferParams::getFont() const
2548 FontInfo f = documentClass().defaultfont();
2549 if (fonts_default_family == "rmdefault")
2550 f.setFamily(ROMAN_FAMILY);
2551 else if (fonts_default_family == "sfdefault")
2552 f.setFamily(SANS_FAMILY);
2553 else if (fonts_default_family == "ttdefault")
2554 f.setFamily(TYPEWRITER_FAMILY);
2555 return Font(f, language);
2559 InsetQuotes::QuoteLanguage BufferParams::getQuoteStyle(string const & qs) const
2561 return quoteslangtranslator().find(qs);
2565 bool BufferParams::isLatex() const
2567 return documentClass().outputType() == LATEX;
2571 bool BufferParams::isLiterate() const
2573 return documentClass().outputType() == LITERATE;
2577 bool BufferParams::isDocBook() const
2579 return documentClass().outputType() == DOCBOOK;
2583 void BufferParams::readPreamble(Lexer & lex)
2585 if (lex.getString() != "\\begin_preamble")
2586 lyxerr << "Error (BufferParams::readPreamble):"
2587 "consistency check failed." << endl;
2589 preamble = lex.getLongString(from_ascii("\\end_preamble"));
2593 void BufferParams::readLocalLayout(Lexer & lex, bool forced)
2595 string const expected = forced ? "\\begin_forced_local_layout" :
2596 "\\begin_local_layout";
2597 if (lex.getString() != expected)
2598 lyxerr << "Error (BufferParams::readLocalLayout):"
2599 "consistency check failed." << endl;
2602 forced_local_layout_ =
2603 lex.getLongString(from_ascii("\\end_forced_local_layout"));
2605 local_layout_ = lex.getLongString(from_ascii("\\end_local_layout"));
2609 bool BufferParams::setLanguage(string const & lang)
2611 Language const *new_language = languages.getLanguage(lang);
2612 if (!new_language) {
2613 // Language lang was not found
2616 language = new_language;
2621 void BufferParams::readLanguage(Lexer & lex)
2623 if (!lex.next()) return;
2625 string const tmptok = lex.getString();
2627 // check if tmptok is part of tex_babel in tex-defs.h
2628 if (!setLanguage(tmptok)) {
2629 // Language tmptok was not found
2630 language = default_language;
2631 lyxerr << "Warning: Setting language `"
2632 << tmptok << "' to `" << language->lang()
2638 void BufferParams::readGraphicsDriver(Lexer & lex)
2643 string const tmptok = lex.getString();
2644 // check if tmptok is part of tex_graphics in tex_defs.h
2647 string const test = tex_graphics[n++];
2649 if (test == tmptok) {
2650 graphics_driver = tmptok;
2655 "Warning: graphics driver `$$Token' not recognized!\n"
2656 " Setting graphics driver to `default'.\n");
2657 graphics_driver = "default";
2664 void BufferParams::readBullets(Lexer & lex)
2669 int const index = lex.getInteger();
2671 int temp_int = lex.getInteger();
2672 user_defined_bullet(index).setFont(temp_int);
2673 temp_bullet(index).setFont(temp_int);
2675 user_defined_bullet(index).setCharacter(temp_int);
2676 temp_bullet(index).setCharacter(temp_int);
2678 user_defined_bullet(index).setSize(temp_int);
2679 temp_bullet(index).setSize(temp_int);
2683 void BufferParams::readBulletsLaTeX(Lexer & lex)
2685 // The bullet class should be able to read this.
2688 int const index = lex.getInteger();
2690 docstring const temp_str = lex.getDocString();
2692 user_defined_bullet(index).setText(temp_str);
2693 temp_bullet(index).setText(temp_str);
2697 void BufferParams::readModules(Lexer & lex)
2699 if (!lex.eatLine()) {
2700 lyxerr << "Error (BufferParams::readModules):"
2701 "Unexpected end of input." << endl;
2705 string mod = lex.getString();
2706 if (mod == "\\end_modules")
2708 addLayoutModule(mod);
2714 void BufferParams::readRemovedModules(Lexer & lex)
2716 if (!lex.eatLine()) {
2717 lyxerr << "Error (BufferParams::readRemovedModules):"
2718 "Unexpected end of input." << endl;
2722 string mod = lex.getString();
2723 if (mod == "\\end_removed_modules")
2725 removed_modules_.push_back(mod);
2728 // now we want to remove any removed modules that were previously
2729 // added. normally, that will be because default modules were added in
2730 // setBaseClass(), which gets called when \textclass is read at the
2731 // start of the read.
2732 list<string>::const_iterator rit = removed_modules_.begin();
2733 list<string>::const_iterator const ren = removed_modules_.end();
2734 for (; rit != ren; ++rit) {
2735 LayoutModuleList::iterator const mit = layout_modules_.begin();
2736 LayoutModuleList::iterator const men = layout_modules_.end();
2737 LayoutModuleList::iterator found = find(mit, men, *rit);
2740 layout_modules_.erase(found);
2745 void BufferParams::readIncludeonly(Lexer & lex)
2747 if (!lex.eatLine()) {
2748 lyxerr << "Error (BufferParams::readIncludeonly):"
2749 "Unexpected end of input." << endl;
2753 string child = lex.getString();
2754 if (child == "\\end_includeonly")
2756 included_children_.push_back(child);
2762 string BufferParams::paperSizeName(PapersizePurpose purpose) const
2764 switch (papersize) {
2766 // could be anything, so don't guess
2768 case PAPER_CUSTOM: {
2769 if (purpose == XDVI && !paperwidth.empty() &&
2770 !paperheight.empty()) {
2771 // heightxwidth<unit>
2772 string first = paperwidth;
2773 string second = paperheight;
2774 if (orientation == ORIENTATION_LANDSCAPE)
2777 return first.erase(first.length() - 2)
2783 // dvips and dvipdfm do not know this
2784 if (purpose == DVIPS || purpose == DVIPDFM)
2788 if (purpose == DVIPS || purpose == DVIPDFM)
2792 if (purpose == DVIPS || purpose == DVIPDFM)
2802 if (purpose == DVIPS || purpose == DVIPDFM)
2806 if (purpose == DVIPS || purpose == DVIPDFM)
2810 if (purpose == DVIPS || purpose == DVIPDFM)
2814 if (purpose == DVIPS || purpose == DVIPDFM)
2818 if (purpose == DVIPS || purpose == DVIPDFM)
2822 // dvipdfm does not know this
2823 if (purpose == DVIPDFM)
2827 if (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)
2883 if (purpose == DVIPS || purpose == DVIPDFM)
2887 if (purpose == DVIPS || purpose == DVIPDFM)
2890 case PAPER_USEXECUTIVE:
2891 // dvipdfm does not know this
2892 if (purpose == DVIPDFM)
2897 case PAPER_USLETTER:
2899 if (purpose == XDVI)
2906 string const BufferParams::dvips_options() const
2910 // If the class loads the geometry package, we do not know which
2911 // paper size is used, since we do not set it (bug 7013).
2912 // Therefore we must not specify any argument here.
2913 // dvips gets the correct paper size via DVI specials in this case
2914 // (if the class uses the geometry package correctly).
2915 if (documentClass().provides("geometry"))
2919 && papersize == PAPER_CUSTOM
2920 && !lyxrc.print_paper_dimension_flag.empty()
2921 && !paperwidth.empty()
2922 && !paperheight.empty()) {
2923 // using a custom papersize
2924 result = lyxrc.print_paper_dimension_flag;
2925 result += ' ' + paperwidth;
2926 result += ',' + paperheight;
2928 string const paper_option = paperSizeName(DVIPS);
2929 if (!paper_option.empty() && (paper_option != "letter" ||
2930 orientation != ORIENTATION_LANDSCAPE)) {
2931 // dvips won't accept -t letter -t landscape.
2932 // In all other cases, include the paper size
2934 result = lyxrc.print_paper_flag;
2935 result += ' ' + paper_option;
2938 if (orientation == ORIENTATION_LANDSCAPE &&
2939 papersize != PAPER_CUSTOM)
2940 result += ' ' + lyxrc.print_landscape_flag;
2945 string const BufferParams::font_encoding() const
2947 return font_encodings().empty() ? "default" : font_encodings().back();
2951 vector<string> const BufferParams::font_encodings() const
2953 string doc_fontenc = (fontenc == "global") ? lyxrc.fontenc : fontenc;
2955 vector<string> fontencs;
2957 // "default" means "no explicit font encoding"
2958 if (doc_fontenc != "default") {
2959 fontencs = getVectorFromString(doc_fontenc);
2960 if (!language->fontenc().empty()
2961 && ascii_lowercase(language->fontenc()) != "none") {
2962 vector<string> fencs = getVectorFromString(language->fontenc());
2963 vector<string>::const_iterator fit = fencs.begin();
2964 for (; fit != fencs.end(); ++fit) {
2965 if (find(fontencs.begin(), fontencs.end(), *fit) == fontencs.end())
2966 fontencs.push_back(*fit);
2975 string BufferParams::babelCall(string const & lang_opts, bool const langoptions) const
2977 // suppress the babel call if there is no BabelName defined
2978 // for the document language in the lib/languages file and if no
2979 // other languages are used (lang_opts is then empty)
2980 if (lang_opts.empty())
2982 // either a specific language (AsBabelOptions setting in
2983 // lib/languages) or the prefs require the languages to
2984 // be submitted to babel itself (not the class).
2986 return "\\usepackage[" + lang_opts + "]{babel}";
2987 return "\\usepackage{babel}";
2991 docstring BufferParams::getGraphicsDriver(string const & package) const
2995 if (package == "geometry") {
2996 if (graphics_driver == "dvips"
2997 || graphics_driver == "dvipdfm"
2998 || graphics_driver == "pdftex"
2999 || graphics_driver == "vtex")
3000 result = from_ascii(graphics_driver);
3001 else if (graphics_driver == "dvipdfmx")
3002 result = from_ascii("dvipdfm");
3009 void BufferParams::writeEncodingPreamble(otexstream & os,
3010 LaTeXFeatures & features) const
3012 // XeTeX/LuaTeX: (see also #9740)
3013 // With Unicode fonts we use utf8-plain without encoding package.
3014 // With TeX fonts, we cannot use utf8-plain, but "inputenc" fails.
3015 // XeTeX must use ASCII encoding (see Buffer.cpp),
3016 // for LuaTeX, we load "luainputenc" (see below).
3017 if (useNonTeXFonts || features.runparams().flavor == OutputParams::XETEX)
3020 if (inputenc == "auto") {
3021 string const doc_encoding =
3022 language->encoding()->latexName();
3023 Encoding::Package const package =
3024 language->encoding()->package();
3026 // Create list of inputenc options:
3027 set<string> encodings;
3028 // luainputenc fails with more than one encoding
3029 if (!features.runparams().isFullUnicode()) // if we reach this point, this means LuaTeX with TeX fonts
3030 // list all input encodings used in the document
3031 encodings = features.getEncodingSet(doc_encoding);
3033 // If the "japanese" package (i.e. pLaTeX) is used,
3034 // inputenc must be omitted.
3035 // see http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg129680.html
3036 if ((!encodings.empty() || package == Encoding::inputenc)
3037 && !features.isRequired("japanese")
3038 && !features.isProvided("inputenc")) {
3039 os << "\\usepackage[";
3040 set<string>::const_iterator it = encodings.begin();
3041 set<string>::const_iterator const end = encodings.end();
3043 os << from_ascii(*it);
3046 for (; it != end; ++it)
3047 os << ',' << from_ascii(*it);
3048 if (package == Encoding::inputenc) {
3049 if (!encodings.empty())
3051 os << from_ascii(doc_encoding);
3053 if (features.runparams().flavor == OutputParams::LUATEX
3054 || features.runparams().flavor == OutputParams::DVILUATEX)
3055 os << "]{luainputenc}\n";
3057 os << "]{inputenc}\n";
3059 if (package == Encoding::CJK || features.mustProvide("CJK")) {
3060 if (language->encoding()->name() == "utf8-cjk"
3061 && LaTeXFeatures::isAvailable("CJKutf8"))
3062 os << "\\usepackage{CJKutf8}\n";
3064 os << "\\usepackage{CJK}\n";
3066 } else if (inputenc != "default") {
3067 switch (encoding().package()) {
3068 case Encoding::none:
3069 case Encoding::japanese:
3071 case Encoding::inputenc:
3072 // do not load inputenc if japanese is used
3073 // or if the class provides inputenc
3074 if (features.isRequired("japanese")
3075 || features.isProvided("inputenc"))
3077 os << "\\usepackage[" << from_ascii(encoding().latexName());
3078 if (features.runparams().flavor == OutputParams::LUATEX
3079 || features.runparams().flavor == OutputParams::DVILUATEX)
3080 os << "]{luainputenc}\n";
3082 os << "]{inputenc}\n";
3085 if (encoding().name() == "utf8-cjk"
3086 && LaTeXFeatures::isAvailable("CJKutf8"))
3087 os << "\\usepackage{CJKutf8}\n";
3089 os << "\\usepackage{CJK}\n";
3092 // Load the CJK package if needed by a secondary language.
3093 // If the main encoding is some variant of UTF8, use CJKutf8.
3094 if (encoding().package() != Encoding::CJK && features.mustProvide("CJK")) {
3095 if (encoding().iconvName() == "UTF-8"
3096 && LaTeXFeatures::isAvailable("CJKutf8"))
3097 os << "\\usepackage{CJKutf8}\n";
3099 os << "\\usepackage{CJK}\n";
3105 string const BufferParams::parseFontName(string const & name) const
3107 string mangled = name;
3108 size_t const idx = mangled.find('[');
3109 if (idx == string::npos || idx == 0)
3112 return mangled.substr(0, idx - 1);
3116 string const BufferParams::loadFonts(LaTeXFeatures & features) const
3118 if (fontsRoman() == "default" && fontsSans() == "default"
3119 && fontsTypewriter() == "default"
3120 && (fontsMath() == "default" || fontsMath() == "auto"))
3126 /* Fontspec (XeTeX, LuaTeX): we provide GUI support for oldstyle
3127 * numbers (Numbers=OldStyle) and sf/tt scaling. The Ligatures=TeX/
3128 * Mapping=tex-text option assures TeX ligatures (such as "--")
3129 * are resolved. Note that tt does not use these ligatures.
3131 * -- add more GUI options?
3132 * -- add more fonts (fonts for other scripts)
3133 * -- if there's a way to find out if a font really supports
3134 * OldStyle, enable/disable the widget accordingly.
3136 if (useNonTeXFonts && features.isAvailable("fontspec")) {
3137 // "Mapping=tex-text" and "Ligatures=TeX" are equivalent.
3138 // However, until v.2 (2010/07/11) fontspec only knew
3139 // Mapping=tex-text (for XeTeX only); then "Ligatures=TeX"
3140 // was introduced for both XeTeX and LuaTeX (LuaTeX
3141 // didn't understand "Mapping=tex-text", while XeTeX
3142 // understood both. With most recent versions, both
3143 // variants are understood by both engines. However,
3144 // we want to provide support for at least TeXLive 2009
3145 // (for XeTeX; LuaTeX is only supported as of v.2)
3146 string const texmapping =
3147 (features.runparams().flavor == OutputParams::XETEX) ?
3148 "Mapping=tex-text" : "Ligatures=TeX";
3149 if (fontsRoman() != "default") {
3150 os << "\\setmainfont[" << texmapping;
3151 if (fonts_old_figures)
3152 os << ",Numbers=OldStyle";
3153 os << "]{" << parseFontName(fontsRoman()) << "}\n";
3155 if (fontsSans() != "default") {
3156 string const sans = parseFontName(fontsSans());
3157 if (fontsSansScale() != 100)
3158 os << "\\setsansfont[Scale="
3159 << float(fontsSansScale()) / 100
3160 << "," << texmapping << "]{"
3163 os << "\\setsansfont[" << texmapping << "]{"
3166 if (fontsTypewriter() != "default") {
3167 string const mono = parseFontName(fontsTypewriter());
3168 if (fontsTypewriterScale() != 100)
3169 os << "\\setmonofont[Scale="
3170 << float(fontsTypewriterScale()) / 100
3174 os << "\\setmonofont{"
3181 bool const ot1 = (font_encoding() == "default" || font_encoding() == "OT1");
3182 bool const dryrun = features.runparams().dryrun;
3183 bool const complete = (fontsSans() == "default" && fontsTypewriter() == "default");
3184 bool const nomath = (fontsMath() == "default");
3187 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsRoman())).getLaTeXCode(
3188 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3192 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsSans())).getLaTeXCode(
3193 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3194 nomath, fontsSansScale());
3196 // MONOSPACED/TYPEWRITER
3197 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsTypewriter())).getLaTeXCode(
3198 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3199 nomath, fontsTypewriterScale());
3202 os << theLaTeXFonts().getLaTeXFont(from_ascii(fontsMath())).getLaTeXCode(
3203 dryrun, ot1, complete, fonts_expert_sc, fonts_old_figures,
3210 Encoding const & BufferParams::encoding() const
3212 // Main encoding for LaTeX output.
3214 // Exception: XeTeX with 8-bit TeX fonts requires ASCII (see #9740).
3215 // As the "flavor" is only known once export started, this
3216 // cannot be handled here. Instead, runparams.encoding is set
3217 // to ASCII in Buffer::makeLaTeXFile (for export)
3218 // and Buffer::writeLaTeXSource (for preview).
3220 return *(encodings.fromLyXName("utf8-plain"));
3221 if (inputenc == "auto" || inputenc == "default")
3222 return *language->encoding();
3223 Encoding const * const enc = encodings.fromLyXName(inputenc);
3226 LYXERR0("Unknown inputenc value `" << inputenc
3227 << "'. Using `auto' instead.");
3228 return *language->encoding();
3232 bool BufferParams::addCiteEngine(string const & engine)
3234 LayoutModuleList::const_iterator it = cite_engine_.begin();
3235 LayoutModuleList::const_iterator en = cite_engine_.end();
3236 for (; it != en; ++it)
3239 cite_engine_.push_back(engine);
3244 bool BufferParams::addCiteEngine(vector<string> const & engine)
3246 vector<string>::const_iterator it = engine.begin();
3247 vector<string>::const_iterator en = engine.end();
3249 for (; it != en; ++it)
3250 if (!addCiteEngine(*it))
3256 string const & BufferParams::defaultBiblioStyle() const
3258 return documentClass().defaultBiblioStyle();
3262 bool const & BufferParams::fullAuthorList() const
3264 return documentClass().fullAuthorList();
3268 void BufferParams::setCiteEngine(string const & engine)
3271 addCiteEngine(engine);
3275 void BufferParams::setCiteEngine(vector<string> const & engine)
3278 addCiteEngine(engine);
3282 vector<string> BufferParams::citeCommands() const
3284 static CitationStyle const default_style;
3285 vector<string> commands =
3286 documentClass().citeCommands(citeEngineType());
3287 if (commands.empty())
3288 commands.push_back(default_style.cmd);
3293 vector<CitationStyle> BufferParams::citeStyles() const
3295 static CitationStyle const default_style;
3296 vector<CitationStyle> styles =
3297 documentClass().citeStyles(citeEngineType());
3299 styles.push_back(default_style);
3303 void BufferParams::invalidateConverterCache() const
3305 pimpl_->isExportCacheValid = false;
3306 pimpl_->isViewCacheValid = false;