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 // CJK languages are handled in text.cpp, polyglossia languages are listed
50 * known babel language names (including synonyms)
51 * not in standard babel: arabic, arabtex, armenian, belarusian, serbian-latin, thai
52 * please keep this in sync with known_coded_languages line by line!
54 const char * const known_languages[] = {"acadian", "afrikaans", "albanian",
55 "american", "arabic", "arabtex", "australian", "austrian", "bahasa", "bahasai",
56 "bahasam", "basque", "belarusian", "brazil", "brazilian", "breton", "british",
57 "bulgarian", "canadian", "canadien", "catalan", "croatian", "czech", "danish",
58 "dutch", "english", "esperanto", "estonian", "farsi", "finnish", "francais",
59 "french", "frenchb", "frenchle", "frenchpro", "galician", "german", "germanb",
60 "greek", "hebrew", "hungarian", "icelandic", "indon", "indonesian", "interlingua",
61 "irish", "italian", "japanese", "kazakh", "kurmanji", "latin", "latvian", "lithuanian",
62 "lowersorbian", "lsorbian", "magyar", "malay", "meyalu", "mongolian", "naustrian",
63 "newzealand", "ngerman", "ngermanb", "norsk", "nynorsk", "polutonikogreek", "polish",
64 "portuges", "portuguese", "romanian", "russian", "russianb", "samin",
65 "scottish", "serbian", "serbian-latin", "slovak", "slovene", "spanish",
66 "swedish", "thai", "turkish", "turkmen", "ukraineb", "ukrainian",
67 "uppersorbian", "UKenglish", "USenglish", "usorbian", "vietnam", "welsh",
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 "greek", "hebrew", "magyar", "icelandic", "bahasa", "bahasa", "interlingua",
81 "irish", "italian", "japanese", "kazakh", "kurmanji", "latin", "latvian", "lithuanian",
82 "lowersorbian", "lowersorbian", "magyar", "bahasam", "bahasam", "mongolian", "naustrian",
83 "newzealand", "ngerman", "ngerman", "norsk", "nynorsk", "polutonikogreek", "polish",
84 "portuguese", "portuguese", "romanian", "russian", "russian", "samin",
85 "scottish", "serbian", "serbian-latin", "slovak", "slovene", "spanish",
86 "swedish", "thai", "turkish", "turkmen", "ukrainian", "ukrainian",
87 "uppersorbian", "uppersorbian", "english", "english", "vietnamese", "welsh",
90 /// languages with danish quotes (.lyx names)
91 const char * const known_danish_quotes_languages[] = {"danish", 0};
93 /// languages with english quotes (.lyx names)
94 const char * const known_english_quotes_languages[] = {"american", "australian",
95 "bahasa", "bahasam", "brazilian", "canadian", "chinese-simplified", "english",
96 "esperanto", "hebrew", "irish", "korean", "newzealand", "portuguese", "scottish",
99 /// languages with french quotes (.lyx names)
100 const char * const known_french_quotes_languages[] = {"albanian",
101 "arabic_arabi", "arabic_arabtex", "basque", "canadien", "catalan", "french",
102 "galician", "greek", "italian", "norsk", "nynorsk", "polutonikogreek",
103 "russian", "spanish", "spanish-mexico", "turkish", "turkmen", "ukrainian",
106 /// languages with german quotes (.lyx names)
107 const char * const known_german_quotes_languages[] = {"austrian", "bulgarian",
108 "czech", "german", "icelandic", "lithuanian", "lowersorbian", "naustrian",
109 "ngerman", "serbian", "serbian-latin", "slovak", "slovene", "uppersorbian", 0};
111 /// languages with polish quotes (.lyx names)
112 const char * const known_polish_quotes_languages[] = {"afrikaans", "croatian",
113 "dutch", "estonian", "magyar", "polish", "romanian", 0};
115 /// languages with swedish quotes (.lyx names)
116 const char * const known_swedish_quotes_languages[] = {"finnish",
119 /// known language packages from the times before babel
120 const char * const known_old_language_packages[] = {"french", "frenchle",
121 "frenchpro", "german", "ngerman", "pmfrench", 0};
123 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
125 const char * const known_roman_fonts[] = { "ae", "beraserif", "bookman",
126 "ccfonts", "chancery", "charter", "cmr", "fourier", "lmodern", "mathpazo",
127 "mathptmx", "newcent", "utopia", 0};
129 const char * const known_sans_fonts[] = { "avant", "berasans", "cmbr", "cmss",
130 "helvet", "lmss", 0};
132 const char * const known_typewriter_fonts[] = { "beramono", "cmtl", "cmtt",
133 "courier", "lmtt", "luximono", "fourier", "lmodern", "mathpazo", "mathptmx",
136 const char * const known_paper_sizes[] = { "a0paper", "b0paper", "c0paper",
137 "a1paper", "b1paper", "c1paper", "a2paper", "b2paper", "c2paper", "a3paper",
138 "b3paper", "c3paper", "a4paper", "b4paper", "c4paper", "a5paper", "b5paper",
139 "c5paper", "a6paper", "b6paper", "c6paper", "executivepaper", "legalpaper",
140 "letterpaper", "b0j", "b1j", "b2j", "b3j", "b4j", "b5j", "b6j", 0};
142 const char * const known_class_paper_sizes[] = { "a4paper", "a5paper",
143 "executivepaper", "legalpaper", "letterpaper", 0};
145 const char * const known_paper_margins[] = { "lmargin", "tmargin", "rmargin",
146 "bmargin", "headheight", "headsep", "footskip", "columnsep", 0};
148 const char * const known_coded_paper_margins[] = { "leftmargin", "topmargin",
149 "rightmargin", "bottommargin", "headheight", "headsep", "footskip",
152 /// commands that can start an \if...\else...\endif sequence
153 const char * const known_if_commands[] = {"if", "ifarydshln", "ifbraket",
154 "ifcancel", "ifcolortbl", "ifeurosym", "ifmarginnote", "ifmmode", "ifpdf",
155 "ifsidecap", "ifupgreek", 0};
157 const char * const known_basic_colors[] = {"blue", "black", "cyan", "green",
158 "magenta", "red", "white", "yellow", 0};
160 const char * const known_basic_color_codes[] = {"#0000ff", "#000000", "#00ffff", "#00ff00",
161 "#ff00ff", "#ff0000", "#ffffff", "#ffff00", 0};
163 /// conditional commands with three arguments like \@ifundefined{}{}{}
164 const char * const known_if_3arg_commands[] = {"@ifundefined", "IfFileExists",
167 /// packages that work only in xetex
168 /// polyglossia is handled separately
169 const char * const known_xetex_packages[] = {"arabxetex", "fixlatvian",
170 "fontbook", "fontwrap", "mathspec", "philokalia", "unisugar",
171 "xeCJK", "xecolor", "xecyr", "xeindex", "xepersian", "xunicode", 0};
173 /// packages that are automatically skipped if loaded by LyX
174 const char * const known_lyx_packages[] = {"amsbsy", "amsmath", "amssymb",
175 "amstext", "amsthm", "array", "babel", "booktabs", "calc", "CJK", "color", "float",
176 "fontspec", "graphicx", "hhline", "ifthen", "longtable", "makeidx", "multirow",
177 "nomencl", "pdfpages", "rotating", "rotfloat", "splitidx", "setspace",
178 "subscript", "textcomp", "ulem", "url", "varioref", "verbatim", "wrapfig",
181 // codes used to remove packages that are loaded automatically by LyX.
182 // Syntax: package_beg_sep<name>package_mid_sep<package loading code>package_end_sep
183 const char package_beg_sep = '\001';
184 const char package_mid_sep = '\002';
185 const char package_end_sep = '\003';
188 // returns true if at least one of the options in what has been found
189 bool handle_opt(vector<string> & opts, char const * const * what, string & target)
195 // the last language option is the document language (for babel and LyX)
196 // the last size option is the document font size
197 vector<string>::iterator it;
198 vector<string>::iterator position = opts.begin();
199 for (; *what; ++what) {
200 it = find(opts.begin(), opts.end(), *what);
201 if (it != opts.end()) {
202 if (it >= position) {
213 void delete_opt(vector<string> & opts, char const * const * what)
218 // remove found options from the list
219 // do this after handle_opt to avoid potential memory leaks
220 vector<string>::iterator it;
221 for (; *what; ++what) {
222 it = find(opts.begin(), opts.end(), *what);
223 if (it != opts.end())
230 * Split a package options string (keyval format) into a vector.
232 * authorformat=smallcaps,
234 * titleformat=colonsep,
235 * bibformat={tabular,ibidem,numbered}
237 vector<string> split_options(string const & input)
239 vector<string> options;
243 Token const & t = p.get_token();
244 if (t.asInput() == ",") {
245 options.push_back(trimSpaceAndEol(option));
247 } else if (t.asInput() == "=") {
250 if (p.next_token().asInput() == "{")
251 option += '{' + p.getArg('{', '}') + '}';
252 } else if (t.cat() != catSpace)
253 option += t.asInput();
257 options.push_back(trimSpaceAndEol(option));
264 * Retrieve a keyval option "name={value with=sign}" named \p name from
265 * \p options and return the value.
266 * The found option is also removed from \p options.
268 string process_keyval_opt(vector<string> & options, string name)
270 for (size_t i = 0; i < options.size(); ++i) {
271 vector<string> option;
272 split(options[i], option, '=');
273 if (option.size() < 2)
275 if (option[0] == name) {
276 options.erase(options.begin() + i);
277 option.erase(option.begin());
278 return join(option, "=");
284 } // anonymous namespace
288 * known polyglossia language names (including variants)
290 const char * const Preamble::polyglossia_languages[] = {
291 "albanian", "croatian", "hebrew", "norsk", "swedish", "amharic", "czech", "hindi",
292 "nynorsk", "syriac", "arabic", "danish", "icelandic", "occitan", "tamil",
293 "armenian", "divehi", "interlingua", "polish", "telugu", "asturian", "dutch",
294 "irish", "portuges", "thai", "bahasai", "english", "italian", "romanian", "turkish",
295 "bahasam", "esperanto", "lao", "russian", "turkmen", "basque", "estonian", "latin",
296 "samin", "ukrainian", "bengali", "farsi", "latvian", "sanskrit", "urdu", "brazil",
297 "brazilian", "finnish", "lithuanian", "scottish", "usorbian", "breton", "french",
298 "lsorbian", "serbian", "vietnamese", "bulgarian", "galician", "magyar", "slovak",
299 "welsh", "catalan", "german", "malayalam", "slovenian", "coptic", "greek",
300 "marathi", "spanish",
301 "american", "ancient", "australian", "british", "monotonic", "newzealand",
305 * the same as polyglossia_languages with .lyx names
306 * please keep this in sync with polyglossia_languages line by line!
308 const char * const Preamble::coded_polyglossia_languages[] = {
309 "albanian", "croatian", "hebrew", "norsk", "swedish", "amharic", "czech", "hindi",
310 "nynorsk", "syriac", "arabic_arabi", "danish", "icelandic", "occitan", "tamil",
311 "armenian", "divehi", "interlingua", "polish", "telugu", "asturian", "dutch",
312 "irish", "portuges", "thai", "bahasa", "english", "italian", "romanian", "turkish",
313 "bahasam", "esperanto", "lao", "russian", "turkmen", "basque", "estonian", "latin",
314 "samin", "ukrainian", "bengali", "farsi", "latvian", "sanskrit", "urdu", "brazilian",
315 "brazilian", "finnish", "lithuanian", "scottish", "uppersorbian", "breton", "french",
316 "lowersorbian", "serbian", "vietnamese", "bulgarian", "galician", "magyar", "slovak",
317 "welsh", "catalan", "ngerman", "malayalam", "slovene", "coptic", "greek",
318 "marathi", "spanish",
319 "american", "ancientgreek", "australian", "british", "greek", "newzealand",
320 "polutonikogreek", 0};
323 bool Preamble::indentParagraphs() const
325 return h_paragraph_separation == "indent";
329 bool Preamble::isPackageUsed(string const & package) const
331 return used_packages.find(package) != used_packages.end();
335 vector<string> Preamble::getPackageOptions(string const & package) const
337 map<string, vector<string> >::const_iterator it = used_packages.find(package);
338 if (it != used_packages.end())
340 return vector<string>();
344 void Preamble::registerAutomaticallyLoadedPackage(std::string const & package)
346 auto_packages.insert(package);
350 void Preamble::addModule(string const & module)
352 used_modules.push_back(module);
356 void Preamble::suppressDate(bool suppress)
359 h_suppress_date = "true";
361 h_suppress_date = "false";
365 void Preamble::registerAuthor(std::string const & name)
367 Author author(from_utf8(name), empty_docstring());
368 author.setUsed(true);
369 authors_.record(author);
370 h_tracking_changes = "true";
371 h_output_changes = "true";
375 Author const & Preamble::getAuthor(std::string const & name) const
377 Author author(from_utf8(name), empty_docstring());
378 for (AuthorList::Authors::const_iterator it = authors_.begin();
379 it != authors_.end(); ++it)
382 static Author const dummy;
387 void Preamble::add_package(string const & name, vector<string> & options)
389 // every package inherits the global options
390 if (used_packages.find(name) == used_packages.end())
391 used_packages[name] = split_options(h_options);
393 vector<string> & v = used_packages[name];
394 v.insert(v.end(), options.begin(), options.end());
395 if (name == "jurabib") {
396 // Don't output the order argument (see the cite command
397 // handling code in text.cpp).
398 vector<string>::iterator end =
399 remove(options.begin(), options.end(), "natbiborder");
400 end = remove(options.begin(), end, "jurabiborder");
401 options.erase(end, options.end());
408 // Given is a string like "scaled=0.9", return 0.9 * 100
409 string const scale_as_percentage(string const & scale)
411 string::size_type pos = scale.find('=');
412 if (pos != string::npos) {
413 string value = scale.substr(pos + 1);
415 return convert<string>(100 * convert<double>(value));
417 // If the input string didn't match our expectations.
418 // return the default value "100"
423 string remove_braces(string const & value)
427 if (value[0] == '{' && value[value.length()-1] == '}')
428 return value.substr(1, value.length()-2);
432 } // anonymous namespace
435 Preamble::Preamble() : one_language(true), title_layout_found(false)
439 h_biblio_style = "plain";
440 h_bibtex_command = "default";
441 h_cite_engine = "basic";
442 h_cite_engine_type = "numerical";
444 h_defskip = "medskip";
447 h_fontencoding = "default";
448 h_font_roman = "default";
449 h_font_sans = "default";
450 h_font_typewriter = "default";
451 h_font_math = "auto";
452 h_font_default_family = "default";
453 h_use_non_tex_fonts = "false";
455 h_font_osf = "false";
456 h_font_sf_scale = "100";
457 h_font_tt_scale = "100";
458 h_graphics = "default";
459 h_default_output_format = "default";
460 h_html_be_strict = "false";
461 h_html_css_as_file = "0";
462 h_html_math_output = "0";
464 h_index_command = "default";
465 h_inputencoding = "auto";
466 h_justification = "true";
467 h_language = "english";
468 h_language_package = "none";
470 h_maintain_unincluded_children = "false";
474 h_output_changes = "false";
476 //h_output_sync_macro
477 h_papercolumns = "1";
478 h_paperfontsize = "default";
479 h_paperorientation = "portrait";
480 h_paperpagestyle = "default";
482 h_papersize = "default";
483 h_paragraph_indentation = "default";
484 h_paragraph_separation = "indent";
489 h_pdf_bookmarks = "1";
490 h_pdf_bookmarksnumbered = "0";
491 h_pdf_bookmarksopen = "0";
492 h_pdf_bookmarksopenlevel = "1";
493 h_pdf_breaklinks = "0";
494 h_pdf_pdfborder = "0";
495 h_pdf_colorlinks = "0";
496 h_pdf_backref = "section";
497 h_pdf_pdfusetitle = "1";
499 //h_pdf_quoted_options;
500 h_quotes_language = "english";
503 h_spacing = "single";
504 h_suppress_date = "false";
505 h_textclass = "article";
507 h_tracking_changes = "false";
508 h_use_bibtopic = "false";
509 h_use_indices = "false";
510 h_use_geometry = "false";
511 h_use_default_options = "false";
512 h_use_hyperref = "false";
513 h_use_refstyle = "0";
514 h_use_packages["amsmath"] = "1";
515 h_use_packages["amssymb"] = "0";
516 h_use_packages["esint"] = "1";
517 h_use_packages["mhchem"] = "0";
518 h_use_packages["mathdots"] = "0";
519 h_use_packages["mathtools"] = "0";
520 h_use_packages["undertilde"] = "0";
524 void Preamble::handle_hyperref(vector<string> & options)
526 // FIXME swallow inputencoding changes that might surround the
527 // hyperref setup if it was written by LyX
528 h_use_hyperref = "true";
529 // swallow "unicode=true", since LyX does always write that
530 vector<string>::iterator it =
531 find(options.begin(), options.end(), "unicode=true");
532 if (it != options.end())
534 it = find(options.begin(), options.end(), "pdfusetitle");
535 if (it != options.end()) {
536 h_pdf_pdfusetitle = "1";
539 string bookmarks = process_keyval_opt(options, "bookmarks");
540 if (bookmarks == "true")
541 h_pdf_bookmarks = "1";
542 else if (bookmarks == "false")
543 h_pdf_bookmarks = "0";
544 if (h_pdf_bookmarks == "1") {
545 string bookmarksnumbered =
546 process_keyval_opt(options, "bookmarksnumbered");
547 if (bookmarksnumbered == "true")
548 h_pdf_bookmarksnumbered = "1";
549 else if (bookmarksnumbered == "false")
550 h_pdf_bookmarksnumbered = "0";
551 string bookmarksopen =
552 process_keyval_opt(options, "bookmarksopen");
553 if (bookmarksopen == "true")
554 h_pdf_bookmarksopen = "1";
555 else if (bookmarksopen == "false")
556 h_pdf_bookmarksopen = "0";
557 if (h_pdf_bookmarksopen == "1") {
558 string bookmarksopenlevel =
559 process_keyval_opt(options, "bookmarksopenlevel");
560 if (!bookmarksopenlevel.empty())
561 h_pdf_bookmarksopenlevel = bookmarksopenlevel;
564 string breaklinks = process_keyval_opt(options, "breaklinks");
565 if (breaklinks == "true")
566 h_pdf_breaklinks = "1";
567 else if (breaklinks == "false")
568 h_pdf_breaklinks = "0";
569 string pdfborder = process_keyval_opt(options, "pdfborder");
570 if (pdfborder == "{0 0 0}")
571 h_pdf_pdfborder = "1";
572 else if (pdfborder == "{0 0 1}")
573 h_pdf_pdfborder = "0";
574 string backref = process_keyval_opt(options, "backref");
575 if (!backref.empty())
576 h_pdf_backref = backref;
577 string colorlinks = process_keyval_opt(options, "colorlinks");
578 if (colorlinks == "true")
579 h_pdf_colorlinks = "1";
580 else if (colorlinks == "false")
581 h_pdf_colorlinks = "0";
582 string pdfpagemode = process_keyval_opt(options, "pdfpagemode");
583 if (!pdfpagemode.empty())
584 h_pdf_pagemode = pdfpagemode;
585 string pdftitle = process_keyval_opt(options, "pdftitle");
586 if (!pdftitle.empty()) {
587 h_pdf_title = remove_braces(pdftitle);
589 string pdfauthor = process_keyval_opt(options, "pdfauthor");
590 if (!pdfauthor.empty()) {
591 h_pdf_author = remove_braces(pdfauthor);
593 string pdfsubject = process_keyval_opt(options, "pdfsubject");
594 if (!pdfsubject.empty())
595 h_pdf_subject = remove_braces(pdfsubject);
596 string pdfkeywords = process_keyval_opt(options, "pdfkeywords");
597 if (!pdfkeywords.empty())
598 h_pdf_keywords = remove_braces(pdfkeywords);
599 if (!options.empty()) {
600 if (!h_pdf_quoted_options.empty())
601 h_pdf_quoted_options += ',';
602 h_pdf_quoted_options += join(options, ",");
608 void Preamble::handle_geometry(vector<string> & options)
610 h_use_geometry = "true";
611 vector<string>::iterator it;
613 if ((it = find(options.begin(), options.end(), "landscape")) != options.end()) {
614 h_paperorientation = "landscape";
618 // keyval version: "paper=letter"
619 string paper = process_keyval_opt(options, "paper");
621 h_papersize = paper + "paper";
622 // alternative version: "letterpaper"
623 handle_opt(options, known_paper_sizes, h_papersize);
624 delete_opt(options, known_paper_sizes);
626 char const * const * margin = known_paper_margins;
627 for (; *margin; ++margin) {
628 string value = process_keyval_opt(options, *margin);
629 if (!value.empty()) {
630 int k = margin - known_paper_margins;
631 string name = known_coded_paper_margins[k];
632 h_margins += '\\' + name + ' ' + value + '\n';
638 void Preamble::handle_package(Parser &p, string const & name,
639 string const & opts, bool in_lyx_preamble)
641 vector<string> options = split_options(opts);
642 add_package(name, options);
644 char const * const * where = 0;
646 if (is_known(name, known_xetex_packages)) {
648 h_use_non_tex_fonts = "true";
649 registerAutomaticallyLoadedPackage("fontspec");
650 if (h_inputencoding == "auto")
651 p.setEncoding("utf8");
655 if (is_known(name, known_roman_fonts))
658 if (name == "fourier") {
659 h_font_roman = "utopia";
660 // when font uses real small capitals
661 if (opts == "expert")
665 else if (name == "mathpazo")
666 h_font_roman = "palatino";
668 else if (name == "mathptmx")
669 h_font_roman = "times";
672 if (is_known(name, known_sans_fonts)) {
676 h_font_sf_scale = scale_as_percentage(scale);
681 if (is_known(name, known_typewriter_fonts)) {
682 // fourier can be set as roman font _only_
683 // fourier as typewriter is handled in handling of \ttdefault
684 if (name != "fourier") {
685 h_font_typewriter = name;
688 h_font_tt_scale = scale_as_percentage(scale);
693 // font uses old-style figure
697 // after the detection and handling of special cases, we can remove the
698 // fonts, otherwise they would appear in the preamble, see bug #7856
699 if (is_known(name, known_roman_fonts) || is_known(name, known_sans_fonts)
700 || is_known(name, known_typewriter_fonts))
703 else if (name == "amsmath" || name == "amssymb" ||
704 name == "esint" || name == "mhchem" || name == "mathdots" ||
705 name == "mathtools" || name == "undertilde")
706 h_use_packages[name] = "2";
708 else if (name == "babel") {
709 h_language_package = "default";
710 // One might think we would have to do nothing if babel is loaded
711 // without any options to prevent pollution of the preamble with this
712 // babel call in every roundtrip.
713 // But the user could have defined babel-specific things afterwards. So
714 // we need to keep it in the preamble to prevent cases like bug #7861.
716 // check if more than one option was used - used later for inputenc
717 if (options.begin() != options.end() - 1)
718 one_language = false;
719 // babel takes the last language of the option of its \usepackage
720 // call as document language. If there is no such language option, the
721 // last language in the documentclass options is used.
722 handle_opt(options, known_languages, h_language);
723 // translate the babel name to a LyX name
724 h_language = babel2lyx(h_language);
725 // for Japanese we assume EUC-JP as encoding
726 // but we cannot determine the exact encoding and thus output also a note
727 if (h_language == "japanese") {
728 h_inputencoding = "euc";
729 p.setEncoding("EUC-JP");
730 is_nonCJKJapanese = true;
731 // in this case babel can be removed from the preamble
732 registerAutomaticallyLoadedPackage("babel");
734 // If babel is called with options, LyX puts them by default into the
735 // document class options. This works for most languages, except
736 // for Latvian, Lithuanian, Mongolian, Turkmen and Vietnamese and
737 // perhaps in future others.
738 // Therefore keep the babel call as it is as the user might have
740 h_preamble << "\\usepackage[" << opts << "]{babel}\n";
742 delete_opt(options, known_languages);
745 h_preamble << "\\usepackage{babel}\n";
748 else if (name == "polyglossia") {
749 h_language_package = "default";
750 h_default_output_format = "pdf4";
751 h_use_non_tex_fonts = "true";
753 registerAutomaticallyLoadedPackage("xunicode");
754 if (h_inputencoding == "auto")
755 p.setEncoding("utf8");
758 else if (name == "CJK") {
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 ((where = is_known(name, known_languages)))
837 h_language = known_coded_languages[where - 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 (is_known(h_language, known_danish_quotes_languages))
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() == "newtheorem") {
1432 string const name = p.getArg('{', '}');
1433 string const opt1 = p.getFullOpt();
1434 string const opt2 = p.getFullOpt();
1435 string const body = p.verbatim_item();
1436 string const opt3 = p.getFullOpt();
1438 add_known_theorem(name, opt1, !opt2.empty(),
1439 from_utf8("\\newtheorem{" + name + '}' +
1440 opt1 + opt2 + '{' + body + '}' + opt3));
1442 if (!in_lyx_preamble)
1443 h_preamble << "\\newtheorem{" << name << '}'
1444 << opt1 << opt2 << '{' << '}' << opt3;
1447 else if (t.cs() == "def") {
1448 string name = p.get_token().cs();
1449 // In fact, name may be more than the name:
1450 // In the test case of bug 8116
1451 // name == "csname SF@gobble@opt \endcsname".
1452 // Therefore, we need to use asInput() instead of cs().
1453 while (p.next_token().cat() != catBegin)
1454 name += p.get_token().asInput();
1455 if (!in_lyx_preamble)
1456 h_preamble << "\\def\\" << name << '{'
1457 << p.verbatim_item() << "}";
1460 else if (t.cs() == "newcolumntype") {
1461 string const name = p.getArg('{', '}');
1462 trimSpaceAndEol(name);
1464 string opts = p.getOpt();
1465 if (!opts.empty()) {
1466 istringstream is(string(opts, 1));
1469 special_columns[name[0]] = nargs;
1470 h_preamble << "\\newcolumntype{" << name << "}";
1472 h_preamble << "[" << nargs << "]";
1473 h_preamble << "{" << p.verbatim_item() << "}";
1476 else if (t.cs() == "setcounter") {
1477 string const name = p.getArg('{', '}');
1478 string const content = p.getArg('{', '}');
1479 if (name == "secnumdepth")
1480 h_secnumdepth = content;
1481 else if (name == "tocdepth")
1482 h_tocdepth = content;
1484 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
1487 else if (t.cs() == "setlength") {
1488 string const name = p.verbatim_item();
1489 string const content = p.verbatim_item();
1490 // the paragraphs are only not indented when \parindent is set to zero
1491 if (name == "\\parindent" && content != "") {
1492 if (content[0] == '0')
1493 h_paragraph_separation = "skip";
1495 h_paragraph_indentation = translate_len(content);
1496 } else if (name == "\\parskip") {
1497 if (content == "\\smallskipamount")
1498 h_defskip = "smallskip";
1499 else if (content == "\\medskipamount")
1500 h_defskip = "medskip";
1501 else if (content == "\\bigskipamount")
1502 h_defskip = "bigskip";
1504 h_defskip = content;
1506 h_preamble << "\\setlength{" << name << "}{" << content << "}";
1509 else if (t.cs() == "onehalfspacing")
1510 h_spacing = "onehalf";
1512 else if (t.cs() == "doublespacing")
1513 h_spacing = "double";
1515 else if (t.cs() == "setstretch")
1516 h_spacing = "other " + p.verbatim_item();
1518 else if (t.cs() == "synctex") {
1519 // the scheme is \synctex=value
1520 // where value can only be "1" or "-1"
1521 h_output_sync = "1";
1522 // there can be any character behind the value (e.g. a linebreak or a '\'
1523 // therefore we extract it char by char
1525 string value = p.get_token().asInput();
1527 value += p.get_token().asInput();
1528 h_output_sync_macro = "\\synctex=" + value;
1531 else if (t.cs() == "begin") {
1532 string const name = p.getArg('{', '}');
1533 if (name == "document")
1535 h_preamble << "\\begin{" << name << "}";
1538 else if (t.cs() == "geometry") {
1539 vector<string> opts = split_options(p.getArg('{', '}'));
1540 handle_geometry(opts);
1543 else if (t.cs() == "definecolor") {
1544 string const color = p.getArg('{', '}');
1545 string const space = p.getArg('{', '}');
1546 string const value = p.getArg('{', '}');
1547 if (color == "document_fontcolor" && space == "rgb") {
1548 RGBColor c(RGBColorFromLaTeX(value));
1549 h_fontcolor = X11hexname(c);
1550 } else if (color == "note_fontcolor" && space == "rgb") {
1551 RGBColor c(RGBColorFromLaTeX(value));
1552 h_notefontcolor = X11hexname(c);
1553 } else if (color == "page_backgroundcolor" && space == "rgb") {
1554 RGBColor c(RGBColorFromLaTeX(value));
1555 h_backgroundcolor = X11hexname(c);
1556 } else if (color == "shadecolor" && space == "rgb") {
1557 RGBColor c(RGBColorFromLaTeX(value));
1558 h_boxbgcolor = X11hexname(c);
1560 h_preamble << "\\definecolor{" << color
1561 << "}{" << space << "}{" << value
1566 else if (t.cs() == "bibliographystyle")
1567 h_biblio_style = p.verbatim_item();
1569 else if (t.cs() == "jurabibsetup") {
1570 // FIXME p.getArg('{', '}') is most probably wrong (it
1571 // does not handle nested braces).
1572 // Use p.verbatim_item() instead.
1573 vector<string> jurabibsetup =
1574 split_options(p.getArg('{', '}'));
1575 // add jurabibsetup to the jurabib package options
1576 add_package("jurabib", jurabibsetup);
1577 if (!jurabibsetup.empty()) {
1578 h_preamble << "\\jurabibsetup{"
1579 << join(jurabibsetup, ",") << '}';
1583 else if (t.cs() == "hypersetup") {
1584 vector<string> hypersetup =
1585 split_options(p.verbatim_item());
1586 // add hypersetup to the hyperref package options
1587 handle_hyperref(hypersetup);
1588 if (!hypersetup.empty()) {
1589 h_preamble << "\\hypersetup{"
1590 << join(hypersetup, ",") << '}';
1594 else if (is_known(t.cs(), known_if_3arg_commands)) {
1595 // prevent misparsing of \usepackage if it is used
1596 // as an argument (see e.g. our own output of
1597 // \@ifundefined above)
1598 string const arg1 = p.verbatim_item();
1599 string const arg2 = p.verbatim_item();
1600 string const arg3 = p.verbatim_item();
1601 // test case \@ifundefined{date}{}{\date{}}
1602 if (t.cs() == "@ifundefined" && arg1 == "date" &&
1603 arg2.empty() && arg3 == "\\date{}") {
1604 h_suppress_date = "true";
1605 // older tex2lyx versions did output
1606 // \@ifundefined{definecolor}{\usepackage{color}}{}
1607 } else if (t.cs() == "@ifundefined" &&
1608 arg1 == "definecolor" &&
1609 arg2 == "\\usepackage{color}" &&
1611 if (!in_lyx_preamble)
1612 h_preamble << package_beg_sep
1615 << "\\@ifundefined{definecolor}{color}{}"
1618 //\@ifundefined{showcaptionsetup}{}{%
1619 // \PassOptionsToPackage{caption=false}{subfig}}
1620 // that LyX uses for subfloats
1621 } else if (t.cs() == "@ifundefined" &&
1622 arg1 == "showcaptionsetup" && arg2.empty()
1623 && arg3 == "%\n \\PassOptionsToPackage{caption=false}{subfig}") {
1625 } else if (!in_lyx_preamble) {
1626 h_preamble << t.asInput()
1627 << '{' << arg1 << '}'
1628 << '{' << arg2 << '}'
1629 << '{' << arg3 << '}';
1633 else if (is_known(t.cs(), known_if_commands)) {
1634 // must not parse anything in conditional code, since
1635 // LyX would output the parsed contents unconditionally
1636 if (!in_lyx_preamble)
1637 h_preamble << t.asInput();
1638 handle_if(p, in_lyx_preamble);
1641 else if (!t.cs().empty() && !in_lyx_preamble)
1642 h_preamble << '\\' << t.cs();
1645 // remove the whitespace
1648 // Force textclass if the user wanted it
1649 if (!forceclass.empty())
1650 h_textclass = forceclass;
1651 tc.setName(h_textclass);
1653 cerr << "Error: Could not read layout file for textclass \"" << h_textclass << "\"." << endl;
1656 if (h_papersides.empty()) {
1659 h_papersides = ss.str();
1662 // If the CJK package is used we cannot set the document language from
1663 // the babel options. Instead, we guess which language is used most
1664 // and set this one.
1665 default_language = h_language;
1666 if (is_full_document && auto_packages.find("CJK") != auto_packages.end()) {
1668 h_language = guessLanguage(p, default_language);
1674 string babel2lyx(string const & language)
1676 char const * const * where = is_known(language, known_languages);
1678 return known_coded_languages[where - known_languages];
1683 string Preamble::polyglossia2lyx(string const & language)
1685 char const * const * where = is_known(language, polyglossia_languages);
1687 return coded_polyglossia_languages[where - polyglossia_languages];
1692 string rgbcolor2code(string const & name)
1694 char const * const * where = is_known(name, known_basic_colors);
1696 // "red", "green" etc
1697 return known_basic_color_codes[where - known_basic_colors];
1699 // "255,0,0", "0,255,0" etc
1700 RGBColor c(RGBColorFromLaTeX(name));
1701 return X11hexname(c);