3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
20 #include "LayoutFile.h"
23 #include "TextClass.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
31 #include "support/regex.h"
37 using namespace lyx::support;
46 // CJK languages are handled in text.cpp, polyglossia languages are listed
49 * known babel language names (including synonyms)
50 * not in standard babel: arabic, arabtex, armenian, belarusian, serbian-latin, thai
51 * please keep this in sync with known_coded_languages line by line!
53 const char * const known_languages[] = {"acadian", "afrikaans", "albanian",
54 "american", "arabic", "arabtex", "australian", "austrian", "bahasa", "bahasai",
55 "bahasam", "basque", "belarusian", "brazil", "brazilian", "breton", "british",
56 "bulgarian", "canadian", "canadien", "catalan", "croatian", "czech", "danish",
57 "dutch", "english", "esperanto", "estonian", "farsi", "finnish", "francais",
58 "french", "frenchb", "frenchle", "frenchpro", "galician", "german", "germanb",
59 "georgian", "greek", "hebrew", "hungarian", "icelandic", "indon", "indonesian",
60 "interlingua", "irish", "italian", "japanese", "kazakh", "kurmanji", "latin",
61 "latvian", "lithuanian", "lowersorbian", "lsorbian", "magyar", "malay", "meyalu",
62 "mongolian", "naustrian", "newzealand", "ngerman", "ngermanb", "norsk", "nswissgerman",
63 "nynorsk", "polutonikogreek", "polish", "portuges", "portuguese", "romanian", "russian",
64 "russianb", "samin", "scottish", "serbian", "serbian-latin", "slovak",
65 "slovene", "spanish", "swedish", "swissgerman", "thai", "turkish", "turkmen",
66 "ukraineb", "ukrainian", "uppersorbian", "UKenglish", "USenglish", "usorbian",
71 * the same as known_languages with .lyx names
72 * please keep this in sync with known_languages line by line!
74 const char * const known_coded_languages[] = {"french", "afrikaans", "albanian",
75 "american", "arabic_arabi", "arabic_arabtex", "australian", "austrian", "bahasa", "bahasa",
76 "bahasam", "basque", "belarusian", "brazilian", "brazilian", "breton", "british",
77 "bulgarian", "canadian", "canadien", "catalan", "croatian", "czech", "danish",
78 "dutch", "english", "esperanto", "estonian", "farsi", "finnish", "french",
79 "french", "french", "french", "french", "galician", "german", "german",
80 "georgian", "greek", "hebrew", "magyar", "icelandic", "bahasa", "bahasa",
81 "interlingua", "irish", "italian", "japanese", "kazakh", "kurmanji", "latin",
82 "latvian", "lithuanian", "lowersorbian", "lowersorbian", "magyar", "bahasam", "bahasam",
83 "mongolian", "naustrian", "newzealand", "ngerman", "ngerman", "norsk", "german-ch",
84 "nynorsk", "polutonikogreek", "polish", "portuguese", "portuguese", "romanian", "russian",
85 "russian", "samin", "scottish", "serbian", "serbian-latin", "slovak",
86 "slovene", "spanish", "swedish", "german-ch-old", "thai", "turkish", "turkmen",
87 "ukrainian", "ukrainian", "uppersorbian", "english", "english", "uppersorbian",
88 "vietnamese", "welsh",
91 /// languages with danish quotes (.lyx names)
92 const char * const known_danish_quotes_languages[] = {"danish", 0};
94 /// languages with english quotes (.lyx names)
95 const char * const known_english_quotes_languages[] = {"american", "australian",
96 "bahasa", "bahasam", "brazilian", "canadian", "chinese-simplified", "english",
97 "esperanto", "hebrew", "irish", "korean", "newzealand", "portuguese", "scottish",
100 /// languages with french quotes (.lyx names)
101 const char * const known_french_quotes_languages[] = {"albanian",
102 "arabic_arabi", "arabic_arabtex", "basque", "canadien", "catalan", "french",
103 "galician", "greek", "italian", "norsk", "nynorsk", "polutonikogreek",
104 "russian", "spanish", "spanish-mexico", "turkish", "turkmen", "ukrainian",
107 /// languages with german quotes (.lyx names)
108 const char * const known_german_quotes_languages[] = {"austrian", "bulgarian",
109 "czech", "german", "georgian", "icelandic", "lithuanian", "lowersorbian", "naustrian",
110 "ngerman", "serbian", "serbian-latin", "slovak", "slovene", "uppersorbian", 0};
112 /// languages with polish quotes (.lyx names)
113 const char * const known_polish_quotes_languages[] = {"afrikaans", "croatian",
114 "dutch", "estonian", "magyar", "polish", "romanian", 0};
116 /// languages with swedish quotes (.lyx names)
117 const char * const known_swedish_quotes_languages[] = {"finnish",
120 /// known language packages from the times before babel
121 const char * const known_old_language_packages[] = {"french", "frenchle",
122 "frenchpro", "german", "ngerman", "pmfrench", 0};
124 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
126 const char * const known_roman_fonts[] = { "ae", "beraserif", "bookman",
127 "ccfonts", "chancery", "charter", "cmr", "fourier", "garamondx", "libertine",
128 "libertine-type1", "lmodern", "mathdesign", "mathpazo", "mathptmx", "newcent",
129 "tgbonum", "tgchorus", "tgpagella", "tgschola", "tgtermes", "utopia", 0};
131 const char * const known_sans_fonts[] = { "avant", "berasans", "biolinum-type1",
132 "cmbr", "cmss", "helvet", "iwona", "iwonac", "iwonal", "iwonalc", "kurier",
133 "kurierc", "kurierl", "kurierlc", "lmss", "tgadventor", "tgheros", 0};
135 const char * const known_typewriter_fonts[] = { "beramono", "cmtl", "cmtt",
136 "courier", "lmtt", "luximono", "fourier", "libertineMono-type1", "lmodern",
137 "mathpazo", "mathptmx", "newcent", "tgcursor", "txtt", 0};
139 const char * const known_math_fonts[] = { "eulervm", "newtxmath", 0};
141 const char * const known_paper_sizes[] = { "a0paper", "b0paper", "c0paper",
142 "a1paper", "b1paper", "c1paper", "a2paper", "b2paper", "c2paper", "a3paper",
143 "b3paper", "c3paper", "a4paper", "b4paper", "c4paper", "a5paper", "b5paper",
144 "c5paper", "a6paper", "b6paper", "c6paper", "executivepaper", "legalpaper",
145 "letterpaper", "b0j", "b1j", "b2j", "b3j", "b4j", "b5j", "b6j", 0};
147 const char * const known_class_paper_sizes[] = { "a4paper", "a5paper",
148 "executivepaper", "legalpaper", "letterpaper", 0};
150 const char * const known_paper_margins[] = { "lmargin", "tmargin", "rmargin",
151 "bmargin", "headheight", "headsep", "footskip", "columnsep", 0};
153 const char * const known_coded_paper_margins[] = { "leftmargin", "topmargin",
154 "rightmargin", "bottommargin", "headheight", "headsep", "footskip",
157 /// commands that can start an \if...\else...\endif sequence
158 const char * const known_if_commands[] = {"if", "ifarydshln", "ifbraket",
159 "ifcancel", "ifcolortbl", "ifeurosym", "ifmarginnote", "ifmmode", "ifpdf",
160 "ifsidecap", "ifupgreek", 0};
162 const char * const known_basic_colors[] = {"black", "blue", "brown", "cyan",
163 "darkgray", "gray", "green", "lightgray", "lime", "magenta", "orange", "olive",
164 "pink", "purple", "red", "teal", "violet", "white", "yellow", 0};
166 const char * const known_basic_color_codes[] = {"#000000", "#0000ff", "#964B00", "#00ffff",
167 "#a9a9a9", "#808080", "#00ff00", "#d3d3d3", "#bfff00", "#ff00ff", "#ff7f00", "#808000",
168 "#ffc0cb", "#800080", "#ff0000", "#008080", "#8f00ff", "#ffffff", "#ffff00", 0};
170 /// conditional commands with three arguments like \@ifundefined{}{}{}
171 const char * const known_if_3arg_commands[] = {"@ifundefined", "IfFileExists",
174 /// packages that work only in xetex
175 /// polyglossia is handled separately
176 const char * const known_xetex_packages[] = {"arabxetex", "fixlatvian",
177 "fontbook", "fontwrap", "mathspec", "philokalia", "unisugar",
178 "xeCJK", "xecolor", "xecyr", "xeindex", "xepersian", "xunicode", 0};
180 /// packages that are automatically skipped if loaded by LyX
181 const char * const known_lyx_packages[] = {"amsbsy", "amsmath", "amssymb",
182 "amstext", "amsthm", "array", "babel", "booktabs", "calc", "CJK", "color",
183 "float", "fontspec", "framed", "graphicx", "hhline", "ifthen", "longtable",
184 "makeidx", "multirow", "nomencl", "pdfpages", "prettyref", "refstyle", "rotating",
185 "rotfloat", "splitidx", "setspace", "subscript", "textcomp", "tipa", "tipx",
186 "tone", "ulem", "url", "varioref", "verbatim", "wrapfig", "xcolor", "xunicode", 0};
188 // codes used to remove packages that are loaded automatically by LyX.
189 // Syntax: package_beg_sep<name>package_mid_sep<package loading code>package_end_sep
190 const char package_beg_sep = '\001';
191 const char package_mid_sep = '\002';
192 const char package_end_sep = '\003';
195 // returns true if at least one of the options in what has been found
196 bool handle_opt(vector<string> & opts, char const * const * what, string & target)
202 // the last language option is the document language (for babel and LyX)
203 // the last size option is the document font size
204 vector<string>::iterator it;
205 vector<string>::iterator position = opts.begin();
206 for (; *what; ++what) {
207 it = find(opts.begin(), opts.end(), *what);
208 if (it != opts.end()) {
209 if (it >= position) {
220 void delete_opt(vector<string> & opts, char const * const * what)
225 // remove found options from the list
226 // do this after handle_opt to avoid potential memory leaks
227 vector<string>::iterator it;
228 for (; *what; ++what) {
229 it = find(opts.begin(), opts.end(), *what);
230 if (it != opts.end())
237 * Split a package options string (keyval format) into a vector.
239 * authorformat=smallcaps,
241 * titleformat=colonsep,
242 * bibformat={tabular,ibidem,numbered}
244 vector<string> split_options(string const & input)
246 vector<string> options;
250 Token const & t = p.get_token();
251 if (t.asInput() == ",") {
252 options.push_back(trimSpaceAndEol(option));
254 } else if (t.asInput() == "=") {
257 if (p.next_token().asInput() == "{")
258 option += '{' + p.getArg('{', '}') + '}';
259 } else if (t.cat() != catSpace)
260 option += t.asInput();
264 options.push_back(trimSpaceAndEol(option));
271 * Retrieve a keyval option "name={value with=sign}" named \p name from
272 * \p options and return the value.
273 * The found option is also removed from \p options.
275 string process_keyval_opt(vector<string> & options, string name)
277 for (size_t i = 0; i < options.size(); ++i) {
278 vector<string> option;
279 split(options[i], option, '=');
280 if (option.size() < 2)
282 if (option[0] == name) {
283 options.erase(options.begin() + i);
284 option.erase(option.begin());
285 return join(option, "=");
291 } // anonymous namespace
295 * known polyglossia language names (including variants)
296 * FIXME: support spelling=old for german variants (german vs. ngerman LyX names etc)
298 const char * const Preamble::polyglossia_languages[] = {
299 "albanian", "croatian", "hebrew", "norsk", "swedish", "amharic", "czech", "hindi",
300 "nynorsk", "syriac", "arabic", "danish", "icelandic", "occitan", "tamil",
301 "armenian", "divehi", "interlingua", "polish", "telugu", "asturian", "dutch",
302 "irish", "portuges", "thai", "bahasai", "english", "italian", "romanian", "turkish",
303 "bahasam", "esperanto", "lao", "russian", "turkmen", "basque", "estonian", "latin",
304 "samin", "ukrainian", "bengali", "farsi", "latvian", "sanskrit", "tibetan", "urdu",
305 "brazil", "brazilian", "finnish", "lithuanian", "scottish", "usorbian", "breton",
306 "french", "lsorbian", "serbian", "vietnamese", "bulgarian", "galician", "magyar",
307 "slovak", "welsh", "catalan", "german", "malayalam", "slovenian", "coptic", "greek",
308 "marathi", "spanish", "austrian",
309 "american", "ancient", "australian", "british", "monotonic", "newzealand",
313 * the same as polyglossia_languages with .lyx names
314 * please keep this in sync with polyglossia_languages line by line!
316 const char * const Preamble::coded_polyglossia_languages[] = {
317 "albanian", "croatian", "hebrew", "norsk", "swedish", "amharic", "czech", "hindi",
318 "nynorsk", "syriac", "arabic_arabi", "danish", "icelandic", "occitan", "tamil",
319 "armenian", "divehi", "interlingua", "polish", "telugu", "asturian", "dutch",
320 "irish", "portuges", "thai", "bahasa", "english", "italian", "romanian", "turkish",
321 "bahasam", "esperanto", "lao", "russian", "turkmen", "basque", "estonian", "latin",
322 "samin", "ukrainian", "bengali", "farsi", "latvian", "sanskrit", "tibetan", "urdu",
323 "brazilian", "brazilian", "finnish", "lithuanian", "scottish", "uppersorbian", "breton",
324 "french", "lowersorbian", "serbian", "vietnamese", "bulgarian", "galician", "magyar",
325 "slovak", "welsh", "catalan", "ngerman", "malayalam", "slovene", "coptic", "greek",
326 "marathi", "spanish", "naustrian",
327 "american", "ancientgreek", "australian", "british", "greek", "newzealand",
328 "polutonikogreek", 0};
331 bool Preamble::usePolyglossia() const
333 return h_use_non_tex_fonts && h_language_package == "default";
337 bool Preamble::indentParagraphs() const
339 return h_paragraph_separation == "indent";
343 bool Preamble::isPackageUsed(string const & package) const
345 return used_packages.find(package) != used_packages.end();
349 vector<string> Preamble::getPackageOptions(string const & package) const
351 map<string, vector<string> >::const_iterator it = used_packages.find(package);
352 if (it != used_packages.end())
354 return vector<string>();
358 void Preamble::registerAutomaticallyLoadedPackage(std::string const & package)
360 auto_packages.insert(package);
364 void Preamble::addModule(string const & module)
366 used_modules.push_back(module);
370 void Preamble::suppressDate(bool suppress)
373 h_suppress_date = "true";
375 h_suppress_date = "false";
379 void Preamble::registerAuthor(std::string const & name)
381 Author author(from_utf8(name), empty_docstring());
382 author.setUsed(true);
383 authors_.record(author);
384 h_tracking_changes = "true";
385 h_output_changes = "true";
389 Author const & Preamble::getAuthor(std::string const & name) const
391 Author author(from_utf8(name), empty_docstring());
392 for (AuthorList::Authors::const_iterator it = authors_.begin();
393 it != authors_.end(); ++it)
396 static Author const dummy;
401 int Preamble::getSpecialTableColumnArguments(char c) const
403 map<char, int>::const_iterator it = special_columns_.find(c);
404 if (it == special_columns_.end())
410 void Preamble::add_package(string const & name, vector<string> & options)
412 // every package inherits the global options
413 if (used_packages.find(name) == used_packages.end())
414 used_packages[name] = split_options(h_options);
416 vector<string> & v = used_packages[name];
417 v.insert(v.end(), options.begin(), options.end());
418 if (name == "jurabib") {
419 // Don't output the order argument (see the cite command
420 // handling code in text.cpp).
421 vector<string>::iterator end =
422 remove(options.begin(), options.end(), "natbiborder");
423 end = remove(options.begin(), end, "jurabiborder");
424 options.erase(end, options.end());
431 // Given is a string like "scaled=0.9" or "Scale=0.9", return 0.9 * 100
432 bool scale_as_percentage(string const & scale, string & percentage)
434 string::size_type pos = scale.find('=');
435 if (pos != string::npos) {
436 string value = scale.substr(pos + 1);
437 if (isStrDbl(value)) {
438 percentage = convert<string>(
439 static_cast<int>(100 * convert<double>(value)));
447 string remove_braces(string const & value)
451 if (value[0] == '{' && value[value.length()-1] == '}')
452 return value.substr(1, value.length()-2);
456 } // anonymous namespace
459 Preamble::Preamble() : one_language(true), explicit_babel(false),
460 title_layout_found(false), index_number(0), h_font_cjk_set(false)
464 h_biblio_style = "plain";
465 h_bibtex_command = "default";
466 h_cite_engine = "basic";
467 h_cite_engine_type = "default";
469 h_defskip = "medskip";
472 h_fontencoding = "default";
473 h_font_roman[0] = "default";
474 h_font_roman[1] = "default";
475 h_font_sans[0] = "default";
476 h_font_sans[1] = "default";
477 h_font_typewriter[0] = "default";
478 h_font_typewriter[1] = "default";
479 h_font_math[0] = "auto";
480 h_font_math[1] = "auto";
481 h_font_default_family = "default";
482 h_use_non_tex_fonts = false;
484 h_font_osf = "false";
485 h_font_sf_scale[0] = "100";
486 h_font_sf_scale[1] = "100";
487 h_font_tt_scale[0] = "100";
488 h_font_tt_scale[1] = "100";
490 h_graphics = "default";
491 h_default_output_format = "default";
492 h_html_be_strict = "false";
493 h_html_css_as_file = "0";
494 h_html_math_output = "0";
495 h_index[0] = "Index";
496 h_index_command = "default";
497 h_inputencoding = "auto";
498 h_justification = "true";
499 h_language = "english";
500 h_language_package = "none";
502 h_maintain_unincluded_children = "false";
506 h_output_changes = "false";
508 //h_output_sync_macro
509 h_papercolumns = "1";
510 h_paperfontsize = "default";
511 h_paperorientation = "portrait";
512 h_paperpagestyle = "default";
514 h_papersize = "default";
515 h_paragraph_indentation = "default";
516 h_paragraph_separation = "indent";
521 h_pdf_bookmarks = "0";
522 h_pdf_bookmarksnumbered = "0";
523 h_pdf_bookmarksopen = "0";
524 h_pdf_bookmarksopenlevel = "1";
525 h_pdf_breaklinks = "0";
526 h_pdf_pdfborder = "0";
527 h_pdf_colorlinks = "0";
528 h_pdf_backref = "section";
529 h_pdf_pdfusetitle = "0";
531 //h_pdf_quoted_options;
532 h_quotes_language = "english";
534 h_shortcut[0] = "idx";
535 h_spacing = "single";
536 h_save_transient_properties = "true";
537 h_suppress_date = "false";
538 h_textclass = "article";
540 h_tracking_changes = "false";
541 h_use_bibtopic = "false";
542 h_use_indices = "false";
543 h_use_geometry = "false";
544 h_use_default_options = "false";
545 h_use_hyperref = "false";
546 h_use_refstyle = false;
547 h_use_packages["amsmath"] = "1";
548 h_use_packages["amssymb"] = "0";
549 h_use_packages["cancel"] = "0";
550 h_use_packages["esint"] = "1";
551 h_use_packages["mhchem"] = "0";
552 h_use_packages["mathdots"] = "0";
553 h_use_packages["mathtools"] = "0";
554 h_use_packages["stackrel"] = "0";
555 h_use_packages["stmaryrd"] = "0";
556 h_use_packages["undertilde"] = "0";
560 void Preamble::handle_hyperref(vector<string> & options)
562 // FIXME swallow inputencoding changes that might surround the
563 // hyperref setup if it was written by LyX
564 h_use_hyperref = "true";
565 // swallow "unicode=true", since LyX does always write that
566 vector<string>::iterator it =
567 find(options.begin(), options.end(), "unicode=true");
568 if (it != options.end())
570 it = find(options.begin(), options.end(), "pdfusetitle");
571 if (it != options.end()) {
572 h_pdf_pdfusetitle = "1";
575 string bookmarks = process_keyval_opt(options, "bookmarks");
576 if (bookmarks == "true")
577 h_pdf_bookmarks = "1";
578 else if (bookmarks == "false")
579 h_pdf_bookmarks = "0";
580 if (h_pdf_bookmarks == "1") {
581 string bookmarksnumbered =
582 process_keyval_opt(options, "bookmarksnumbered");
583 if (bookmarksnumbered == "true")
584 h_pdf_bookmarksnumbered = "1";
585 else if (bookmarksnumbered == "false")
586 h_pdf_bookmarksnumbered = "0";
587 string bookmarksopen =
588 process_keyval_opt(options, "bookmarksopen");
589 if (bookmarksopen == "true")
590 h_pdf_bookmarksopen = "1";
591 else if (bookmarksopen == "false")
592 h_pdf_bookmarksopen = "0";
593 if (h_pdf_bookmarksopen == "1") {
594 string bookmarksopenlevel =
595 process_keyval_opt(options, "bookmarksopenlevel");
596 if (!bookmarksopenlevel.empty())
597 h_pdf_bookmarksopenlevel = bookmarksopenlevel;
600 string breaklinks = process_keyval_opt(options, "breaklinks");
601 if (breaklinks == "true")
602 h_pdf_breaklinks = "1";
603 else if (breaklinks == "false")
604 h_pdf_breaklinks = "0";
605 string pdfborder = process_keyval_opt(options, "pdfborder");
606 if (pdfborder == "{0 0 0}")
607 h_pdf_pdfborder = "1";
608 else if (pdfborder == "{0 0 1}")
609 h_pdf_pdfborder = "0";
610 string backref = process_keyval_opt(options, "backref");
611 if (!backref.empty())
612 h_pdf_backref = backref;
613 string colorlinks = process_keyval_opt(options, "colorlinks");
614 if (colorlinks == "true")
615 h_pdf_colorlinks = "1";
616 else if (colorlinks == "false")
617 h_pdf_colorlinks = "0";
618 string pdfpagemode = process_keyval_opt(options, "pdfpagemode");
619 if (!pdfpagemode.empty())
620 h_pdf_pagemode = pdfpagemode;
621 string pdftitle = process_keyval_opt(options, "pdftitle");
622 if (!pdftitle.empty()) {
623 h_pdf_title = remove_braces(pdftitle);
625 string pdfauthor = process_keyval_opt(options, "pdfauthor");
626 if (!pdfauthor.empty()) {
627 h_pdf_author = remove_braces(pdfauthor);
629 string pdfsubject = process_keyval_opt(options, "pdfsubject");
630 if (!pdfsubject.empty())
631 h_pdf_subject = remove_braces(pdfsubject);
632 string pdfkeywords = process_keyval_opt(options, "pdfkeywords");
633 if (!pdfkeywords.empty())
634 h_pdf_keywords = remove_braces(pdfkeywords);
635 if (!options.empty()) {
636 if (!h_pdf_quoted_options.empty())
637 h_pdf_quoted_options += ',';
638 h_pdf_quoted_options += join(options, ",");
644 void Preamble::handle_geometry(vector<string> & options)
646 h_use_geometry = "true";
647 vector<string>::iterator it;
649 if ((it = find(options.begin(), options.end(), "landscape")) != options.end()) {
650 h_paperorientation = "landscape";
654 // keyval version: "paper=letter"
655 string paper = process_keyval_opt(options, "paper");
657 h_papersize = paper + "paper";
658 // alternative version: "letterpaper"
659 handle_opt(options, known_paper_sizes, h_papersize);
660 delete_opt(options, known_paper_sizes);
662 char const * const * margin = known_paper_margins;
663 for (; *margin; ++margin) {
664 string value = process_keyval_opt(options, *margin);
665 if (!value.empty()) {
666 int k = margin - known_paper_margins;
667 string name = known_coded_paper_margins[k];
668 h_margins += '\\' + name + ' ' + value + '\n';
674 void Preamble::handle_package(Parser &p, string const & name,
675 string const & opts, bool in_lyx_preamble,
678 vector<string> options = split_options(opts);
679 add_package(name, options);
680 char const * const * where = 0;
682 if (is_known(name, known_xetex_packages)) {
684 h_use_non_tex_fonts = true;
685 registerAutomaticallyLoadedPackage("fontspec");
686 if (h_inputencoding == "auto")
687 p.setEncoding("UTF-8");
691 if (is_known(name, known_roman_fonts))
692 h_font_roman[0] = name;
694 if (name == "fourier") {
695 h_font_roman[0] = "utopia";
696 // when font uses real small capitals
697 if (opts == "expert")
701 if (name == "garamondx") {
702 h_font_roman[0] = "garamondx";
707 if (name == "libertine") {
708 h_font_roman[0] = "libertine";
709 // this automatically invokes biolinum
710 h_font_sans[0] = "biolinum";
713 else if (opts == "lining")
714 h_font_osf = "false";
717 if (name == "libertine-type1") {
718 h_font_roman[0] = "libertine";
719 // NOTE: contrary to libertine.sty, libertine-type1
720 // does not automatically invoke biolinum
721 if (opts == "lining")
722 h_font_osf = "false";
723 else if (opts == "osf")
727 if (name == "mathdesign") {
728 if (opts.find("charter") != string::npos)
729 h_font_roman[0] = "md-charter";
730 if (opts.find("garamond") != string::npos)
731 h_font_roman[0] = "md-garamond";
732 if (opts.find("utopia") != string::npos)
733 h_font_roman[0] = "md-utopia";
734 if (opts.find("expert") != string::npos) {
740 else if (name == "mathpazo")
741 h_font_roman[0] = "palatino";
743 else if (name == "mathptmx")
744 h_font_roman[0] = "times";
747 if (is_known(name, known_sans_fonts)) {
748 h_font_sans[0] = name;
749 if (options.size() >= 1) {
750 if (scale_as_percentage(opts, h_font_sf_scale[0]))
755 if (name == "biolinum-type1") {
756 h_font_sans[0] = "biolinum";
757 // biolinum can have several options, e.g. [osf,scaled=0.97]
758 string::size_type pos = opts.find("osf");
759 if (pos != string::npos)
764 if (is_known(name, known_typewriter_fonts)) {
765 // fourier can be set as roman font _only_
766 // fourier as typewriter is handled in handling of \ttdefault
767 if (name != "fourier") {
768 h_font_typewriter[0] = name;
769 if (options.size() >= 1) {
770 if (scale_as_percentage(opts, h_font_tt_scale[0]))
776 if (name == "libertineMono-type1") {
777 h_font_typewriter[0] = "libertine-mono";
780 // font uses old-style figure
785 if (is_known(name, known_math_fonts))
786 h_font_math[0] = name;
788 if (name == "newtxmath") {
790 h_font_math[0] = "newtxmath";
791 else if (opts == "garamondx")
792 h_font_math[0] = "garamondx-ntxm";
793 else if (opts == "libertine")
794 h_font_math[0] = "libertine-ntxm";
795 else if (opts == "minion")
796 h_font_math[0] = "minion-ntxm";
801 h_font_math[0] = "iwona-math";
803 if (name == "kurier")
805 h_font_math[0] = "kurier-math";
807 // after the detection and handling of special cases, we can remove the
808 // fonts, otherwise they would appear in the preamble, see bug #7856
809 if (is_known(name, known_roman_fonts) || is_known(name, known_sans_fonts)
810 || is_known(name, known_typewriter_fonts) || is_known(name, known_math_fonts))
813 else if (name == "amsmath" || name == "amssymb" || name == "cancel" ||
814 name == "esint" || name == "mhchem" || name == "mathdots" ||
815 name == "mathtools" || name == "stackrel" ||
816 name == "stmaryrd" || name == "undertilde")
817 h_use_packages[name] = "2";
819 else if (name == "babel") {
820 h_language_package = "default";
821 // One might think we would have to do nothing if babel is loaded
822 // without any options to prevent pollution of the preamble with this
823 // babel call in every roundtrip.
824 // But the user could have defined babel-specific things afterwards. So
825 // we need to keep it in the preamble to prevent cases like bug #7861.
827 // check if more than one option was used - used later for inputenc
828 if (options.begin() != options.end() - 1)
829 one_language = false;
830 // babel takes the last language of the option of its \usepackage
831 // call as document language. If there is no such language option, the
832 // last language in the documentclass options is used.
833 handle_opt(options, known_languages, h_language);
834 // translate the babel name to a LyX name
835 h_language = babel2lyx(h_language);
836 if (h_language == "japanese") {
837 // For Japanese, the encoding isn't indicated in the source
838 // file, and there's really not much we can do. We could
839 // 1) offer a list of possible encodings to choose from, or
840 // 2) determine the encoding of the file by inspecting it.
841 // For the time being, we leave the encoding alone so that
842 // we don't get iconv errors when making a wrong guess, and
843 // we will output a note at the top of the document
844 // explaining what to do.
845 Encoding const * const enc = encodings.fromIconvName(
846 p.getEncoding(), Encoding::japanese, false);
848 h_inputencoding = enc->name();
849 is_nonCJKJapanese = true;
850 // in this case babel can be removed from the preamble
851 registerAutomaticallyLoadedPackage("babel");
853 // If babel is called with options, LyX puts them by default into the
854 // document class options. This works for most languages, except
855 // for Latvian, Lithuanian, Mongolian, Turkmen and Vietnamese and
856 // perhaps in future others.
857 // Therefore keep the babel call as it is as the user might have
859 h_preamble << "\\usepackage[" << opts << "]{babel}\n";
861 delete_opt(options, known_languages);
863 h_preamble << "\\usepackage{babel}\n";
864 explicit_babel = true;
868 else if (name == "polyglossia") {
869 h_language_package = "default";
870 h_default_output_format = "pdf4";
871 h_use_non_tex_fonts = true;
873 registerAutomaticallyLoadedPackage("xunicode");
874 if (h_inputencoding == "auto")
875 p.setEncoding("UTF-8");
878 else if (name == "CJK") {
879 // set the encoding to "auto" because it might be set to "default" by the babel handling
880 // and this would not be correct for CJK
881 if (h_inputencoding == "default")
882 h_inputencoding = "auto";
883 registerAutomaticallyLoadedPackage("CJK");
886 else if (name == "CJKutf8") {
887 h_inputencoding = "utf8-cjk";
888 p.setEncoding("UTF-8");
889 registerAutomaticallyLoadedPackage("CJKutf8");
892 else if (name == "fontenc") {
893 h_fontencoding = getStringFromVector(options, ",");
894 /* We could do the following for better round trip support,
895 * but this makes the document less portable, so I skip it:
896 if (h_fontencoding == lyxrc.fontenc)
897 h_fontencoding = "global";
902 else if (name == "inputenc" || name == "luainputenc") {
903 // h_inputencoding is only set when there is not more than one
904 // inputenc option because otherwise h_inputencoding must be
905 // set to "auto" (the default encoding of the document language)
906 // Therefore check that exactly one option is passed to inputenc.
907 // It is also only set when there is not more than one babel
909 if (!options.empty()) {
910 string const encoding = options.back();
911 Encoding const * const enc = encodings.fromLaTeXName(
912 encoding, Encoding::inputenc, true);
915 cerr << "Unknown encoding " << encoding
916 << ". Ignoring." << std::endl;
918 if (!enc->unsafe() && options.size() == 1 && one_language == true)
919 h_inputencoding = enc->name();
920 p.setEncoding(enc->iconvName());
926 else if (name == "srcltx") {
929 h_output_sync_macro = "\\usepackage[" + opts + "]{srcltx}";
932 h_output_sync_macro = "\\usepackage{srcltx}";
935 else if (is_known(name, known_old_language_packages)) {
936 // known language packages from the times before babel
937 // if they are found and not also babel, they will be used as
938 // custom language package
939 h_language_package = "\\usepackage{" + name + "}";
942 else if (name == "lyxskak") {
943 // ignore this and its options
944 const char * const o[] = {"ps", "mover", 0};
945 delete_opt(options, o);
948 else if (is_known(name, known_lyx_packages) && options.empty()) {
949 if (name == "splitidx")
950 h_use_indices = "true";
951 if (name == "refstyle")
952 h_use_refstyle = true;
953 else if (name == "prettyref")
954 h_use_refstyle = false;
955 if (!in_lyx_preamble) {
956 h_preamble << package_beg_sep << name
957 << package_mid_sep << "\\usepackage{"
959 if (p.next_token().cat() == catNewline ||
960 (p.next_token().cat() == catSpace &&
961 p.next_next_token().cat() == catNewline))
963 h_preamble << package_end_sep;
967 else if (name == "geometry")
968 handle_geometry(options);
970 else if (name == "subfig")
971 ; // ignore this FIXME: Use the package separator mechanism instead
973 else if ((where = is_known(name, known_languages)))
974 h_language = known_coded_languages[where - known_languages];
976 else if (name == "natbib") {
977 h_biblio_style = "plainnat";
978 h_cite_engine = "natbib";
979 h_cite_engine_type = "authoryear";
980 vector<string>::iterator it =
981 find(options.begin(), options.end(), "authoryear");
982 if (it != options.end())
985 it = find(options.begin(), options.end(), "numbers");
986 if (it != options.end()) {
987 h_cite_engine_type = "numerical";
993 else if (name == "jurabib") {
994 h_biblio_style = "jurabib";
995 h_cite_engine = "jurabib";
996 h_cite_engine_type = "authoryear";
999 else if (name == "bibtopic")
1000 h_use_bibtopic = "true";
1002 else if (name == "hyperref")
1003 handle_hyperref(options);
1005 else if (name == "algorithm2e") {
1006 // Load "algorithm2e" module
1007 addModule("algorithm2e");
1008 // Add the package options to the global document options
1009 if (!options.empty()) {
1010 if (h_options.empty())
1011 h_options = join(options, ",");
1013 h_options += ',' + join(options, ",");
1017 else if (!in_lyx_preamble) {
1018 if (options.empty())
1019 h_preamble << "\\usepackage{" << name << '}';
1021 h_preamble << "\\usepackage[" << opts << "]{"
1025 if (p.next_token().cat() == catNewline ||
1026 (p.next_token().cat() == catSpace &&
1027 p.next_next_token().cat() == catNewline))
1031 // We need to do something with the options...
1032 if (!options.empty() && !detectEncoding)
1033 cerr << "Ignoring options '" << join(options, ",")
1034 << "' of package " << name << '.' << endl;
1036 // remove the whitespace
1041 void Preamble::handle_if(Parser & p, bool in_lyx_preamble)
1044 Token t = p.get_token();
1045 if (t.cat() == catEscape &&
1046 is_known(t.cs(), known_if_commands))
1047 handle_if(p, in_lyx_preamble);
1049 if (!in_lyx_preamble)
1050 h_preamble << t.asInput();
1051 if (t.cat() == catEscape && t.cs() == "fi")
1058 bool Preamble::writeLyXHeader(ostream & os, bool subdoc, string const & outfiledir)
1060 // set the quote language
1061 // LyX only knows the following quotes languages:
1062 // english, swedish, german, polish, french and danish
1063 // (quotes for "japanese" and "chinese-traditional" are missing because
1064 // they wouldn't be useful: http://www.lyx.org/trac/ticket/6383)
1065 // conversion list taken from
1066 // http://en.wikipedia.org/wiki/Quotation_mark,_non-English_usage
1067 // (quotes for kazakh and interlingua are unknown)
1069 if (is_known(h_language, known_danish_quotes_languages))
1070 h_quotes_language = "danish";
1072 else if (is_known(h_language, known_french_quotes_languages))
1073 h_quotes_language = "french";
1075 else if (is_known(h_language, known_german_quotes_languages))
1076 h_quotes_language = "german";
1078 else if (is_known(h_language, known_polish_quotes_languages))
1079 h_quotes_language = "polish";
1081 else if (is_known(h_language, known_swedish_quotes_languages))
1082 h_quotes_language = "swedish";
1084 else if (is_known(h_language, known_english_quotes_languages))
1085 h_quotes_language = "english";
1087 if (contains(h_float_placement, "H"))
1088 registerAutomaticallyLoadedPackage("float");
1089 if (h_spacing != "single" && h_spacing != "default")
1090 registerAutomaticallyLoadedPackage("setspace");
1091 if (h_use_packages["amsmath"] == "2") {
1092 // amsbsy and amstext are already provided by amsmath
1093 registerAutomaticallyLoadedPackage("amsbsy");
1094 registerAutomaticallyLoadedPackage("amstext");
1097 // output the LyX file settings
1098 // Important: Keep the version formatting in sync with LyX and
1099 // lyx2lyx (bug 7951)
1100 string const origin = roundtripMode() ? "roundtrip" : outfiledir;
1101 os << "#LyX file created by tex2lyx " << lyx_version_major << '.'
1102 << lyx_version_minor << '\n'
1103 << "\\lyxformat " << LYX_FORMAT << '\n'
1104 << "\\begin_document\n"
1105 << "\\begin_header\n"
1106 << "\\save_transient_properties " << h_save_transient_properties << "\n"
1107 << "\\origin " << origin << "\n"
1108 << "\\textclass " << h_textclass << "\n";
1109 string const raw = subdoc ? empty_string() : h_preamble.str();
1111 os << "\\begin_preamble\n";
1112 for (string::size_type i = 0; i < raw.size(); ++i) {
1113 if (raw[i] == package_beg_sep) {
1114 // Here follows some package loading code that
1115 // must be skipped if the package is loaded
1117 string::size_type j = raw.find(package_mid_sep, i);
1118 if (j == string::npos)
1120 string::size_type k = raw.find(package_end_sep, j);
1121 if (k == string::npos)
1123 string const package = raw.substr(i + 1, j - i - 1);
1124 string const replacement = raw.substr(j + 1, k - j - 1);
1125 if (auto_packages.find(package) == auto_packages.end())
1131 os << "\n\\end_preamble\n";
1133 if (!h_options.empty())
1134 os << "\\options " << h_options << "\n";
1135 os << "\\use_default_options " << h_use_default_options << "\n";
1136 if (!used_modules.empty()) {
1137 os << "\\begin_modules\n";
1138 vector<string>::const_iterator const end = used_modules.end();
1139 vector<string>::const_iterator it = used_modules.begin();
1140 for (; it != end; ++it)
1142 os << "\\end_modules\n";
1144 os << "\\maintain_unincluded_children " << h_maintain_unincluded_children << "\n"
1145 << "\\language " << h_language << "\n"
1146 << "\\language_package " << h_language_package << "\n"
1147 << "\\inputencoding " << h_inputencoding << "\n"
1148 << "\\fontencoding " << h_fontencoding << "\n"
1149 << "\\font_roman \"" << h_font_roman[0]
1150 << "\" \"" << h_font_roman[1] << "\"\n"
1151 << "\\font_sans \"" << h_font_sans[0] << "\" \"" << h_font_sans[1] << "\"\n"
1152 << "\\font_typewriter \"" << h_font_typewriter[0]
1153 << "\" \"" << h_font_typewriter[1] << "\"\n"
1154 << "\\font_math \"" << h_font_math[0] << "\" \"" << h_font_math[1] << "\"\n"
1155 << "\\font_default_family " << h_font_default_family << "\n"
1156 << "\\use_non_tex_fonts " << (h_use_non_tex_fonts ? "true" : "false") << '\n'
1157 << "\\font_sc " << h_font_sc << "\n"
1158 << "\\font_osf " << h_font_osf << "\n"
1159 << "\\font_sf_scale " << h_font_sf_scale[0]
1160 << ' ' << h_font_sf_scale[1] << '\n'
1161 << "\\font_tt_scale " << h_font_tt_scale[0]
1162 << ' ' << h_font_tt_scale[1] << '\n';
1163 if (!h_font_cjk.empty())
1164 os << "\\font_cjk " << h_font_cjk << '\n';
1165 os << "\\graphics " << h_graphics << '\n'
1166 << "\\default_output_format " << h_default_output_format << "\n"
1167 << "\\output_sync " << h_output_sync << "\n";
1168 if (h_output_sync == "1")
1169 os << "\\output_sync_macro \"" << h_output_sync_macro << "\"\n";
1170 os << "\\bibtex_command " << h_bibtex_command << "\n"
1171 << "\\index_command " << h_index_command << "\n";
1172 if (!h_float_placement.empty())
1173 os << "\\float_placement " << h_float_placement << "\n";
1174 os << "\\paperfontsize " << h_paperfontsize << "\n"
1175 << "\\spacing " << h_spacing << "\n"
1176 << "\\use_hyperref " << h_use_hyperref << '\n';
1177 if (h_use_hyperref == "true") {
1178 if (!h_pdf_title.empty())
1179 os << "\\pdf_title " << Lexer::quoteString(h_pdf_title) << '\n';
1180 if (!h_pdf_author.empty())
1181 os << "\\pdf_author " << Lexer::quoteString(h_pdf_author) << '\n';
1182 if (!h_pdf_subject.empty())
1183 os << "\\pdf_subject " << Lexer::quoteString(h_pdf_subject) << '\n';
1184 if (!h_pdf_keywords.empty())
1185 os << "\\pdf_keywords " << Lexer::quoteString(h_pdf_keywords) << '\n';
1186 os << "\\pdf_bookmarks " << h_pdf_bookmarks << "\n"
1187 "\\pdf_bookmarksnumbered " << h_pdf_bookmarksnumbered << "\n"
1188 "\\pdf_bookmarksopen " << h_pdf_bookmarksopen << "\n"
1189 "\\pdf_bookmarksopenlevel " << h_pdf_bookmarksopenlevel << "\n"
1190 "\\pdf_breaklinks " << h_pdf_breaklinks << "\n"
1191 "\\pdf_pdfborder " << h_pdf_pdfborder << "\n"
1192 "\\pdf_colorlinks " << h_pdf_colorlinks << "\n"
1193 "\\pdf_backref " << h_pdf_backref << "\n"
1194 "\\pdf_pdfusetitle " << h_pdf_pdfusetitle << '\n';
1195 if (!h_pdf_pagemode.empty())
1196 os << "\\pdf_pagemode " << h_pdf_pagemode << '\n';
1197 if (!h_pdf_quoted_options.empty())
1198 os << "\\pdf_quoted_options " << Lexer::quoteString(h_pdf_quoted_options) << '\n';
1200 os << "\\papersize " << h_papersize << "\n"
1201 << "\\use_geometry " << h_use_geometry << '\n';
1202 for (map<string, string>::const_iterator it = h_use_packages.begin();
1203 it != h_use_packages.end(); ++it)
1204 os << "\\use_package " << it->first << ' ' << it->second << '\n';
1205 os << "\\cite_engine " << h_cite_engine << '\n'
1206 << "\\cite_engine_type " << h_cite_engine_type << '\n'
1207 << "\\biblio_style " << h_biblio_style << "\n"
1208 << "\\use_bibtopic " << h_use_bibtopic << "\n"
1209 << "\\use_indices " << h_use_indices << "\n"
1210 << "\\paperorientation " << h_paperorientation << '\n'
1211 << "\\suppress_date " << h_suppress_date << '\n'
1212 << "\\justification " << h_justification << '\n'
1213 << "\\use_refstyle " << h_use_refstyle << '\n';
1214 if (!h_fontcolor.empty())
1215 os << "\\fontcolor " << h_fontcolor << '\n';
1216 if (!h_notefontcolor.empty())
1217 os << "\\notefontcolor " << h_notefontcolor << '\n';
1218 if (!h_backgroundcolor.empty())
1219 os << "\\backgroundcolor " << h_backgroundcolor << '\n';
1220 if (!h_boxbgcolor.empty())
1221 os << "\\boxbgcolor " << h_boxbgcolor << '\n';
1222 if (index_number != 0)
1223 for (int i = 0; i < index_number; i++) {
1224 os << "\\index " << h_index[i] << '\n'
1225 << "\\shortcut " << h_shortcut[i] << '\n'
1226 << "\\color " << h_color << '\n'
1230 os << "\\index " << h_index[0] << '\n'
1231 << "\\shortcut " << h_shortcut[0] << '\n'
1232 << "\\color " << h_color << '\n'
1236 << "\\secnumdepth " << h_secnumdepth << "\n"
1237 << "\\tocdepth " << h_tocdepth << "\n"
1238 << "\\paragraph_separation " << h_paragraph_separation << "\n";
1239 if (h_paragraph_separation == "skip")
1240 os << "\\defskip " << h_defskip << "\n";
1242 os << "\\paragraph_indentation " << h_paragraph_indentation << "\n";
1243 os << "\\quotes_language " << h_quotes_language << "\n"
1244 << "\\papercolumns " << h_papercolumns << "\n"
1245 << "\\papersides " << h_papersides << "\n"
1246 << "\\paperpagestyle " << h_paperpagestyle << "\n";
1247 if (!h_listings_params.empty())
1248 os << "\\listings_params " << h_listings_params << "\n";
1249 os << "\\tracking_changes " << h_tracking_changes << "\n"
1250 << "\\output_changes " << h_output_changes << "\n"
1251 << "\\html_math_output " << h_html_math_output << "\n"
1252 << "\\html_css_as_file " << h_html_css_as_file << "\n"
1253 << "\\html_be_strict " << h_html_be_strict << "\n"
1255 << "\\end_header\n\n"
1256 << "\\begin_body\n";
1261 void Preamble::parse(Parser & p, string const & forceclass,
1262 TeX2LyXDocClass & tc)
1264 // initialize fixed types
1265 special_columns_['D'] = 3;
1266 parse(p, forceclass, false, tc);
1270 void Preamble::parse(Parser & p, string const & forceclass,
1271 bool detectEncoding, TeX2LyXDocClass & tc)
1273 bool is_full_document = false;
1274 bool is_lyx_file = false;
1275 bool in_lyx_preamble = false;
1277 // determine whether this is a full document or a fragment for inclusion
1279 Token const & t = p.get_token();
1281 if (t.cat() == catEscape && t.cs() == "documentclass") {
1282 is_full_document = true;
1288 if (detectEncoding && !is_full_document)
1291 while (is_full_document && p.good()) {
1292 if (detectEncoding && h_inputencoding != "auto" &&
1293 h_inputencoding != "default")
1296 Token const & t = p.get_token();
1299 if (!detectEncoding)
1300 cerr << "t: " << t << '\n';
1306 if (!in_lyx_preamble &&
1307 (t.cat() == catLetter ||
1308 t.cat() == catSuper ||
1309 t.cat() == catSub ||
1310 t.cat() == catOther ||
1311 t.cat() == catMath ||
1312 t.cat() == catActive ||
1313 t.cat() == catBegin ||
1314 t.cat() == catEnd ||
1315 t.cat() == catAlign ||
1316 t.cat() == catParameter))
1317 h_preamble << t.cs();
1319 else if (!in_lyx_preamble &&
1320 (t.cat() == catSpace || t.cat() == catNewline))
1321 h_preamble << t.asInput();
1323 else if (t.cat() == catComment) {
1324 static regex const islyxfile("%% LyX .* created this file");
1325 static regex const usercommands("User specified LaTeX commands");
1327 string const comment = t.asInput();
1329 // magically switch encoding default if it looks like XeLaTeX
1330 static string const magicXeLaTeX =
1331 "% This document must be compiled with XeLaTeX ";
1332 if (comment.size() > magicXeLaTeX.size()
1333 && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
1334 && h_inputencoding == "auto") {
1335 if (!detectEncoding)
1336 cerr << "XeLaTeX comment found, switching to UTF8\n";
1337 h_inputencoding = "utf8";
1340 if (regex_search(comment, sub, islyxfile)) {
1342 in_lyx_preamble = true;
1343 } else if (is_lyx_file
1344 && regex_search(comment, sub, usercommands))
1345 in_lyx_preamble = false;
1346 else if (!in_lyx_preamble)
1347 h_preamble << t.asInput();
1350 else if (t.cs() == "pagestyle")
1351 h_paperpagestyle = p.verbatim_item();
1353 else if (t.cs() == "setdefaultlanguage") {
1355 // We don't yet care about non-language variant options
1356 // because LyX doesn't support this yet, see bug #8214
1358 string langopts = p.getOpt();
1359 // check if the option contains a variant, if yes, extract it
1360 string::size_type pos_var = langopts.find("variant");
1361 string::size_type i = langopts.find(',', pos_var);
1362 string::size_type k = langopts.find('=', pos_var);
1363 if (pos_var != string::npos){
1365 if (i == string::npos)
1366 variant = langopts.substr(k + 1, langopts.length() - k - 2);
1368 variant = langopts.substr(k + 1, i - k - 1);
1369 h_language = variant;
1373 h_language = p.verbatim_item();
1374 //finally translate the poyglossia name to a LyX name
1375 h_language = polyglossia2lyx(h_language);
1378 else if (t.cs() == "setotherlanguage") {
1379 // We don't yet care about the option because LyX doesn't
1380 // support this yet, see bug #8214
1381 p.hasOpt() ? p.getOpt() : string();
1385 else if (t.cs() == "setmainfont") {
1386 // we don't care about the option
1387 p.hasOpt() ? p.getOpt() : string();
1388 h_font_roman[1] = p.getArg('{', '}');
1391 else if (t.cs() == "setsansfont" || t.cs() == "setmonofont") {
1392 // LyX currently only supports the scale option
1395 string fontopts = p.getArg('[', ']');
1396 // check if the option contains a scaling, if yes, extract it
1397 string::size_type pos = fontopts.find("Scale");
1398 if (pos != string::npos) {
1399 string::size_type i = fontopts.find(',', pos);
1400 if (i == string::npos)
1401 scale_as_percentage(fontopts.substr(pos + 1), scale);
1403 scale_as_percentage(fontopts.substr(pos, i - pos), scale);
1406 if (t.cs() == "setsansfont") {
1408 h_font_sf_scale[1] = scale;
1409 h_font_sans[1] = p.getArg('{', '}');
1412 h_font_tt_scale[1] = scale;
1413 h_font_typewriter[1] = p.getArg('{', '}');
1417 else if (t.cs() == "date") {
1418 string argument = p.getArg('{', '}');
1419 if (argument.empty())
1420 h_suppress_date = "true";
1422 h_preamble << t.asInput() << '{' << argument << '}';
1425 else if (t.cs() == "color") {
1426 string const space =
1427 (p.hasOpt() ? p.getOpt() : string());
1428 string argument = p.getArg('{', '}');
1429 // check the case that a standard color is used
1430 if (space.empty() && is_known(argument, known_basic_colors)) {
1431 h_fontcolor = rgbcolor2code(argument);
1432 registerAutomaticallyLoadedPackage("color");
1433 } else if (space.empty() && argument == "document_fontcolor")
1434 registerAutomaticallyLoadedPackage("color");
1435 // check the case that LyX's document_fontcolor is defined
1436 // but not used for \color
1438 h_preamble << t.asInput();
1440 h_preamble << space;
1441 h_preamble << '{' << argument << '}';
1442 // the color might already be set because \definecolor
1443 // is parsed before this
1448 else if (t.cs() == "pagecolor") {
1449 string argument = p.getArg('{', '}');
1450 // check the case that a standard color is used
1451 if (is_known(argument, known_basic_colors)) {
1452 h_backgroundcolor = rgbcolor2code(argument);
1453 } else if (argument == "page_backgroundcolor")
1454 registerAutomaticallyLoadedPackage("color");
1455 // check the case that LyX's page_backgroundcolor is defined
1456 // but not used for \pagecolor
1458 h_preamble << t.asInput() << '{' << argument << '}';
1459 // the color might already be set because \definecolor
1460 // is parsed before this
1461 h_backgroundcolor = "";
1465 else if (t.cs() == "makeatletter") {
1466 // LyX takes care of this
1467 p.setCatcode('@', catLetter);
1470 else if (t.cs() == "makeatother") {
1471 // LyX takes care of this
1472 p.setCatcode('@', catOther);
1475 else if (t.cs() == "makeindex") {
1476 // LyX will re-add this if a print index command is found
1480 else if (t.cs() == "newindex") {
1481 string const indexname = p.getArg('[', ']');
1482 string const shortcut = p.verbatim_item();
1483 if (!indexname.empty())
1484 h_index[index_number] = indexname;
1486 h_index[index_number] = shortcut;
1487 h_shortcut[index_number] = shortcut;
1492 else if (t.cs() == "RS@ifundefined") {
1493 string const name = p.verbatim_item();
1494 string const body1 = p.verbatim_item();
1495 string const body2 = p.verbatim_item();
1496 // only non-lyxspecific stuff
1497 if (in_lyx_preamble &&
1498 (name == "subsecref" || name == "thmref" || name == "lemref"))
1502 ss << '\\' << t.cs();
1503 ss << '{' << name << '}'
1504 << '{' << body1 << '}'
1505 << '{' << body2 << '}';
1506 h_preamble << ss.str();
1510 else if (t.cs() == "AtBeginDocument") {
1511 string const name = p.verbatim_item();
1512 // only non-lyxspecific stuff
1513 if (in_lyx_preamble &&
1514 (name == "\\providecommand\\partref[1]{\\ref{part:#1}}"
1515 || name == "\\providecommand\\chapref[1]{\\ref{chap:#1}}"
1516 || name == "\\providecommand\\secref[1]{\\ref{sec:#1}}"
1517 || name == "\\providecommand\\subsecref[1]{\\ref{subsec:#1}}"
1518 || name == "\\providecommand\\parref[1]{\\ref{par:#1}}"
1519 || name == "\\providecommand\\figref[1]{\\ref{fig:#1}}"
1520 || name == "\\providecommand\\tabref[1]{\\ref{tab:#1}}"
1521 || name == "\\providecommand\\algref[1]{\\ref{alg:#1}}"
1522 || name == "\\providecommand\\fnref[1]{\\ref{fn:#1}}"
1523 || name == "\\providecommand\\enuref[1]{\\ref{enu:#1}}"
1524 || name == "\\providecommand\\eqref[1]{\\ref{eq:#1}}"
1525 || name == "\\providecommand\\lemref[1]{\\ref{lem:#1}}"
1526 || name == "\\providecommand\\thmref[1]{\\ref{thm:#1}}"
1527 || name == "\\providecommand\\corref[1]{\\ref{cor:#1}}"
1528 || name == "\\providecommand\\propref[1]{\\ref{prop:#1}}"))
1532 ss << '\\' << t.cs();
1533 ss << '{' << name << '}';
1534 h_preamble << ss.str();
1538 else if (t.cs() == "newcommand" || t.cs() == "newcommandx"
1539 || t.cs() == "renewcommand" || t.cs() == "renewcommandx"
1540 || t.cs() == "providecommand" || t.cs() == "providecommandx"
1541 || t.cs() == "DeclareRobustCommand"
1542 || t.cs() == "DeclareRobustCommandx"
1543 || t.cs() == "ProvideTextCommandDefault"
1544 || t.cs() == "DeclareMathAccent") {
1546 if (p.next_token().character() == '*') {
1550 string const name = p.verbatim_item();
1551 string const opt1 = p.getFullOpt();
1552 string const opt2 = p.getFullOpt();
1553 string const body = p.verbatim_item();
1554 // store the in_lyx_preamble setting
1555 bool const was_in_lyx_preamble = in_lyx_preamble;
1557 if (name == "\\rmdefault")
1558 if (is_known(body, known_roman_fonts)) {
1559 h_font_roman[0] = body;
1561 in_lyx_preamble = true;
1563 if (name == "\\sfdefault")
1564 if (is_known(body, known_sans_fonts)) {
1565 h_font_sans[0] = body;
1567 in_lyx_preamble = true;
1569 if (name == "\\ttdefault")
1570 if (is_known(body, known_typewriter_fonts)) {
1571 h_font_typewriter[0] = body;
1573 in_lyx_preamble = true;
1575 if (name == "\\familydefault") {
1576 string family = body;
1577 // remove leading "\"
1578 h_font_default_family = family.erase(0,1);
1580 in_lyx_preamble = true;
1583 // remove LyX-specific definitions that are re-added by LyX
1585 // \lyxline is an ancient command that is converted by tex2lyx into
1586 // a \rule therefore remove its preamble code
1587 if (name == "\\lyxdot" || name == "\\lyxarrow"
1588 || name == "\\lyxline" || name == "\\LyX") {
1590 in_lyx_preamble = true;
1593 // Add the command to the known commands
1594 add_known_command(name, opt1, !opt2.empty(), from_utf8(body));
1596 // only non-lyxspecific stuff
1597 if (!in_lyx_preamble) {
1599 ss << '\\' << t.cs();
1602 ss << '{' << name << '}' << opt1 << opt2
1603 << '{' << body << "}";
1604 h_preamble << ss.str();
1606 ostream & out = in_preamble ? h_preamble : os;
1607 out << "\\" << t.cs() << "{" << name << "}"
1608 << opts << "{" << body << "}";
1611 // restore the in_lyx_preamble setting
1612 in_lyx_preamble = was_in_lyx_preamble;
1615 else if (t.cs() == "documentclass") {
1616 vector<string>::iterator it;
1617 vector<string> opts = split_options(p.getArg('[', ']'));
1618 handle_opt(opts, known_fontsizes, h_paperfontsize);
1619 delete_opt(opts, known_fontsizes);
1620 // delete "pt" at the end
1621 string::size_type i = h_paperfontsize.find("pt");
1622 if (i != string::npos)
1623 h_paperfontsize.erase(i);
1624 // The documentclass options are always parsed before the options
1625 // of the babel call so that a language cannot overwrite the babel
1627 handle_opt(opts, known_languages, h_language);
1628 delete_opt(opts, known_languages);
1630 // paper orientation
1631 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
1632 h_paperorientation = "landscape";
1636 if ((it = find(opts.begin(), opts.end(), "oneside"))
1641 if ((it = find(opts.begin(), opts.end(), "twoside"))
1647 if ((it = find(opts.begin(), opts.end(), "onecolumn"))
1649 h_papercolumns = "1";
1652 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
1654 h_papercolumns = "2";
1658 // some size options are known to any document classes, other sizes
1659 // are handled by the \geometry command of the geometry package
1660 handle_opt(opts, known_class_paper_sizes, h_papersize);
1661 delete_opt(opts, known_class_paper_sizes);
1662 // the remaining options
1663 h_options = join(opts, ",");
1664 // FIXME This does not work for classes that have a
1665 // different name in LyX than in LaTeX
1666 h_textclass = p.getArg('{', '}');
1670 else if (t.cs() == "usepackage") {
1671 string const options = p.getArg('[', ']');
1672 string const name = p.getArg('{', '}');
1673 vector<string> vecnames;
1674 split(name, vecnames, ',');
1675 vector<string>::const_iterator it = vecnames.begin();
1676 vector<string>::const_iterator end = vecnames.end();
1677 for (; it != end; ++it)
1678 handle_package(p, trimSpaceAndEol(*it), options,
1679 in_lyx_preamble, detectEncoding);
1682 else if (t.cs() == "inputencoding") {
1683 string const encoding = p.getArg('{','}');
1684 Encoding const * const enc = encodings.fromLaTeXName(
1685 encoding, Encoding::inputenc, true);
1687 if (!detectEncoding)
1688 cerr << "Unknown encoding " << encoding
1689 << ". Ignoring." << std::endl;
1692 h_inputencoding = enc->name();
1693 p.setEncoding(enc->iconvName());
1697 else if (t.cs() == "newenvironment") {
1698 string const name = p.getArg('{', '}');
1699 string const opt1 = p.getFullOpt();
1700 string const opt2 = p.getFullOpt();
1701 string const beg = p.verbatim_item();
1702 string const end = p.verbatim_item();
1703 if (!in_lyx_preamble) {
1704 h_preamble << "\\newenvironment{" << name
1705 << '}' << opt1 << opt2 << '{'
1706 << beg << "}{" << end << '}';
1708 add_known_environment(name, opt1, !opt2.empty(),
1709 from_utf8(beg), from_utf8(end));
1713 else if (t.cs() == "newtheorem") {
1714 string const name = p.getArg('{', '}');
1715 string const opt1 = p.getFullOpt();
1716 string const opt2 = p.getFullOpt();
1717 string const body = p.verbatim_item();
1718 string const opt3 = p.getFullOpt();
1720 string const complete = "\\newtheorem{" + name + '}' +
1721 opt1 + opt2 + '{' + body + '}' + opt3;
1723 add_known_theorem(name, opt1, !opt2.empty(), from_utf8(complete));
1725 if (!in_lyx_preamble)
1726 h_preamble << complete;
1729 else if (t.cs() == "def") {
1730 string name = p.get_token().cs();
1731 // In fact, name may be more than the name:
1732 // In the test case of bug 8116
1733 // name == "csname SF@gobble@opt \endcsname".
1734 // Therefore, we need to use asInput() instead of cs().
1735 while (p.next_token().cat() != catBegin)
1736 name += p.get_token().asInput();
1737 if (!in_lyx_preamble)
1738 h_preamble << "\\def\\" << name << '{'
1739 << p.verbatim_item() << "}";
1742 else if (t.cs() == "newcolumntype") {
1743 string const name = p.getArg('{', '}');
1744 trimSpaceAndEol(name);
1746 string opts = p.getOpt();
1747 if (!opts.empty()) {
1748 istringstream is(string(opts, 1));
1751 special_columns_[name[0]] = nargs;
1752 h_preamble << "\\newcolumntype{" << name << "}";
1754 h_preamble << "[" << nargs << "]";
1755 h_preamble << "{" << p.verbatim_item() << "}";
1758 else if (t.cs() == "setcounter") {
1759 string const name = p.getArg('{', '}');
1760 string const content = p.getArg('{', '}');
1761 if (name == "secnumdepth")
1762 h_secnumdepth = content;
1763 else if (name == "tocdepth")
1764 h_tocdepth = content;
1766 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
1769 else if (t.cs() == "setlength") {
1770 string const name = p.verbatim_item();
1771 string const content = p.verbatim_item();
1772 // the paragraphs are only not indented when \parindent is set to zero
1773 if (name == "\\parindent" && content != "") {
1774 if (content[0] == '0')
1775 h_paragraph_separation = "skip";
1777 h_paragraph_indentation = translate_len(content);
1778 } else if (name == "\\parskip") {
1779 if (content == "\\smallskipamount")
1780 h_defskip = "smallskip";
1781 else if (content == "\\medskipamount")
1782 h_defskip = "medskip";
1783 else if (content == "\\bigskipamount")
1784 h_defskip = "bigskip";
1786 h_defskip = translate_len(content);
1788 h_preamble << "\\setlength{" << name << "}{" << content << "}";
1791 else if (t.cs() == "onehalfspacing")
1792 h_spacing = "onehalf";
1794 else if (t.cs() == "doublespacing")
1795 h_spacing = "double";
1797 else if (t.cs() == "setstretch")
1798 h_spacing = "other " + p.verbatim_item();
1800 else if (t.cs() == "synctex") {
1801 // the scheme is \synctex=value
1802 // where value can only be "1" or "-1"
1803 h_output_sync = "1";
1804 // there can be any character behind the value (e.g. a linebreak or a '\'
1805 // therefore we extract it char by char
1807 string value = p.get_token().asInput();
1809 value += p.get_token().asInput();
1810 h_output_sync_macro = "\\synctex=" + value;
1813 else if (t.cs() == "begin") {
1814 string const name = p.getArg('{', '}');
1815 if (name == "document")
1817 h_preamble << "\\begin{" << name << "}";
1820 else if (t.cs() == "geometry") {
1821 vector<string> opts = split_options(p.getArg('{', '}'));
1822 handle_geometry(opts);
1825 else if (t.cs() == "definecolor") {
1826 string const color = p.getArg('{', '}');
1827 string const space = p.getArg('{', '}');
1828 string const value = p.getArg('{', '}');
1829 if (color == "document_fontcolor" && space == "rgb") {
1830 RGBColor c(RGBColorFromLaTeX(value));
1831 h_fontcolor = X11hexname(c);
1832 } else if (color == "note_fontcolor" && space == "rgb") {
1833 RGBColor c(RGBColorFromLaTeX(value));
1834 h_notefontcolor = X11hexname(c);
1835 } else if (color == "page_backgroundcolor" && space == "rgb") {
1836 RGBColor c(RGBColorFromLaTeX(value));
1837 h_backgroundcolor = X11hexname(c);
1838 } else if (color == "shadecolor" && space == "rgb") {
1839 RGBColor c(RGBColorFromLaTeX(value));
1840 h_boxbgcolor = X11hexname(c);
1842 h_preamble << "\\definecolor{" << color
1843 << "}{" << space << "}{" << value
1848 else if (t.cs() == "bibliographystyle")
1849 h_biblio_style = p.verbatim_item();
1851 else if (t.cs() == "jurabibsetup") {
1852 // FIXME p.getArg('{', '}') is most probably wrong (it
1853 // does not handle nested braces).
1854 // Use p.verbatim_item() instead.
1855 vector<string> jurabibsetup =
1856 split_options(p.getArg('{', '}'));
1857 // add jurabibsetup to the jurabib package options
1858 add_package("jurabib", jurabibsetup);
1859 if (!jurabibsetup.empty()) {
1860 h_preamble << "\\jurabibsetup{"
1861 << join(jurabibsetup, ",") << '}';
1865 else if (t.cs() == "hypersetup") {
1866 vector<string> hypersetup =
1867 split_options(p.verbatim_item());
1868 // add hypersetup to the hyperref package options
1869 handle_hyperref(hypersetup);
1870 if (!hypersetup.empty()) {
1871 h_preamble << "\\hypersetup{"
1872 << join(hypersetup, ",") << '}';
1876 else if (is_known(t.cs(), known_if_3arg_commands)) {
1877 // prevent misparsing of \usepackage if it is used
1878 // as an argument (see e.g. our own output of
1879 // \@ifundefined above)
1880 string const arg1 = p.verbatim_item();
1881 string const arg2 = p.verbatim_item();
1882 string const arg3 = p.verbatim_item();
1883 // test case \@ifundefined{date}{}{\date{}}
1884 if (t.cs() == "@ifundefined" && arg1 == "date" &&
1885 arg2.empty() && arg3 == "\\date{}") {
1886 h_suppress_date = "true";
1887 // older tex2lyx versions did output
1888 // \@ifundefined{definecolor}{\usepackage{color}}{}
1889 } else if (t.cs() == "@ifundefined" &&
1890 arg1 == "definecolor" &&
1891 arg2 == "\\usepackage{color}" &&
1893 if (!in_lyx_preamble)
1894 h_preamble << package_beg_sep
1897 << "\\@ifundefined{definecolor}{color}{}"
1900 //\@ifundefined{showcaptionsetup}{}{%
1901 // \PassOptionsToPackage{caption=false}{subfig}}
1902 // that LyX uses for subfloats
1903 } else if (t.cs() == "@ifundefined" &&
1904 arg1 == "showcaptionsetup" && arg2.empty()
1905 && arg3 == "%\n \\PassOptionsToPackage{caption=false}{subfig}") {
1907 } else if (!in_lyx_preamble) {
1908 h_preamble << t.asInput()
1909 << '{' << arg1 << '}'
1910 << '{' << arg2 << '}'
1911 << '{' << arg3 << '}';
1915 else if (is_known(t.cs(), known_if_commands)) {
1916 // must not parse anything in conditional code, since
1917 // LyX would output the parsed contents unconditionally
1918 if (!in_lyx_preamble)
1919 h_preamble << t.asInput();
1920 handle_if(p, in_lyx_preamble);
1923 else if (!t.cs().empty() && !in_lyx_preamble)
1924 h_preamble << '\\' << t.cs();
1927 // remove the whitespace
1930 // Force textclass if the user wanted it
1931 if (!forceclass.empty())
1932 h_textclass = forceclass;
1933 tc.setName(h_textclass);
1935 cerr << "Error: Could not read layout file for textclass \"" << h_textclass << "\"." << endl;
1938 if (h_papersides.empty()) {
1941 h_papersides = ss.str();
1944 // If the CJK package is used we cannot set the document language from
1945 // the babel options. Instead, we guess which language is used most
1946 // and set this one.
1947 default_language = h_language;
1948 if (is_full_document &&
1949 (auto_packages.find("CJK") != auto_packages.end() ||
1950 auto_packages.find("CJKutf8") != auto_packages.end())) {
1952 h_language = guessLanguage(p, default_language);
1954 if (explicit_babel && h_language != default_language) {
1955 // We set the document language to a CJK language,
1956 // but babel is explicitly called in the user preamble
1957 // without options. LyX will not add the default
1958 // language to the document options if it is either
1959 // english, or no text is set as default language.
1960 // Therefore we need to add a language option explicitly.
1961 // FIXME: It would be better to remove all babel calls
1962 // from the user preamble, but this is difficult
1963 // without re-introducing bug 7861.
1964 if (h_options.empty())
1965 h_options = lyx2babel(default_language);
1967 h_options += ',' + lyx2babel(default_language);
1973 string Preamble::parseEncoding(Parser & p, string const & forceclass)
1975 TeX2LyXDocClass dummy;
1976 parse(p, forceclass, true, dummy);
1977 if (h_inputencoding != "auto" && h_inputencoding != "default")
1978 return h_inputencoding;
1983 string babel2lyx(string const & language)
1985 char const * const * where = is_known(language, known_languages);
1987 return known_coded_languages[where - known_languages];
1992 string lyx2babel(string const & language)
1994 char const * const * where = is_known(language, known_coded_languages);
1996 return known_languages[where - known_coded_languages];
2001 string Preamble::polyglossia2lyx(string const & language)
2003 char const * const * where = is_known(language, polyglossia_languages);
2005 return coded_polyglossia_languages[where - polyglossia_languages];
2010 string rgbcolor2code(string const & name)
2012 char const * const * where = is_known(name, known_basic_colors);
2014 // "red", "green" etc
2015 return known_basic_color_codes[where - known_basic_colors];
2017 // "255,0,0", "0,255,0" etc
2018 RGBColor c(RGBColorFromLaTeX(name));
2019 return X11hexname(c);