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.
19 #include "LayoutFile.h"
22 #include "TextClass.h"
24 #include "support/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/lstrings.h"
29 #include "support/regex.h"
35 using namespace lyx::support;
40 // special columntypes
41 extern map<char, int> special_columns;
47 // "chinese-simplified", "chinese-traditional", "japanese-cjk", "korean"
48 // cannot be supported because it is impossible to determine the correct document
49 // language if CJK is used.
51 * known babel language names (including synonyms)
52 * not in standard babel: arabic, arabtex, armenian, belarusian, serbian-latin, thai
53 * please keep this in sync with known_coded_languages line by line!
55 const char * const known_languages[] = {"acadian", "afrikaans", "albanian",
56 "american", "arabic", "arabtex", "australian", "austrian", "bahasa", "bahasai",
57 "bahasam", "basque", "belarusian", "brazil", "brazilian", "breton", "british",
58 "bulgarian", "canadian", "canadien", "catalan", "croatian", "czech", "danish",
59 "dutch", "english", "esperanto", "estonian", "farsi", "finnish", "francais",
60 "french", "frenchb", "frenchle", "frenchpro", "galician", "german", "germanb",
61 "greek", "hebrew", "hungarian", "icelandic", "indon", "indonesian", "interlingua",
62 "irish", "italian", "japanese", "kazakh", "kurmanji", "latin", "latvian", "lithuanian",
63 "lowersorbian", "lsorbian", "magyar", "malay", "meyalu", "mongolian", "naustrian",
64 "newzealand", "ngerman", "ngermanb", "norsk", "nynorsk", "polutonikogreek", "polish",
65 "portuges", "portuguese", "romanian", "russian", "russianb", "samin",
66 "scottish", "serbian", "serbian-latin", "slovak", "slovene", "spanish",
67 "swedish", "thai", "turkish", "turkmen", "ukraineb", "ukrainian",
68 "uppersorbian", "UKenglish", "USenglish", "usorbian", "vietnam", "welsh",
72 * the same as known_languages with .lyx names
73 * please keep this in sync with known_languages line by line!
75 const char * const known_coded_languages[] = {"french", "afrikaans", "albanian",
76 "american", "arabic_arabi", "arabic_arabtex", "australian", "austrian", "bahasa", "bahasa",
77 "bahasam", "basque", "belarusian", "brazilian", "brazilian", "breton", "british",
78 "bulgarian", "canadian", "canadien", "catalan", "croatian", "czech", "danish",
79 "dutch", "english", "esperanto", "estonian", "farsi", "finnish", "french",
80 "french", "french", "french", "french", "galician", "german", "german",
81 "greek", "hebrew", "magyar", "icelandic", "bahasa", "bahasa", "interlingua",
82 "irish", "italian", "japanese", "kazakh", "kurmanji", "latin", "latvian", "lithuanian",
83 "lowersorbian", "lowersorbian", "magyar", "bahasam", "bahasam", "mongolian", "naustrian",
84 "newzealand", "ngerman", "ngerman", "norsk", "nynorsk", "polutonikogreek", "polish",
85 "portuguese", "portuguese", "romanian", "russian", "russian", "samin",
86 "scottish", "serbian", "serbian-latin", "slovak", "slovene", "spanish",
87 "swedish", "thai", "turkish", "turkmen", "ukrainian", "ukrainian",
88 "uppersorbian", "uppersorbian", "english", "english", "vietnamese", "welsh",
91 /// languages with english quotes (.lyx names)
92 const char * const known_english_quotes_languages[] = {"american", "australian",
93 "bahasa", "bahasam", "brazilian", "canadian", "chinese-simplified", "english",
94 "esperanto", "hebrew", "irish", "korean", "newzealand", "portuguese", "scottish",
97 /// languages with french quotes (.lyx names)
98 const char * const known_french_quotes_languages[] = {"albanian",
99 "arabic_arabi", "arabic_arabtex", "basque", "canadien", "catalan", "french",
100 "galician", "greek", "italian", "norsk", "nynorsk", "polutonikogreek",
101 "russian", "spanish", "spanish-mexico", "turkish", "turkmen", "ukrainian",
104 /// languages with german quotes (.lyx names)
105 const char * const known_german_quotes_languages[] = {"austrian", "bulgarian",
106 "czech", "german", "icelandic", "lithuanian", "lowersorbian", "naustrian",
107 "ngerman", "serbian", "serbian-latin", "slovak", "slovene", "uppersorbian", 0};
109 /// languages with polish quotes (.lyx names)
110 const char * const known_polish_quotes_languages[] = {"afrikaans", "croatian",
111 "dutch", "estonian", "magyar", "polish", "romanian", 0};
113 /// languages with swedish quotes (.lyx names)
114 const char * const known_swedish_quotes_languages[] = {"finnish",
117 /// known language packages from the times before babel
118 const char * const known_old_language_packages[] = {"french", "frenchle",
119 "frenchpro", "german", "ngerman", "pmfrench", 0};
121 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
123 const char * const known_roman_fonts[] = { "ae", "beraserif", "bookman",
124 "ccfonts", "chancery", "charter", "cmr", "fourier", "lmodern", "mathpazo",
125 "mathptmx", "newcent", "utopia", 0};
127 const char * const known_sans_fonts[] = { "avant", "berasans", "cmbr", "cmss",
128 "helvet", "lmss", 0};
130 const char * const known_typewriter_fonts[] = { "beramono", "cmtl", "cmtt",
131 "courier", "lmtt", "luximono", "fourier", "lmodern", "mathpazo", "mathptmx",
134 const char * const known_paper_sizes[] = { "a0paper", "b0paper", "c0paper",
135 "a1paper", "b1paper", "c1paper", "a2paper", "b2paper", "c2paper", "a3paper",
136 "b3paper", "c3paper", "a4paper", "b4paper", "c4paper", "a5paper", "b5paper",
137 "c5paper", "a6paper", "b6paper", "c6paper", "executivepaper", "legalpaper",
138 "letterpaper", "b0j", "b1j", "b2j", "b3j", "b4j", "b5j", "b6j", 0};
140 const char * const known_class_paper_sizes[] = { "a4paper", "a5paper",
141 "executivepaper", "legalpaper", "letterpaper", 0};
143 const char * const known_paper_margins[] = { "lmargin", "tmargin", "rmargin",
144 "bmargin", "headheight", "headsep", "footskip", "columnsep", 0};
146 const char * const known_coded_paper_margins[] = { "leftmargin", "topmargin",
147 "rightmargin", "bottommargin", "headheight", "headsep", "footskip",
150 /// commands that can start an \if...\else...\endif sequence
151 const char * const known_if_commands[] = {"if", "ifarydshln", "ifbraket",
152 "ifcancel", "ifcolortbl", "ifeurosym", "ifmarginnote", "ifmmode", "ifpdf",
153 "ifsidecap", "ifupgreek", 0};
155 const char * const known_basic_colors[] = {"blue", "black", "cyan", "green",
156 "magenta", "red", "white", "yellow", 0};
158 const char * const known_basic_color_codes[] = {"#0000ff", "#000000", "#00ffff", "#00ff00",
159 "#ff00ff", "#ff0000", "#ffffff", "#ffff00", 0};
161 /// conditional commands with three arguments like \@ifundefined{}{}{}
162 const char * const known_if_3arg_commands[] = {"@ifundefined", "IfFileExists",
165 /// packages that work only in xetex
166 /// polyglossia is handled separately
167 const char * const known_xetex_packages[] = {"arabxetex", "fixlatvian",
168 "fontbook", "fontwrap", "mathspec", "philokalia", "unisugar",
169 "xeCJK", "xecolor", "xecyr", "xeindex", "xepersian", "xunicode", 0};
171 /// packages that are automatically skipped if loaded by LyX
172 const char * const known_lyx_packages[] = {"amsbsy", "amsmath", "amssymb",
173 "amstext", "amsthm", "array", "babel", "booktabs", "calc", "CJK", "color", "float",
174 "fontspec", "graphicx", "hhline", "ifthen", "longtable", "makeidx", "multirow",
175 "nomencl", "pdfpages", "rotating", "rotfloat", "splitidx", "setspace",
176 "subscript", "textcomp", "ulem", "url", "varioref", "verbatim", "wrapfig",
179 // codes used to remove packages that are loaded automatically by LyX.
180 // Syntax: package_beg_sep<name>package_mid_sep<package loading code>package_end_sep
181 const char package_beg_sep = '\001';
182 const char package_mid_sep = '\002';
183 const char package_end_sep = '\003';
186 // returns true if at least one of the options in what has been found
187 bool handle_opt(vector<string> & opts, char const * const * what, string & target)
193 // the last language option is the document language (for babel and LyX)
194 // the last size option is the document font size
195 vector<string>::iterator it;
196 vector<string>::iterator position = opts.begin();
197 for (; *what; ++what) {
198 it = find(opts.begin(), opts.end(), *what);
199 if (it != opts.end()) {
200 if (it >= position) {
211 void delete_opt(vector<string> & opts, char const * const * what)
216 // remove found options from the list
217 // do this after handle_opt to avoid potential memory leaks
218 vector<string>::iterator it;
219 for (; *what; ++what) {
220 it = find(opts.begin(), opts.end(), *what);
221 if (it != opts.end())
228 * Split a package options string (keyval format) into a vector.
230 * authorformat=smallcaps,
232 * titleformat=colonsep,
233 * bibformat={tabular,ibidem,numbered}
235 vector<string> split_options(string const & input)
237 vector<string> options;
241 Token const & t = p.get_token();
242 if (t.asInput() == ",") {
243 options.push_back(trimSpaceAndEol(option));
245 } else if (t.asInput() == "=") {
248 if (p.next_token().asInput() == "{")
249 option += '{' + p.getArg('{', '}') + '}';
250 } else if (t.cat() != catSpace)
251 option += t.asInput();
255 options.push_back(trimSpaceAndEol(option));
262 * Retrieve a keyval option "name={value with=sign}" named \p name from
263 * \p options and return the value.
264 * The found option is also removed from \p options.
266 string process_keyval_opt(vector<string> & options, string name)
268 for (size_t i = 0; i < options.size(); ++i) {
269 vector<string> option;
270 split(options[i], option, '=');
271 if (option.size() < 2)
273 if (option[0] == name) {
274 options.erase(options.begin() + i);
275 option.erase(option.begin());
276 return join(option, "=");
282 } // anonymous namespace
286 * known polyglossia language names (including variants)
288 const char * const Preamble::polyglossia_languages[] = {
289 "albanian", "croatian", "hebrew", "norsk", "swedish", "amharic", "czech", "hindi",
290 "nynorsk", "syriac", "arabic", "danish", "icelandic", "occitan", "tamil",
291 "armenian", "divehi", "interlingua", "polish", "telugu", "asturian", "dutch",
292 "irish", "portuges", "thai", "bahasai", "english", "italian", "romanian", "turkish",
293 "bahasam", "esperanto", "lao", "russian", "turkmen", "basque", "estonian", "latin",
294 "samin", "ukrainian", "bengali", "farsi", "latvian", "sanskrit", "urdu", "brazil",
295 "brazilian", "finnish", "lithuanian", "scottish", "usorbian", "breton", "french",
296 "lsorbian", "serbian", "vietnamese", "bulgarian", "galician", "magyar", "slovak",
297 "welsh", "catalan", "german", "malayalam", "slovenian", "coptic", "greek",
298 "marathi", "spanish",
299 "american", "ancient", "australian", "british", "monotonic", "newzealand",
303 * the same as polyglossia_languages with .lyx names
304 * please keep this in sync with polyglossia_languages line by line!
306 const char * const Preamble::coded_polyglossia_languages[] = {
307 "albanian", "croatian", "hebrew", "norsk", "swedish", "amharic", "czech", "hindi",
308 "nynorsk", "syriac", "arabic_arabi", "danish", "icelandic", "occitan", "tamil",
309 "armenian", "divehi", "interlingua", "polish", "telugu", "asturian", "dutch",
310 "irish", "portuges", "thai", "bahasa", "english", "italian", "romanian", "turkish",
311 "bahasam", "esperanto", "lao", "russian", "turkmen", "basque", "estonian", "latin",
312 "samin", "ukrainian", "bengali", "farsi", "latvian", "sanskrit", "urdu", "brazilian",
313 "brazilian", "finnish", "lithuanian", "scottish", "uppersorbian", "breton", "french",
314 "lowersorbian", "serbian", "vietnamese", "bulgarian", "galician", "magyar", "slovak",
315 "welsh", "catalan", "ngerman", "malayalam", "slovene", "coptic", "greek",
316 "marathi", "spanish",
317 "american", "ancientgreek", "australian", "british", "greek", "newzealand",
318 "polutonikogreek", 0};
321 bool Preamble::indentParagraphs() const
323 return h_paragraph_separation == "indent";
327 bool Preamble::isPackageUsed(string const & package) const
329 return used_packages.find(package) != used_packages.end();
333 vector<string> Preamble::getPackageOptions(string const & package) const
335 map<string, vector<string> >::const_iterator it = used_packages.find(package);
336 if (it != used_packages.end())
338 return vector<string>();
342 void Preamble::registerAutomaticallyLoadedPackage(std::string const & package)
344 auto_packages.insert(package);
348 void Preamble::addModule(string const & module)
350 used_modules.push_back(module);
354 void Preamble::suppressDate(bool suppress)
357 h_suppress_date = "true";
359 h_suppress_date = "false";
363 void Preamble::registerAuthor(std::string const & name)
365 Author author(from_utf8(name), empty_docstring());
366 author.setUsed(true);
367 authors_.record(author);
368 h_tracking_changes = "true";
369 h_output_changes = "true";
373 Author const & Preamble::getAuthor(std::string const & name) const
375 Author author(from_utf8(name), empty_docstring());
376 for (AuthorList::Authors::const_iterator it = authors_.begin();
377 it != authors_.end(); ++it)
380 static Author const dummy;
385 void Preamble::add_package(string const & name, vector<string> & options)
387 // every package inherits the global options
388 if (used_packages.find(name) == used_packages.end())
389 used_packages[name] = split_options(h_options);
391 vector<string> & v = used_packages[name];
392 v.insert(v.end(), options.begin(), options.end());
393 if (name == "jurabib") {
394 // Don't output the order argument (see the cite command
395 // handling code in text.cpp).
396 vector<string>::iterator end =
397 remove(options.begin(), options.end(), "natbiborder");
398 end = remove(options.begin(), end, "jurabiborder");
399 options.erase(end, options.end());
406 // Given is a string like "scaled=0.9", return 0.9 * 100
407 string const scale_as_percentage(string const & scale)
409 string::size_type pos = scale.find('=');
410 if (pos != string::npos) {
411 string value = scale.substr(pos + 1);
413 return convert<string>(100 * convert<double>(value));
415 // If the input string didn't match our expectations.
416 // return the default value "100"
421 string remove_braces(string const & value)
425 if (value[0] == '{' && value[value.length()-1] == '}')
426 return value.substr(1, value.length()-2);
430 } // anonymous namespace
433 Preamble::Preamble() : one_language(true), title_layout_found(false)
437 h_biblio_style = "plain";
438 h_bibtex_command = "default";
439 h_cite_engine = "basic";
440 h_cite_engine_type = "numerical";
442 h_defskip = "medskip";
445 h_fontencoding = "default";
446 h_font_roman = "default";
447 h_font_sans = "default";
448 h_font_typewriter = "default";
449 h_font_math = "auto";
450 h_font_default_family = "default";
451 h_use_non_tex_fonts = "false";
453 h_font_osf = "false";
454 h_font_sf_scale = "100";
455 h_font_tt_scale = "100";
456 h_graphics = "default";
457 h_default_output_format = "default";
458 h_html_be_strict = "false";
459 h_html_css_as_file = "0";
460 h_html_math_output = "0";
462 h_index_command = "default";
463 h_inputencoding = "auto";
464 h_justification = "true";
465 h_language = "english";
466 h_language_package = "none";
468 h_maintain_unincluded_children = "false";
472 h_output_changes = "false";
474 //h_output_sync_macro
475 h_papercolumns = "1";
476 h_paperfontsize = "default";
477 h_paperorientation = "portrait";
478 h_paperpagestyle = "default";
480 h_papersize = "default";
481 h_paragraph_indentation = "default";
482 h_paragraph_separation = "indent";
487 h_pdf_bookmarks = "1";
488 h_pdf_bookmarksnumbered = "0";
489 h_pdf_bookmarksopen = "0";
490 h_pdf_bookmarksopenlevel = "1";
491 h_pdf_breaklinks = "0";
492 h_pdf_pdfborder = "0";
493 h_pdf_colorlinks = "0";
494 h_pdf_backref = "section";
495 h_pdf_pdfusetitle = "1";
497 //h_pdf_quoted_options;
498 h_quotes_language = "english";
501 h_spacing = "single";
502 h_suppress_date = "false";
503 h_textclass = "article";
505 h_tracking_changes = "false";
506 h_use_bibtopic = "false";
507 h_use_indices = "false";
508 h_use_geometry = "false";
509 h_use_default_options = "false";
510 h_use_hyperref = "false";
511 h_use_refstyle = "0";
512 h_use_packages["amsmath"] = "1";
513 h_use_packages["amssymb"] = "0";
514 h_use_packages["esint"] = "1";
515 h_use_packages["mhchem"] = "0";
516 h_use_packages["mathdots"] = "0";
517 h_use_packages["mathtools"] = "0";
518 h_use_packages["undertilde"] = "0";
522 void Preamble::handle_hyperref(vector<string> & options)
524 // FIXME swallow inputencoding changes that might surround the
525 // hyperref setup if it was written by LyX
526 h_use_hyperref = "true";
527 // swallow "unicode=true", since LyX does always write that
528 vector<string>::iterator it =
529 find(options.begin(), options.end(), "unicode=true");
530 if (it != options.end())
532 it = find(options.begin(), options.end(), "pdfusetitle");
533 if (it != options.end()) {
534 h_pdf_pdfusetitle = "1";
537 string bookmarks = process_keyval_opt(options, "bookmarks");
538 if (bookmarks == "true")
539 h_pdf_bookmarks = "1";
540 else if (bookmarks == "false")
541 h_pdf_bookmarks = "0";
542 if (h_pdf_bookmarks == "1") {
543 string bookmarksnumbered =
544 process_keyval_opt(options, "bookmarksnumbered");
545 if (bookmarksnumbered == "true")
546 h_pdf_bookmarksnumbered = "1";
547 else if (bookmarksnumbered == "false")
548 h_pdf_bookmarksnumbered = "0";
549 string bookmarksopen =
550 process_keyval_opt(options, "bookmarksopen");
551 if (bookmarksopen == "true")
552 h_pdf_bookmarksopen = "1";
553 else if (bookmarksopen == "false")
554 h_pdf_bookmarksopen = "0";
555 if (h_pdf_bookmarksopen == "1") {
556 string bookmarksopenlevel =
557 process_keyval_opt(options, "bookmarksopenlevel");
558 if (!bookmarksopenlevel.empty())
559 h_pdf_bookmarksopenlevel = bookmarksopenlevel;
562 string breaklinks = process_keyval_opt(options, "breaklinks");
563 if (breaklinks == "true")
564 h_pdf_breaklinks = "1";
565 else if (breaklinks == "false")
566 h_pdf_breaklinks = "0";
567 string pdfborder = process_keyval_opt(options, "pdfborder");
568 if (pdfborder == "{0 0 0}")
569 h_pdf_pdfborder = "1";
570 else if (pdfborder == "{0 0 1}")
571 h_pdf_pdfborder = "0";
572 string backref = process_keyval_opt(options, "backref");
573 if (!backref.empty())
574 h_pdf_backref = backref;
575 string colorlinks = process_keyval_opt(options, "colorlinks");
576 if (colorlinks == "true")
577 h_pdf_colorlinks = "1";
578 else if (colorlinks == "false")
579 h_pdf_colorlinks = "0";
580 string pdfpagemode = process_keyval_opt(options, "pdfpagemode");
581 if (!pdfpagemode.empty())
582 h_pdf_pagemode = pdfpagemode;
583 string pdftitle = process_keyval_opt(options, "pdftitle");
584 if (!pdftitle.empty()) {
585 h_pdf_title = remove_braces(pdftitle);
587 string pdfauthor = process_keyval_opt(options, "pdfauthor");
588 if (!pdfauthor.empty()) {
589 h_pdf_author = remove_braces(pdfauthor);
591 string pdfsubject = process_keyval_opt(options, "pdfsubject");
592 if (!pdfsubject.empty())
593 h_pdf_subject = remove_braces(pdfsubject);
594 string pdfkeywords = process_keyval_opt(options, "pdfkeywords");
595 if (!pdfkeywords.empty())
596 h_pdf_keywords = remove_braces(pdfkeywords);
597 if (!options.empty()) {
598 if (!h_pdf_quoted_options.empty())
599 h_pdf_quoted_options += ',';
600 h_pdf_quoted_options += join(options, ",");
606 void Preamble::handle_geometry(vector<string> & options)
608 h_use_geometry = "true";
609 vector<string>::iterator it;
611 if ((it = find(options.begin(), options.end(), "landscape")) != options.end()) {
612 h_paperorientation = "landscape";
616 // keyval version: "paper=letter"
617 string paper = process_keyval_opt(options, "paper");
619 h_papersize = paper + "paper";
620 // alternative version: "letterpaper"
621 handle_opt(options, known_paper_sizes, h_papersize);
622 delete_opt(options, known_paper_sizes);
624 char const * const * margin = known_paper_margins;
625 for (; *margin; ++margin) {
626 string value = process_keyval_opt(options, *margin);
627 if (!value.empty()) {
628 int k = margin - known_paper_margins;
629 string name = known_coded_paper_margins[k];
630 h_margins += '\\' + name + ' ' + value + '\n';
636 void Preamble::handle_package(Parser &p, string const & name,
637 string const & opts, bool in_lyx_preamble)
639 vector<string> options = split_options(opts);
640 add_package(name, options);
643 if (is_known(name, known_xetex_packages)) {
645 h_use_non_tex_fonts = "true";
646 registerAutomaticallyLoadedPackage("fontspec");
647 if (h_inputencoding == "auto")
648 p.setEncoding("utf8");
652 if (is_known(name, known_roman_fonts))
655 if (name == "fourier") {
656 h_font_roman = "utopia";
657 // when font uses real small capitals
658 if (opts == "expert")
662 else if (name == "mathpazo")
663 h_font_roman = "palatino";
665 else if (name == "mathptmx")
666 h_font_roman = "times";
669 if (is_known(name, known_sans_fonts)) {
673 h_font_sf_scale = scale_as_percentage(scale);
678 if (is_known(name, known_typewriter_fonts)) {
679 // fourier can be set as roman font _only_
680 // fourier as typewriter is handled in handling of \ttdefault
681 if (name != "fourier") {
682 h_font_typewriter = name;
685 h_font_tt_scale = scale_as_percentage(scale);
690 // font uses old-style figure
694 // after the detection and handling of special cases, we can remove the
695 // fonts, otherwise they would appear in the preamble, see bug #7856
696 if (is_known(name, known_roman_fonts) || is_known(name, known_sans_fonts)
697 || is_known(name, known_typewriter_fonts))
700 else if (name == "amsmath" || name == "amssymb" ||
701 name == "esint" || name == "mhchem" || name == "mathdots" ||
702 name == "mathtools" || name == "undertilde")
703 h_use_packages[name] = "2";
705 else if (name == "babel") {
706 h_language_package = "default";
707 // One might think we would have to do nothing if babel is loaded
708 // without any options to prevent pollution of the preamble with this
709 // babel call in every roundtrip.
710 // But the user could have defined babel-specific things afterwards. So
711 // we need to keep it in the preamble to prevent cases like bug #7861.
713 // check if more than one option was used - used later for inputenc
714 if (options.begin() != options.end() - 1)
715 one_language = false;
716 // babel takes the last language of the option of its \usepackage
717 // call as document language. If there is no such language option, the
718 // last language in the documentclass options is used.
719 handle_opt(options, known_languages, h_language);
720 // translate the babel name to a LyX name
721 h_language = babel2lyx(h_language);
722 // for Japanese we assume EUC-JP as encoding
723 // but we cannot determine the exact encoding and thus output also a note
724 if (h_language == "japanese") {
725 h_inputencoding = "euc";
726 p.setEncoding("EUC-JP");
727 is_nonCJKJapanese = true;
728 // in this case babel can be removed from the preamble
729 registerAutomaticallyLoadedPackage("babel");
731 // If babel is called with options, LyX puts them by default into the
732 // document class options. This works for most languages, except
733 // for Latvian, Lithuanian, Mongolian, Turkmen and Vietnamese and
734 // perhaps in future others.
735 // Therefore keep the babel call as it is as the user might have
737 h_preamble << "\\usepackage[" << opts << "]{babel}\n";
739 delete_opt(options, known_languages);
742 h_preamble << "\\usepackage{babel}\n";
745 else if (name == "polyglossia") {
746 h_language_package = "default";
747 h_default_output_format = "pdf4";
748 h_use_non_tex_fonts = "true";
750 registerAutomaticallyLoadedPackage("xunicode");
751 if (h_inputencoding == "auto")
752 p.setEncoding("utf8");
755 else if (name == "CJK") {
756 // It is impossible to determine the document language if CJK is used.
757 // All we can do is to notify the user that he has to set this by himself.
759 // set the encoding to "auto" because it might be set to "default" by the babel handling
760 // and this would not be correct for CJK
761 if (h_inputencoding == "default")
762 h_inputencoding = "auto";
763 registerAutomaticallyLoadedPackage("CJK");
766 else if (name == "fontenc") {
767 h_fontencoding = getStringFromVector(options, ",");
768 /* We could do the following for better round trip support,
769 * but this makes the document less portable, so I skip it:
770 if (h_fontencoding == lyxrc.fontenc)
771 h_fontencoding = "global";
776 else if (name == "inputenc" || name == "luainputenc") {
777 // h_inputencoding is only set when there is not more than one
778 // inputenc option because otherwise h_inputencoding must be
779 // set to "auto" (the default encoding of the document language)
780 // Therefore check for the "," character.
781 // It is also only set when there is not more than one babel
783 if (opts.find(",") == string::npos && one_language == true)
784 h_inputencoding = opts;
785 if (!options.empty())
786 p.setEncoding(options.back());
790 else if (name == "srcltx") {
793 h_output_sync_macro = "\\usepackage[" + opts + "]{srcltx}";
796 h_output_sync_macro = "\\usepackage{srcltx}";
799 else if (is_known(name, known_old_language_packages)) {
800 // known language packages from the times before babel
801 // if they are found and not also babel, they will be used as
802 // custom language package
803 h_language_package = "\\usepackage{" + name + "}";
806 else if (name == "prettyref")
807 ; // ignore this FIXME: Use the package separator mechanism instead
809 else if (name == "lyxskak") {
810 // ignore this and its options
811 const char * const o[] = {"ps", "mover", 0};
812 delete_opt(options, o);
815 else if (is_known(name, known_lyx_packages) && options.empty()) {
816 if (name == "splitidx")
817 h_use_indices = "true";
818 if (!in_lyx_preamble) {
819 h_preamble << package_beg_sep << name
820 << package_mid_sep << "\\usepackage{"
822 if (p.next_token().cat() == catNewline ||
823 (p.next_token().cat() == catSpace &&
824 p.next_next_token().cat() == catNewline))
826 h_preamble << package_end_sep;
830 else if (name == "geometry")
831 handle_geometry(options);
833 else if (name == "subfig")
834 ; // ignore this FIXME: Use the package separator mechanism instead
836 else if (is_known(name, known_languages))
839 else if (name == "natbib") {
840 h_biblio_style = "plainnat";
841 h_cite_engine = "natbib";
842 h_cite_engine_type = "authoryear";
843 vector<string>::iterator it =
844 find(options.begin(), options.end(), "authoryear");
845 if (it != options.end())
848 it = find(options.begin(), options.end(), "numbers");
849 if (it != options.end()) {
850 h_cite_engine_type = "numerical";
856 else if (name == "jurabib") {
857 h_biblio_style = "jurabib";
858 h_cite_engine = "jurabib";
859 h_cite_engine_type = "authoryear";
862 else if (name == "hyperref")
863 handle_hyperref(options);
865 else if (!in_lyx_preamble) {
867 h_preamble << "\\usepackage{" << name << '}';
869 h_preamble << "\\usepackage[" << opts << "]{"
873 if (p.next_token().cat() == catNewline ||
874 (p.next_token().cat() == catSpace &&
875 p.next_next_token().cat() == catNewline))
879 // We need to do something with the options...
880 if (!options.empty())
881 cerr << "Ignoring options '" << join(options, ",")
882 << "' of package " << name << '.' << endl;
884 // remove the whitespace
889 void Preamble::handle_if(Parser & p, bool in_lyx_preamble)
892 Token t = p.get_token();
893 if (t.cat() == catEscape &&
894 is_known(t.cs(), known_if_commands))
895 handle_if(p, in_lyx_preamble);
897 if (!in_lyx_preamble)
898 h_preamble << t.asInput();
899 if (t.cat() == catEscape && t.cs() == "fi")
906 bool Preamble::writeLyXHeader(ostream & os, bool subdoc)
908 // set the quote language
909 // LyX only knows the following quotes languages:
910 // english, swedish, german, polish, french and danish
911 // (quotes for "japanese" and "chinese-traditional" are missing because
912 // they wouldn't be useful: http://www.lyx.org/trac/ticket/6383)
913 // conversion list taken from
914 // http://en.wikipedia.org/wiki/Quotation_mark,_non-English_usage
915 // (quotes for kazakh and interlingua are unknown)
917 if (h_language == "danish")
918 h_quotes_language = "danish";
920 else if (is_known(h_language, known_french_quotes_languages))
921 h_quotes_language = "french";
923 else if (is_known(h_language, known_german_quotes_languages))
924 h_quotes_language = "german";
926 else if (is_known(h_language, known_polish_quotes_languages))
927 h_quotes_language = "polish";
929 else if (is_known(h_language, known_swedish_quotes_languages))
930 h_quotes_language = "swedish";
932 else if (is_known(h_language, known_english_quotes_languages))
933 h_quotes_language = "english";
935 if (contains(h_float_placement, "H"))
936 registerAutomaticallyLoadedPackage("float");
937 if (h_spacing != "single" && h_spacing != "default")
938 registerAutomaticallyLoadedPackage("setspace");
939 if (h_use_packages["amsmath"] == "2") {
940 // amsbsy and amstext are already provided by amsmath
941 registerAutomaticallyLoadedPackage("amsbsy");
942 registerAutomaticallyLoadedPackage("amstext");
945 // output the LyX file settings
946 os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
947 << "\\lyxformat " << LYX_FORMAT << '\n'
948 << "\\begin_document\n"
949 << "\\begin_header\n"
950 << "\\textclass " << h_textclass << "\n";
951 string const raw = subdoc ? empty_string() : h_preamble.str();
953 os << "\\begin_preamble\n";
954 for (string::size_type i = 0; i < raw.size(); ++i) {
955 if (raw[i] == package_beg_sep) {
956 // Here follows some package loading code that
957 // must be skipped if the package is loaded
959 string::size_type j = raw.find(package_mid_sep, i);
960 if (j == string::npos)
962 string::size_type k = raw.find(package_end_sep, j);
963 if (k == string::npos)
965 string const package = raw.substr(i + 1, j - i - 1);
966 string const replacement = raw.substr(j + 1, k - j - 1);
967 if (auto_packages.find(package) == auto_packages.end())
973 os << "\n\\end_preamble\n";
975 if (!h_options.empty())
976 os << "\\options " << h_options << "\n";
977 os << "\\use_default_options " << h_use_default_options << "\n";
978 if (!used_modules.empty()) {
979 os << "\\begin_modules\n";
980 vector<string>::const_iterator const end = used_modules.end();
981 vector<string>::const_iterator it = used_modules.begin();
982 for (; it != end; ++it)
984 os << "\\end_modules\n";
986 os << "\\maintain_unincluded_children " << h_maintain_unincluded_children << "\n"
987 << "\\language " << h_language << "\n"
988 << "\\language_package " << h_language_package << "\n"
989 << "\\inputencoding " << h_inputencoding << "\n"
990 << "\\fontencoding " << h_fontencoding << "\n"
991 << "\\font_roman " << h_font_roman << "\n"
992 << "\\font_sans " << h_font_sans << "\n"
993 << "\\font_typewriter " << h_font_typewriter << "\n"
994 << "\\font_math " << h_font_math << "\n"
995 << "\\font_default_family " << h_font_default_family << "\n"
996 << "\\use_non_tex_fonts " << h_use_non_tex_fonts << "\n"
997 << "\\font_sc " << h_font_sc << "\n"
998 << "\\font_osf " << h_font_osf << "\n"
999 << "\\font_sf_scale " << h_font_sf_scale << "\n"
1000 << "\\font_tt_scale " << h_font_tt_scale << "\n"
1001 << "\\graphics " << h_graphics << "\n"
1002 << "\\default_output_format " << h_default_output_format << "\n"
1003 << "\\output_sync " << h_output_sync << "\n";
1004 if (h_output_sync == "1")
1005 os << "\\output_sync_macro \"" << h_output_sync_macro << "\"\n";
1006 os << "\\bibtex_command " << h_bibtex_command << "\n"
1007 << "\\index_command " << h_index_command << "\n";
1008 if (!h_float_placement.empty())
1009 os << "\\float_placement " << h_float_placement << "\n";
1010 os << "\\paperfontsize " << h_paperfontsize << "\n"
1011 << "\\spacing " << h_spacing << "\n"
1012 << "\\use_hyperref " << h_use_hyperref << '\n';
1013 if (h_use_hyperref == "true") {
1014 if (!h_pdf_title.empty())
1015 os << "\\pdf_title \"" << h_pdf_title << "\"\n";
1016 if (!h_pdf_author.empty())
1017 os << "\\pdf_author \"" << h_pdf_author << "\"\n";
1018 if (!h_pdf_subject.empty())
1019 os << "\\pdf_subject \"" << h_pdf_subject << "\"\n";
1020 if (!h_pdf_keywords.empty())
1021 os << "\\pdf_keywords \"" << h_pdf_keywords << "\"\n";
1022 os << "\\pdf_bookmarks " << h_pdf_bookmarks << "\n"
1023 "\\pdf_bookmarksnumbered " << h_pdf_bookmarksnumbered << "\n"
1024 "\\pdf_bookmarksopen " << h_pdf_bookmarksopen << "\n"
1025 "\\pdf_bookmarksopenlevel " << h_pdf_bookmarksopenlevel << "\n"
1026 "\\pdf_breaklinks " << h_pdf_breaklinks << "\n"
1027 "\\pdf_pdfborder " << h_pdf_pdfborder << "\n"
1028 "\\pdf_colorlinks " << h_pdf_colorlinks << "\n"
1029 "\\pdf_backref " << h_pdf_backref << "\n"
1030 "\\pdf_pdfusetitle " << h_pdf_pdfusetitle << '\n';
1031 if (!h_pdf_pagemode.empty())
1032 os << "\\pdf_pagemode " << h_pdf_pagemode << '\n';
1033 if (!h_pdf_quoted_options.empty())
1034 os << "\\pdf_quoted_options \"" << h_pdf_quoted_options << "\"\n";
1036 os << "\\papersize " << h_papersize << "\n"
1037 << "\\use_geometry " << h_use_geometry << '\n';
1038 for (map<string, string>::const_iterator it = h_use_packages.begin();
1039 it != h_use_packages.end(); ++it)
1040 os << "\\use_package " << it->first << ' ' << it->second << '\n';
1041 os << "\\cite_engine " << h_cite_engine << '\n'
1042 << "\\cite_engine_type " << h_cite_engine_type << '\n'
1043 << "\\biblio_style " << h_biblio_style << "\n"
1044 << "\\use_bibtopic " << h_use_bibtopic << "\n"
1045 << "\\use_indices " << h_use_indices << "\n"
1046 << "\\paperorientation " << h_paperorientation << '\n'
1047 << "\\suppress_date " << h_suppress_date << '\n'
1048 << "\\justification " << h_justification << '\n'
1049 << "\\use_refstyle " << h_use_refstyle << '\n';
1050 if (!h_fontcolor.empty())
1051 os << "\\fontcolor " << h_fontcolor << '\n';
1052 if (!h_notefontcolor.empty())
1053 os << "\\notefontcolor " << h_notefontcolor << '\n';
1054 if (!h_backgroundcolor.empty())
1055 os << "\\backgroundcolor " << h_backgroundcolor << '\n';
1056 if (!h_boxbgcolor.empty())
1057 os << "\\boxbgcolor " << h_boxbgcolor << '\n';
1058 os << "\\index " << h_index << '\n'
1059 << "\\shortcut " << h_shortcut << '\n'
1060 << "\\color " << h_color << '\n'
1063 << "\\secnumdepth " << h_secnumdepth << "\n"
1064 << "\\tocdepth " << h_tocdepth << "\n"
1065 << "\\paragraph_separation " << h_paragraph_separation << "\n";
1066 if (h_paragraph_separation == "skip")
1067 os << "\\defskip " << h_defskip << "\n";
1069 os << "\\paragraph_indentation " << h_paragraph_indentation << "\n";
1070 os << "\\quotes_language " << h_quotes_language << "\n"
1071 << "\\papercolumns " << h_papercolumns << "\n"
1072 << "\\papersides " << h_papersides << "\n"
1073 << "\\paperpagestyle " << h_paperpagestyle << "\n";
1074 if (!h_listings_params.empty())
1075 os << "\\listings_params " << h_listings_params << "\n";
1076 os << "\\tracking_changes " << h_tracking_changes << "\n"
1077 << "\\output_changes " << h_output_changes << "\n"
1078 << "\\html_math_output " << h_html_math_output << "\n"
1079 << "\\html_css_as_file " << h_html_css_as_file << "\n"
1080 << "\\html_be_strict " << h_html_be_strict << "\n"
1082 << "\\end_header\n\n"
1083 << "\\begin_body\n";
1088 void Preamble::parse(Parser & p, string const & forceclass,
1089 TeX2LyXDocClass & tc)
1091 // initialize fixed types
1092 special_columns['D'] = 3;
1093 bool is_full_document = false;
1094 bool is_lyx_file = false;
1095 bool in_lyx_preamble = false;
1097 // determine whether this is a full document or a fragment for inclusion
1099 Token const & t = p.get_token();
1101 if (t.cat() == catEscape && t.cs() == "documentclass") {
1102 is_full_document = true;
1108 while (is_full_document && p.good()) {
1109 Token const & t = p.get_token();
1112 cerr << "t: " << t << "\n";
1118 if (!in_lyx_preamble &&
1119 (t.cat() == catLetter ||
1120 t.cat() == catSuper ||
1121 t.cat() == catSub ||
1122 t.cat() == catOther ||
1123 t.cat() == catMath ||
1124 t.cat() == catActive ||
1125 t.cat() == catBegin ||
1126 t.cat() == catEnd ||
1127 t.cat() == catAlign ||
1128 t.cat() == catParameter))
1129 h_preamble << t.cs();
1131 else if (!in_lyx_preamble &&
1132 (t.cat() == catSpace || t.cat() == catNewline))
1133 h_preamble << t.asInput();
1135 else if (t.cat() == catComment) {
1136 static regex const islyxfile("%% LyX .* created this file");
1137 static regex const usercommands("User specified LaTeX commands");
1139 string const comment = t.asInput();
1141 // magically switch encoding default if it looks like XeLaTeX
1142 static string const magicXeLaTeX =
1143 "% This document must be compiled with XeLaTeX ";
1144 if (comment.size() > magicXeLaTeX.size()
1145 && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
1146 && h_inputencoding == "auto") {
1147 cerr << "XeLaTeX comment found, switching to UTF8\n";
1148 h_inputencoding = "utf8";
1151 if (regex_search(comment, sub, islyxfile)) {
1153 in_lyx_preamble = true;
1154 } else if (is_lyx_file
1155 && regex_search(comment, sub, usercommands))
1156 in_lyx_preamble = false;
1157 else if (!in_lyx_preamble)
1158 h_preamble << t.asInput();
1161 else if (t.cs() == "pagestyle")
1162 h_paperpagestyle = p.verbatim_item();
1164 else if (t.cs() == "setdefaultlanguage") {
1166 // We don't yet care about non-language variant options
1167 // because LyX doesn't support this yet, see bug #8214
1169 string langopts = p.getOpt();
1170 // check if the option contains a variant, if yes, extract it
1171 string::size_type pos_var = langopts.find("variant");
1172 string::size_type i = langopts.find(',', pos_var);
1173 string::size_type k = langopts.find('=', pos_var);
1174 if (pos_var != string::npos){
1176 if (i == string::npos)
1177 variant = langopts.substr(k + 1, langopts.length() - k - 2);
1179 variant = langopts.substr(k + 1, i - k - 1);
1180 h_language = variant;
1184 h_language = p.verbatim_item();
1185 //finally translate the poyglossia name to a LyX name
1186 h_language = polyglossia2lyx(h_language);
1189 else if (t.cs() == "setotherlanguage") {
1190 // We don't yet care about the option because LyX doesn't
1191 // support this yet, see bug #8214
1192 p.hasOpt() ? p.getOpt() : string();
1196 else if (t.cs() == "setmainfont") {
1197 // we don't care about the option
1198 p.hasOpt() ? p.getOpt() : string();
1199 h_font_roman = p.getArg('{', '}');
1202 else if (t.cs() == "setsansfont" || t.cs() == "setmonofont") {
1203 // LyX currently only supports the scale option
1206 string fontopts = p.getArg('[', ']');
1207 // check if the option contains a scaling, if yes, extract it
1208 string::size_type pos = fontopts.find("Scale");
1209 if (pos != string::npos) {
1210 string::size_type i = fontopts.find(',', pos);
1211 if (i == string::npos)
1212 scale = scale_as_percentage(fontopts.substr(pos + 1));
1214 scale = scale_as_percentage(fontopts.substr(pos, i - pos));
1217 if (t.cs() == "setsansfont") {
1219 h_font_sf_scale = scale;
1220 h_font_sans = p.getArg('{', '}');
1223 h_font_tt_scale = scale;
1224 h_font_typewriter = p.getArg('{', '}');
1228 else if (t.cs() == "date") {
1229 string argument = p.getArg('{', '}');
1230 if (argument.empty())
1231 h_suppress_date = "true";
1233 h_preamble << t.asInput() << '{' << argument << '}';
1236 else if (t.cs() == "color") {
1237 string const space =
1238 (p.hasOpt() ? p.getOpt() : string());
1239 string argument = p.getArg('{', '}');
1240 // check the case that a standard color is used
1241 if (space.empty() && is_known(argument, known_basic_colors)) {
1242 h_fontcolor = rgbcolor2code(argument);
1243 preamble.registerAutomaticallyLoadedPackage("color");
1244 } else if (space.empty() && argument == "document_fontcolor")
1245 preamble.registerAutomaticallyLoadedPackage("color");
1246 // check the case that LyX's document_fontcolor is defined
1247 // but not used for \color
1249 h_preamble << t.asInput();
1251 h_preamble << space;
1252 h_preamble << '{' << argument << '}';
1253 // the color might already be set because \definecolor
1254 // is parsed before this
1259 else if (t.cs() == "pagecolor") {
1260 string argument = p.getArg('{', '}');
1261 // check the case that a standard color is used
1262 if (is_known(argument, known_basic_colors)) {
1263 h_backgroundcolor = rgbcolor2code(argument);
1264 } else if (argument == "page_backgroundcolor")
1265 preamble.registerAutomaticallyLoadedPackage("color");
1266 // check the case that LyX's page_backgroundcolor is defined
1267 // but not used for \pagecolor
1269 h_preamble << t.asInput() << '{' << argument << '}';
1270 // the color might already be set because \definecolor
1271 // is parsed before this
1272 h_backgroundcolor = "";
1276 else if (t.cs() == "makeatletter") {
1277 // LyX takes care of this
1278 p.setCatCode('@', catLetter);
1281 else if (t.cs() == "makeatother") {
1282 // LyX takes care of this
1283 p.setCatCode('@', catOther);
1286 else if (t.cs() == "newcommand" || t.cs() == "newcommandx"
1287 || t.cs() == "renewcommand" || t.cs() == "renewcommandx"
1288 || t.cs() == "providecommand" || t.cs() == "providecommandx"
1289 || t.cs() == "DeclareRobustCommand"
1290 || t.cs() == "DeclareRobustCommandx"
1291 || t.cs() == "ProvideTextCommandDefault"
1292 || t.cs() == "DeclareMathAccent") {
1294 if (p.next_token().character() == '*') {
1298 string const name = p.verbatim_item();
1299 string const opt1 = p.getFullOpt();
1300 string const opt2 = p.getFullOpt();
1301 string const body = p.verbatim_item();
1303 if (name == "\\rmdefault")
1304 if (is_known(body, known_roman_fonts))
1305 h_font_roman = body;
1306 if (name == "\\sfdefault")
1307 if (is_known(body, known_sans_fonts))
1309 if (name == "\\ttdefault")
1310 if (is_known(body, known_typewriter_fonts))
1311 h_font_typewriter = body;
1312 if (name == "\\familydefault") {
1313 string family = body;
1314 // remove leading "\"
1315 h_font_default_family = family.erase(0,1);
1318 // remove the lyxdot definition that is re-added by LyX
1320 if (name == "\\lyxdot")
1321 in_lyx_preamble = true;
1323 // Add the command to the known commands
1324 add_known_command(name, opt1, !opt2.empty(), from_utf8(body));
1326 // only non-lyxspecific stuff
1327 if (!in_lyx_preamble) {
1329 ss << '\\' << t.cs();
1332 ss << '{' << name << '}' << opt1 << opt2
1333 << '{' << body << "}";
1334 h_preamble << ss.str();
1336 ostream & out = in_preamble ? h_preamble : os;
1337 out << "\\" << t.cs() << "{" << name << "}"
1338 << opts << "{" << body << "}";
1343 else if (t.cs() == "documentclass") {
1344 vector<string>::iterator it;
1345 vector<string> opts = split_options(p.getArg('[', ']'));
1346 handle_opt(opts, known_fontsizes, h_paperfontsize);
1347 delete_opt(opts, known_fontsizes);
1348 // delete "pt" at the end
1349 string::size_type i = h_paperfontsize.find("pt");
1350 if (i != string::npos)
1351 h_paperfontsize.erase(i);
1352 // The documentclass options are always parsed before the options
1353 // of the babel call so that a language cannot overwrite the babel
1355 handle_opt(opts, known_languages, h_language);
1356 delete_opt(opts, known_languages);
1358 // paper orientation
1359 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
1360 h_paperorientation = "landscape";
1364 if ((it = find(opts.begin(), opts.end(), "oneside"))
1369 if ((it = find(opts.begin(), opts.end(), "twoside"))
1375 if ((it = find(opts.begin(), opts.end(), "onecolumn"))
1377 h_papercolumns = "1";
1380 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
1382 h_papercolumns = "2";
1386 // some size options are known to any document classes, other sizes
1387 // are handled by the \geometry command of the geometry package
1388 handle_opt(opts, known_class_paper_sizes, h_papersize);
1389 delete_opt(opts, known_class_paper_sizes);
1390 // the remaining options
1391 h_options = join(opts, ",");
1392 // FIXME This does not work for classes that have a
1393 // different name in LyX than in LaTeX
1394 h_textclass = p.getArg('{', '}');
1397 else if (t.cs() == "usepackage") {
1398 string const options = p.getArg('[', ']');
1399 string const name = p.getArg('{', '}');
1400 vector<string> vecnames;
1401 split(name, vecnames, ',');
1402 vector<string>::const_iterator it = vecnames.begin();
1403 vector<string>::const_iterator end = vecnames.end();
1404 for (; it != end; ++it)
1405 handle_package(p, trimSpaceAndEol(*it), options,
1409 else if (t.cs() == "inputencoding") {
1410 string const encoding = p.getArg('{','}');
1411 h_inputencoding = encoding;
1412 p.setEncoding(encoding);
1415 else if (t.cs() == "newenvironment") {
1416 string const name = p.getArg('{', '}');
1417 string const opt1 = p.getFullOpt();
1418 string const opt2 = p.getFullOpt();
1419 string const beg = p.verbatim_item();
1420 string const end = p.verbatim_item();
1421 if (!in_lyx_preamble) {
1422 h_preamble << "\\newenvironment{" << name
1423 << '}' << opt1 << opt2 << '{'
1424 << beg << "}{" << end << '}';
1426 add_known_environment(name, opt1, !opt2.empty(),
1427 from_utf8(beg), from_utf8(end));
1431 else if (t.cs() == "def") {
1432 string name = p.get_token().cs();
1433 // In fact, name may be more than the name:
1434 // In the test case of bug 8116
1435 // name == "csname SF@gobble@opt \endcsname".
1436 // Therefore, we need to use asInput() instead of cs().
1437 while (p.next_token().cat() != catBegin)
1438 name += p.get_token().asInput();
1439 if (!in_lyx_preamble)
1440 h_preamble << "\\def\\" << name << '{'
1441 << p.verbatim_item() << "}";
1444 else if (t.cs() == "newcolumntype") {
1445 string const name = p.getArg('{', '}');
1446 trimSpaceAndEol(name);
1448 string opts = p.getOpt();
1449 if (!opts.empty()) {
1450 istringstream is(string(opts, 1));
1453 special_columns[name[0]] = nargs;
1454 h_preamble << "\\newcolumntype{" << name << "}";
1456 h_preamble << "[" << nargs << "]";
1457 h_preamble << "{" << p.verbatim_item() << "}";
1460 else if (t.cs() == "setcounter") {
1461 string const name = p.getArg('{', '}');
1462 string const content = p.getArg('{', '}');
1463 if (name == "secnumdepth")
1464 h_secnumdepth = content;
1465 else if (name == "tocdepth")
1466 h_tocdepth = content;
1468 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
1471 else if (t.cs() == "setlength") {
1472 string const name = p.verbatim_item();
1473 string const content = p.verbatim_item();
1474 // the paragraphs are only not indented when \parindent is set to zero
1475 if (name == "\\parindent" && content != "") {
1476 if (content[0] == '0')
1477 h_paragraph_separation = "skip";
1479 h_paragraph_indentation = translate_len(content);
1480 } else if (name == "\\parskip") {
1481 if (content == "\\smallskipamount")
1482 h_defskip = "smallskip";
1483 else if (content == "\\medskipamount")
1484 h_defskip = "medskip";
1485 else if (content == "\\bigskipamount")
1486 h_defskip = "bigskip";
1488 h_defskip = content;
1490 h_preamble << "\\setlength{" << name << "}{" << content << "}";
1493 else if (t.cs() == "onehalfspacing")
1494 h_spacing = "onehalf";
1496 else if (t.cs() == "doublespacing")
1497 h_spacing = "double";
1499 else if (t.cs() == "setstretch")
1500 h_spacing = "other " + p.verbatim_item();
1502 else if (t.cs() == "synctex") {
1503 // the scheme is \synctex=value
1504 // where value can only be "1" or "-1"
1505 h_output_sync = "1";
1506 // there can be any character behind the value (e.g. a linebreak or a '\'
1507 // therefore we extract it char by char
1509 string value = p.get_token().asInput();
1511 value += p.get_token().asInput();
1512 h_output_sync_macro = "\\synctex=" + value;
1515 else if (t.cs() == "begin") {
1516 string const name = p.getArg('{', '}');
1517 if (name == "document")
1519 h_preamble << "\\begin{" << name << "}";
1522 else if (t.cs() == "geometry") {
1523 vector<string> opts = split_options(p.getArg('{', '}'));
1524 handle_geometry(opts);
1527 else if (t.cs() == "definecolor") {
1528 string const color = p.getArg('{', '}');
1529 string const space = p.getArg('{', '}');
1530 string const value = p.getArg('{', '}');
1531 if (color == "document_fontcolor" && space == "rgb") {
1532 RGBColor c(RGBColorFromLaTeX(value));
1533 h_fontcolor = X11hexname(c);
1534 } else if (color == "note_fontcolor" && space == "rgb") {
1535 RGBColor c(RGBColorFromLaTeX(value));
1536 h_notefontcolor = X11hexname(c);
1537 } else if (color == "page_backgroundcolor" && space == "rgb") {
1538 RGBColor c(RGBColorFromLaTeX(value));
1539 h_backgroundcolor = X11hexname(c);
1540 } else if (color == "shadecolor" && space == "rgb") {
1541 RGBColor c(RGBColorFromLaTeX(value));
1542 h_boxbgcolor = X11hexname(c);
1544 h_preamble << "\\definecolor{" << color
1545 << "}{" << space << "}{" << value
1550 else if (t.cs() == "bibliographystyle")
1551 h_biblio_style = p.verbatim_item();
1553 else if (t.cs() == "jurabibsetup") {
1554 // FIXME p.getArg('{', '}') is most probably wrong (it
1555 // does not handle nested braces).
1556 // Use p.verbatim_item() instead.
1557 vector<string> jurabibsetup =
1558 split_options(p.getArg('{', '}'));
1559 // add jurabibsetup to the jurabib package options
1560 add_package("jurabib", jurabibsetup);
1561 if (!jurabibsetup.empty()) {
1562 h_preamble << "\\jurabibsetup{"
1563 << join(jurabibsetup, ",") << '}';
1567 else if (t.cs() == "hypersetup") {
1568 vector<string> hypersetup =
1569 split_options(p.verbatim_item());
1570 // add hypersetup to the hyperref package options
1571 handle_hyperref(hypersetup);
1572 if (!hypersetup.empty()) {
1573 h_preamble << "\\hypersetup{"
1574 << join(hypersetup, ",") << '}';
1578 else if (is_known(t.cs(), known_if_3arg_commands)) {
1579 // prevent misparsing of \usepackage if it is used
1580 // as an argument (see e.g. our own output of
1581 // \@ifundefined above)
1582 string const arg1 = p.verbatim_item();
1583 string const arg2 = p.verbatim_item();
1584 string const arg3 = p.verbatim_item();
1585 // test case \@ifundefined{date}{}{\date{}}
1586 if (t.cs() == "@ifundefined" && arg1 == "date" &&
1587 arg2.empty() && arg3 == "\\date{}") {
1588 h_suppress_date = "true";
1589 // older tex2lyx versions did output
1590 // \@ifundefined{definecolor}{\usepackage{color}}{}
1591 } else if (t.cs() == "@ifundefined" &&
1592 arg1 == "definecolor" &&
1593 arg2 == "\\usepackage{color}" &&
1595 if (!in_lyx_preamble)
1596 h_preamble << package_beg_sep
1599 << "\\@ifundefined{definecolor}{color}{}"
1602 //\@ifundefined{showcaptionsetup}{}{%
1603 // \PassOptionsToPackage{caption=false}{subfig}}
1604 // that LyX uses for subfloats
1605 } else if (t.cs() == "@ifundefined" &&
1606 arg1 == "showcaptionsetup" && arg2.empty()
1607 && arg3 == "%\n \\PassOptionsToPackage{caption=false}{subfig}") {
1609 } else if (!in_lyx_preamble) {
1610 h_preamble << t.asInput()
1611 << '{' << arg1 << '}'
1612 << '{' << arg2 << '}'
1613 << '{' << arg3 << '}';
1617 else if (is_known(t.cs(), known_if_commands)) {
1618 // must not parse anything in conditional code, since
1619 // LyX would output the parsed contents unconditionally
1620 if (!in_lyx_preamble)
1621 h_preamble << t.asInput();
1622 handle_if(p, in_lyx_preamble);
1625 else if (!t.cs().empty() && !in_lyx_preamble)
1626 h_preamble << '\\' << t.cs();
1629 // remove the whitespace
1632 // Force textclass if the user wanted it
1633 if (!forceclass.empty())
1634 h_textclass = forceclass;
1635 if (noweb_mode && !prefixIs(h_textclass, "literate-"))
1636 h_textclass.insert(0, "literate-");
1637 tc.setName(h_textclass);
1639 cerr << "Error: Could not read layout file for textclass \"" << h_textclass << "\"." << endl;
1642 if (h_papersides.empty()) {
1645 h_papersides = ss.str();
1650 string babel2lyx(string const & language)
1652 char const * const * where = is_known(language, known_languages);
1654 return known_coded_languages[where - known_languages];
1659 string Preamble::polyglossia2lyx(string const & language)
1661 char const * const * where = is_known(language, polyglossia_languages);
1663 return coded_polyglossia_languages[where - polyglossia_languages];
1668 string rgbcolor2code(string const & name)
1670 char const * const * where = is_known(name, known_basic_colors);
1672 // "red", "green" etc
1673 return known_basic_color_codes[where - known_basic_colors];
1675 // "255,0,0", "0,255,0" etc
1676 RGBColor c(RGBColorFromLaTeX(name));
1677 return X11hexname(c);