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.
18 #include "LayoutFile.h"
21 #include "TextClass.h"
23 #include "support/convert.h"
24 #include "support/FileName.h"
25 #include "support/filetools.h"
26 #include "support/lstrings.h"
28 #include "support/regex.h"
38 using namespace lyx::support;
43 // special columntypes
44 extern map<char, int> special_columns;
46 map<string, vector<string> > used_packages;
48 // needed to handle encodings with babel
49 bool one_language = true;
53 //add this to known_languages when updating to lyxformat 266:
55 //add these to known_languages when updating to lyxformat 268:
56 //"chinese-simplified", "chinese-traditional", "japanese", "korean"
57 // Both changes require first that support for non-babel languages (CJK,
59 // add turkmen for lyxformat 383
61 * known babel language names (including synonyms)
62 * not in standard babel: arabic, arabtex, belarusian, serbian-latin, thai
63 * not yet supported by LyX: kurmanji
64 * please keep this in sync with known_coded_languages line by line!
66 const char * const known_languages[] = {"acadian", "afrikaans", "albanian",
67 "american", "arabic", "arabtex", "austrian", "bahasa", "bahasai", "bahasam",
68 "basque", "belarusian", "brazil", "brazilian", "breton", "british", "bulgarian",
69 "canadian", "canadien", "catalan", "croatian", "czech", "danish", "dutch",
70 "english", "esperanto", "estonian", "farsi", "finnish", "francais", "french",
71 "frenchb", "frenchle", "frenchpro", "galician", "german", "germanb", "greek",
72 "hebrew", "hungarian", "icelandic", "indon", "indonesian", "interlingua",
73 "irish", "italian", "kazakh", "latin", "latvian", "lithuanian", "lowersorbian",
74 "lsorbian", "magyar", "malay", "meyalu", "mongolian", "naustrian", "newzealand",
75 "ngerman", "ngermanb", "norsk", "nynorsk", "polutonikogreek", "polish",
76 "portuges", "portuguese", "romanian", "russian", "russianb", "samin",
77 "scottish", "serbian", "serbian-latin", "slovak", "slovene", "spanish",
78 "swedish", "thai", "turkish", "ukraineb", "ukrainian", "uppersorbian",
79 "UKenglish", "USenglish", "usorbian", "vietnam", "welsh", 0};
82 * the same as known_languages with .lyx names
83 * please keep this in sync with known_languages line by line!
85 const char * const known_coded_languages[] = {"french", "afrikaans", "albanian",
86 "american", "arabic_arabi", "arabic_arabtex", "austrian", "bahasa", "bahasa", "bahasam",
87 "basque", "belarusian", "brazilian", "brazilian", "breton", "british", "bulgarian",
88 "canadian", "canadien", "catalan", "croatian", "czech", "danish", "dutch",
89 "english", "esperanto", "estonian", "farsi", "finnish", "french", "french",
90 "french", "french", "french", "galician", "german", "german", "greek",
91 "hebrew", "magyar", "icelandic", "bahasa", "bahasa", "interlingua",
92 "irish", "italian", "kazakh", "latin", "latvian", "lithuanian", "lowersorbian",
93 "lowersorbian", "magyar", "bahasam", "bahasam", "mongolian", "naustrian", "english",
94 "ngerman", "ngerman", "norsk", "nynorsk", "polutonikogreek", "polish",
95 "portuguese", "portuguese", "romanian", "russian", "russian", "samin",
96 "scottish", "serbian", "serbian-latin", "slovak", "slovene", "spanish",
97 "swedish", "thai", "turkish", "ukrainian", "ukrainian", "uppersorbian",
98 "uppersorbian", "english", "english", "vietnamese", "welsh", 0};
100 /// languages with english quotes (.lyx names)
101 const char * const known_english_quotes_languages[] = {"american", "bahasa",
102 "bahasam", "brazilian", "canadian", "chinese-simplified", "english",
103 "esperanto", "hebrew", "irish", "korean", "portuguese", "scottish", "thai", 0};
105 //add this to known_french_quotes_languages when updating to
106 //lyxformat 383: "turkmen"
107 /// languages with french quotes (.lyx names)
108 const char * const known_french_quotes_languages[] = {"albanian",
109 "arabic_arabi", "arabic_arabtex", "basque", "canadien", "catalan", "french",
110 "galician", "greek", "italian", "norsk", "nynorsk", "polutonikogreek",
111 "russian", "spanish", "spanish-mexico", "turkish", "ukrainian", "vietnamese", 0};
113 /// languages with german quotes (.lyx names)
114 const char * const known_german_quotes_languages[] = {"austrian", "bulgarian",
115 "czech", "german", "icelandic", "lithuanian", "lowersorbian", "naustrian",
116 "ngerman", "serbian", "serbian-latin", "slovak", "slovene", "uppersorbian", 0};
118 /// languages with polish quotes (.lyx names)
119 const char * const known_polish_quotes_languages[] = {"afrikaans", "croatian",
120 "dutch", "estonian", "magyar", "polish", "romanian", 0};
122 /// languages with swedish quotes (.lyx names)
123 const char * const known_swedish_quotes_languages[] = {"finnish",
126 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
128 const char * const known_roman_fonts[] = { "ae", "bookman", "charter",
129 "cmr", "fourier", "lmodern", "mathpazo", "mathptmx", "newcent", 0};
131 const char * const known_sans_fonts[] = { "avant", "berasans", "cmbr", "cmss",
132 "helvet", "lmss", 0};
134 const char * const known_typewriter_fonts[] = { "beramono", "cmtl", "cmtt",
135 "courier", "lmtt", "luximono", "fourier", "lmodern", "mathpazo", "mathptmx",
138 const char * const known_paper_sizes[] = { "a3paper", "b3paper", "a4paper",
139 "b4paper", "a5paper", "b5paper", "executivepaper", "legalpaper",
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 /// conditional commands with three arguments like \@ifundefined{}{}{}
158 const char * const known_if_3arg_commands[] = {"@ifundefined", "IfFileExists",
162 ostringstream h_preamble;
163 string h_textclass = "article";
164 string h_use_default_options = "false";
166 string h_language = "english";
167 string h_inputencoding = "auto";
168 string h_font_roman = "default";
169 string h_font_sans = "default";
170 string h_font_typewriter = "default";
171 string h_font_default_family = "default";
172 string h_font_sc = "false";
173 string h_font_osf = "false";
174 string h_font_sf_scale = "100";
175 string h_font_tt_scale = "100";
176 string h_graphics = "default";
177 string h_float_placement;
178 string h_paperfontsize = "default";
179 string h_spacing = "single";
180 string h_use_hyperref = "0";
183 string h_pdf_subject;
184 string h_pdf_keywords;
185 string h_pdf_bookmarks = "1";
186 string h_pdf_bookmarksnumbered = "0";
187 string h_pdf_bookmarksopen = "0";
188 string h_pdf_bookmarksopenlevel = "1";
189 string h_pdf_breaklinks = "0";
190 string h_pdf_pdfborder = "0";
191 string h_pdf_colorlinks = "0";
192 string h_pdf_backref = "section";
193 string h_pdf_pdfusetitle = "1";
194 string h_pdf_pagemode;
195 string h_pdf_quoted_options;
196 string h_papersize = "default";
197 string h_use_geometry = "false";
198 string h_use_amsmath = "1";
199 string h_use_esint = "1";
200 string h_cite_engine = "basic";
201 string h_use_bibtopic = "false";
202 string h_paperorientation = "portrait";
203 string h_notefontcolor;
204 string h_secnumdepth = "3";
205 string h_tocdepth = "3";
206 string h_paragraph_separation = "indent";
207 string h_defskip = "medskip";
208 string h_paragraph_indentation = "default";
209 string h_quotes_language = "english";
210 string h_papercolumns = "1";
212 string h_paperpagestyle = "default";
213 string h_listings_params;
214 string h_tracking_changes = "false";
215 string h_output_changes = "false";
219 // returns true if at least one of the options in what has been found
220 bool handle_opt(vector<string> & opts, char const * const * what, string & target)
226 // the last language option is the document language (for babel and LyX)
227 // the last size option is the document font size
228 vector<string>::iterator it;
229 vector<string>::iterator position = opts.begin();
230 for (; *what; ++what) {
231 it = find(opts.begin(), opts.end(), *what);
232 if (it != opts.end()) {
233 if (it >= position) {
244 void delete_opt(vector<string> & opts, char const * const * what)
249 // remove found options from the list
250 // do this after handle_opt to avoid potential memory leaks
251 vector<string>::iterator it;
252 for (; *what; ++what) {
253 it = find(opts.begin(), opts.end(), *what);
254 if (it != opts.end())
261 * Split a package options string (keyval format) into a vector.
263 * authorformat=smallcaps,
265 * titleformat=colonsep,
266 * bibformat={tabular,ibidem,numbered}
268 vector<string> split_options(string const & input)
270 vector<string> options;
274 Token const & t = p.get_token();
275 if (t.asInput() == ",") {
276 options.push_back(trim(option));
278 } else if (t.asInput() == "=") {
281 if (p.next_token().asInput() == "{")
282 option += '{' + p.getArg('{', '}') + '}';
283 } else if (t.cat() != catSpace)
284 option += t.asInput();
288 options.push_back(trim(option));
295 * Retrieve a keyval option "name={value with=sign}" named \p name from
296 * \p options and return the value.
297 * The found option is also removed from \p options.
299 string process_keyval_opt(vector<string> & options, string name)
301 for (size_t i = 0; i < options.size(); ++i) {
302 vector<string> option;
303 split(options[i], option, '=');
304 if (option.size() < 2)
306 if (option[0] == name) {
307 options.erase(options.begin() + i);
308 option.erase(option.begin());
309 return join(option, "=");
317 * Add package \p name with options \p options to used_packages.
318 * Remove options from \p options that we don't want to output.
320 void add_package(string const & name, vector<string> & options)
322 // every package inherits the global options
323 if (used_packages.find(name) == used_packages.end())
324 used_packages[name] = split_options(h_options);
326 vector<string> & v = used_packages[name];
327 v.insert(v.end(), options.begin(), options.end());
328 if (name == "jurabib") {
329 // Don't output the order argument (see the cite command
330 // handling code in text.cpp).
331 vector<string>::iterator end =
332 remove(options.begin(), options.end(), "natbiborder");
333 end = remove(options.begin(), end, "jurabiborder");
334 options.erase(end, options.end());
339 // Given is a string like "scaled=0.9", return 0.9 * 100
340 string const scale_as_percentage(string const & scale)
342 string::size_type pos = scale.find('=');
343 if (pos != string::npos) {
344 string value = scale.substr(pos + 1);
346 return convert<string>(100 * convert<double>(value));
348 // If the input string didn't match our expectations.
349 // return the default value "100"
354 string remove_braces(string const & value)
358 if (value[0] == '{' && value[value.length()-1] == '}')
359 return value.substr(1, value.length()-2);
364 void handle_hyperref(vector<string> & options)
366 // FIXME swallow inputencoding changes that might surround the
367 // hyperref setup if it was written by LyX
368 h_use_hyperref = "1";
369 // swallow "unicode=true", since LyX does always write that
370 vector<string>::iterator it =
371 find(options.begin(), options.end(), "unicode=true");
372 if (it != options.end())
374 it = find(options.begin(), options.end(), "pdfusetitle");
375 if (it != options.end()) {
376 h_pdf_pdfusetitle = "1";
379 string bookmarks = process_keyval_opt(options, "bookmarks");
380 if (bookmarks == "true")
381 h_pdf_bookmarks = "1";
382 else if (bookmarks == "false")
383 h_pdf_bookmarks = "0";
384 if (h_pdf_bookmarks == "1") {
385 string bookmarksnumbered =
386 process_keyval_opt(options, "bookmarksnumbered");
387 if (bookmarksnumbered == "true")
388 h_pdf_bookmarksnumbered = "1";
389 else if (bookmarksnumbered == "false")
390 h_pdf_bookmarksnumbered = "0";
391 string bookmarksopen =
392 process_keyval_opt(options, "bookmarksopen");
393 if (bookmarksopen == "true")
394 h_pdf_bookmarksopen = "1";
395 else if (bookmarksopen == "false")
396 h_pdf_bookmarksopen = "0";
397 if (h_pdf_bookmarksopen == "1") {
398 string bookmarksopenlevel =
399 process_keyval_opt(options, "bookmarksopenlevel");
400 if (!bookmarksopenlevel.empty())
401 h_pdf_bookmarksopenlevel = bookmarksopenlevel;
404 string breaklinks = process_keyval_opt(options, "breaklinks");
405 if (breaklinks == "true")
406 h_pdf_breaklinks = "1";
407 else if (breaklinks == "false")
408 h_pdf_breaklinks = "0";
409 string pdfborder = process_keyval_opt(options, "pdfborder");
410 if (pdfborder == "{0 0 0}")
411 h_pdf_pdfborder = "1";
412 else if (pdfborder == "{0 0 1}")
413 h_pdf_pdfborder = "0";
414 string backref = process_keyval_opt(options, "backref");
415 if (!backref.empty())
416 h_pdf_backref = backref;
417 string colorlinks = process_keyval_opt(options, "colorlinks");
418 if (colorlinks == "true")
419 h_pdf_colorlinks = "1";
420 else if (colorlinks == "false")
421 h_pdf_colorlinks = "0";
422 string pdfpagemode = process_keyval_opt(options, "pdfpagemode");
423 if (!pdfpagemode.empty())
424 h_pdf_pagemode = pdfpagemode;
425 string pdftitle = process_keyval_opt(options, "pdftitle");
426 if (!pdftitle.empty()) {
427 h_pdf_title = remove_braces(pdftitle);
429 string pdfauthor = process_keyval_opt(options, "pdfauthor");
430 if (!pdfauthor.empty()) {
431 h_pdf_author = remove_braces(pdfauthor);
433 string pdfsubject = process_keyval_opt(options, "pdfsubject");
434 if (!pdfsubject.empty())
435 h_pdf_subject = remove_braces(pdfsubject);
436 string pdfkeywords = process_keyval_opt(options, "pdfkeywords");
437 if (!pdfkeywords.empty())
438 h_pdf_keywords = remove_braces(pdfkeywords);
439 if (!options.empty()) {
440 if (!h_pdf_quoted_options.empty())
441 h_pdf_quoted_options += ',';
442 h_pdf_quoted_options += join(options, ",");
448 void handle_package(Parser &p, string const & name, string const & opts,
449 bool in_lyx_preamble)
451 vector<string> options = split_options(opts);
452 add_package(name, options);
456 if (is_known(name, known_roman_fonts)) {
461 if (name == "fourier") {
462 h_font_roman = "utopia";
463 // when font uses real small capitals
464 if (opts == "expert")
468 if (name == "mathpazo")
469 h_font_roman = "palatino";
471 if (name == "mathptmx")
472 h_font_roman = "times";
475 if (is_known(name, known_sans_fonts)) {
479 h_font_sf_scale = scale_as_percentage(scale);
484 if (is_known(name, known_typewriter_fonts)) {
485 h_font_typewriter = name;
488 h_font_tt_scale = scale_as_percentage(scale);
492 // font uses old-style figure
496 else if (name == "amsmath" || name == "amssymb")
499 else if (name == "esint")
502 else if (name == "babel" && !opts.empty()) {
503 // check if more than one option was used - used later for inputenc
504 // in case inputenc is parsed before babel, set the encoding to auto
505 if (options.begin() != options.end() - 1) {
506 one_language = false;
507 h_inputencoding = "auto";
509 // babel takes the last language of the option of its \usepackage
510 // call as document language. If there is no such language option, the
511 // last language in the documentclass options is used.
512 handle_opt(options, known_languages, h_language);
513 delete_opt(options, known_languages);
516 else if (name == "fontenc")
519 else if (name == "inputenc") {
520 // h_inputencoding is only set when there is not more than one
521 // inputenc option because otherwise h_inputencoding must be
522 // set to "auto" (the default encoding of the document language)
523 // Therefore check for the "," character.
524 // It is also only set when there is not more then one babel
525 // language option but this is handled in the routine for babel.
526 if (opts.find(",") == string::npos && one_language == true)
527 h_inputencoding = opts;
528 if (!options.empty())
529 p.setEncoding(options.back());
533 else if (name == "makeidx")
536 else if (name == "prettyref")
539 else if (name == "varioref")
542 else if (name == "verbatim")
545 else if (name == "nomencl")
548 else if (name == "textcomp")
551 else if (name == "url")
554 else if (LYX_FORMAT >= 408 && name == "subscript")
557 else if (name == "color") {
558 // with the following command this package is only loaded when needed for
559 // undefined colors, since we only support the predefined colors
560 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
563 else if (name == "graphicx")
566 else if (name == "setspace")
569 else if (name == "geometry")
570 ; // Ignore this, the geometry settings are made by the \geometry
571 // command. This command is handled below.
573 else if (is_known(name, known_languages))
576 else if (name == "natbib") {
577 h_cite_engine = "natbib_authoryear";
578 vector<string>::iterator it =
579 find(options.begin(), options.end(), "authoryear");
580 if (it != options.end())
583 it = find(options.begin(), options.end(), "numbers");
584 if (it != options.end()) {
585 h_cite_engine = "natbib_numerical";
591 else if (name == "jurabib")
592 h_cite_engine = "jurabib";
594 else if (name == "hyperref")
595 handle_hyperref(options);
597 else if (!in_lyx_preamble) {
599 h_preamble << "\\usepackage{" << name << "}";
601 h_preamble << "\\usepackage[" << opts << "]{"
607 // We need to do something with the options...
608 if (!options.empty())
609 cerr << "Ignoring options '" << join(options, ",")
610 << "' of package " << name << '.' << endl;
612 // remove the whitespace
617 void handle_if(Parser & p, bool in_lyx_preamble)
620 Token t = p.get_token();
621 if (t.cat() == catEscape &&
622 is_known(t.cs(), known_if_commands))
623 handle_if(p, in_lyx_preamble);
625 if (!in_lyx_preamble)
626 h_preamble << t.asInput();
627 if (t.cat() == catEscape && t.cs() == "fi")
634 void end_preamble(ostream & os, TextClass const & /*textclass*/)
636 // translate from babel to LyX names
637 h_language = babel2lyx(h_language);
639 // set the quote language
640 // LyX only knows the following quotes languages:
641 // english, swedish, german, polish, french and danish
642 // (quotes for "japanese" and "chinese-traditional" are missing because
643 // they wouldn't be useful: http://www.lyx.org/trac/ticket/6383)
644 // conversion list taken from
645 // http://en.wikipedia.org/wiki/Quotation_mark,_non-English_usage
646 // (quotes for kazakh and interlingua are unknown)
648 if (h_language == "danish")
649 h_quotes_language = "danish";
651 else if (is_known(h_language, known_french_quotes_languages))
652 h_quotes_language = "french";
654 else if (is_known(h_language, known_german_quotes_languages))
655 h_quotes_language = "german";
657 else if (is_known(h_language, known_polish_quotes_languages))
658 h_quotes_language = "polish";
660 else if (is_known(h_language, known_swedish_quotes_languages))
661 h_quotes_language = "swedish";
663 else if (is_known(h_language, known_english_quotes_languages))
664 h_quotes_language = "english";
666 // output the LyX file settings
667 os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
668 << "\\lyxformat " << LYX_FORMAT << '\n'
669 << "\\begin_document\n"
670 << "\\begin_header\n"
671 << "\\textclass " << h_textclass << "\n";
672 if (!h_preamble.str().empty())
673 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
674 if (!h_options.empty())
675 os << "\\options " << h_options << "\n";
676 os << "\\use_default_options " << h_use_default_options << "\n"
677 << "\\language " << h_language << "\n"
678 << "\\inputencoding " << h_inputencoding << "\n"
679 << "\\font_roman " << h_font_roman << "\n"
680 << "\\font_sans " << h_font_sans << "\n"
681 << "\\font_typewriter " << h_font_typewriter << "\n"
682 << "\\font_default_family " << h_font_default_family << "\n"
683 << "\\font_sc " << h_font_sc << "\n"
684 << "\\font_osf " << h_font_osf << "\n"
685 << "\\font_sf_scale " << h_font_sf_scale << "\n"
686 << "\\font_tt_scale " << h_font_tt_scale << "\n"
687 << "\\graphics " << h_graphics << "\n";
688 if (!h_float_placement.empty())
689 os << "\\float_placement " << h_float_placement << "\n";
690 os << "\\paperfontsize " << h_paperfontsize << "\n"
691 << "\\spacing " << h_spacing << "\n"
692 << "\\use_hyperref " << h_use_hyperref << '\n';
693 if (h_use_hyperref == "1") {
694 if (!h_pdf_title.empty())
695 os << "\\pdf_title \"" << h_pdf_title << "\"\n";
696 if (!h_pdf_author.empty())
697 os << "\\pdf_author \"" << h_pdf_author << "\"\n";
698 if (!h_pdf_subject.empty())
699 os << "\\pdf_subject \"" << h_pdf_subject << "\"\n";
700 if (!h_pdf_keywords.empty())
701 os << "\\pdf_keywords \"" << h_pdf_keywords << "\"\n";
702 os << "\\pdf_bookmarks " << h_pdf_bookmarks << "\n"
703 "\\pdf_bookmarksnumbered " << h_pdf_bookmarksnumbered << "\n"
704 "\\pdf_bookmarksopen " << h_pdf_bookmarksopen << "\n"
705 "\\pdf_bookmarksopenlevel " << h_pdf_bookmarksopenlevel << "\n"
706 "\\pdf_breaklinks " << h_pdf_breaklinks << "\n"
707 "\\pdf_pdfborder " << h_pdf_pdfborder << "\n"
708 "\\pdf_colorlinks " << h_pdf_colorlinks << "\n"
709 "\\pdf_backref " << h_pdf_backref << "\n"
710 "\\pdf_pdfusetitle " << h_pdf_pdfusetitle << '\n';
711 if (!h_pdf_pagemode.empty())
712 os << "\\pdf_pagemode " << h_pdf_pagemode << '\n';
713 if (!h_pdf_quoted_options.empty())
714 os << "\\pdf_quoted_options \"" << h_pdf_quoted_options << "\"\n";
716 os << "\\papersize " << h_papersize << "\n"
717 << "\\use_geometry " << h_use_geometry << "\n"
718 << "\\use_amsmath " << h_use_amsmath << "\n"
719 << "\\use_esint " << h_use_esint << "\n"
720 << "\\cite_engine " << h_cite_engine << "\n"
721 << "\\use_bibtopic " << h_use_bibtopic << "\n"
722 << "\\paperorientation " << h_paperorientation << '\n';
723 if (LYX_FORMAT >= 382 && !h_notefontcolor.empty())
724 os << "\\notefontcolor " << h_notefontcolor << '\n';
726 << "\\secnumdepth " << h_secnumdepth << "\n"
727 << "\\tocdepth " << h_tocdepth << "\n"
728 << "\\paragraph_separation " << h_paragraph_separation << "\n";
729 if (LYX_FORMAT < 365 || h_paragraph_separation == "skip")
730 os << "\\defskip " << h_defskip << "\n";
732 os << "\\paragraph_indentation " << h_paragraph_indentation << "\n";
733 os << "\\quotes_language " << h_quotes_language << "\n"
734 << "\\papercolumns " << h_papercolumns << "\n"
735 << "\\papersides " << h_papersides << "\n"
736 << "\\paperpagestyle " << h_paperpagestyle << "\n";
737 if (!h_listings_params.empty())
738 os << "\\listings_params " << h_listings_params << "\n";
739 os << "\\tracking_changes " << h_tracking_changes << "\n"
740 << "\\output_changes " << h_output_changes << "\n"
741 << "\\end_header\n\n"
743 // clear preamble for subdocuments
747 } // anonymous namespace
750 void parse_preamble(Parser & p, ostream & os,
751 string const & forceclass, TeX2LyXDocClass & tc)
753 // initialize fixed types
754 special_columns['D'] = 3;
755 bool is_full_document = false;
756 bool is_lyx_file = false;
757 bool in_lyx_preamble = false;
759 // determine whether this is a full document or a fragment for inclusion
761 Token const & t = p.get_token();
763 if (t.cat() == catEscape && t.cs() == "documentclass") {
764 is_full_document = true;
770 while (is_full_document && p.good()) {
771 Token const & t = p.get_token();
774 cerr << "t: " << t << "\n";
780 if (!in_lyx_preamble &&
781 (t.cat() == catLetter ||
782 t.cat() == catSuper ||
784 t.cat() == catOther ||
785 t.cat() == catMath ||
786 t.cat() == catActive ||
787 t.cat() == catBegin ||
789 t.cat() == catAlign ||
790 t.cat() == catParameter))
791 h_preamble << t.cs();
793 else if (!in_lyx_preamble &&
794 (t.cat() == catSpace || t.cat() == catNewline))
795 h_preamble << t.asInput();
797 else if (t.cat() == catComment) {
798 // regex to parse comments (currently not used)
799 static regex const islyxfile("%% LyX .* created this file");
800 static regex const usercommands("User specified LaTeX commands");
802 string const comment = t.asInput();
804 // magically switch encoding default if it looks like XeLaTeX
805 static string const magicXeLaTeX =
806 "% This document must be compiled with XeLaTeX ";
807 if (comment.size() > magicXeLaTeX.size()
808 && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
809 && h_inputencoding == "auto") {
810 cerr << "XeLaTeX comment found, switching to UTF8\n";
811 h_inputencoding = "utf8";
814 if (regex_search(comment, sub, islyxfile)) {
816 in_lyx_preamble = true;
817 } else if (is_lyx_file
818 && regex_search(comment, sub, usercommands))
819 in_lyx_preamble = false;
820 else if (!in_lyx_preamble)
821 h_preamble << t.asInput();
824 else if (t.cs() == "pagestyle")
825 h_paperpagestyle = p.verbatim_item();
827 else if (t.cs() == "makeatletter") {
828 // LyX takes care of this
829 p.setCatCode('@', catLetter);
832 else if (t.cs() == "makeatother") {
833 // LyX takes care of this
834 p.setCatCode('@', catOther);
837 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
838 || t.cs() == "providecommand"
839 || t.cs() == "DeclareRobustCommand"
840 || t.cs() == "ProvideTextCommandDefault"
841 || t.cs() == "DeclareMathAccent") {
843 if (p.next_token().character() == '*') {
847 string const name = p.verbatim_item();
848 string const opt1 = p.getOpt();
849 string const opt2 = p.getFullOpt();
850 string const body = p.verbatim_item();
852 if (name == "\\rmdefault")
853 if (is_known(body, known_roman_fonts))
855 if (name == "\\sfdefault")
856 if (is_known(body, known_sans_fonts))
858 if (name == "\\ttdefault")
859 if (is_known(body, known_typewriter_fonts))
860 h_font_typewriter = body;
861 if (name == "\\familydefault") {
862 string family = body;
863 // remove leading "\"
864 h_font_default_family = family.erase(0,1);
866 // only non-lyxspecific stuff
867 if (!in_lyx_preamble) {
869 ss << '\\' << t.cs();
872 ss << '{' << name << '}' << opt1 << opt2
873 << '{' << body << "}";
874 h_preamble << ss.str();
876 // Add the command to the known commands
877 add_known_command(name, opt1, !opt2.empty());
879 ostream & out = in_preamble ? h_preamble : os;
880 out << "\\" << t.cs() << "{" << name << "}"
881 << opts << "{" << body << "}";
886 else if (t.cs() == "documentclass") {
887 vector<string>::iterator it;
888 vector<string> opts = split_options(p.getArg('[', ']'));
889 handle_opt(opts, known_fontsizes, h_paperfontsize);
890 delete_opt(opts, known_fontsizes);
891 // delete "pt" at the end
892 string::size_type i = h_paperfontsize.find("pt");
893 if (i != string::npos)
894 h_paperfontsize.erase(i);
895 // The documentclass options are always parsed before the options
896 // of the babel call so that a language cannot overwrite the babel
898 handle_opt(opts, known_languages, h_language);
899 delete_opt(opts, known_languages);
902 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
903 h_paperorientation = "landscape";
907 if ((it = find(opts.begin(), opts.end(), "oneside"))
912 if ((it = find(opts.begin(), opts.end(), "twoside"))
918 if ((it = find(opts.begin(), opts.end(), "onecolumn"))
920 h_papercolumns = "1";
923 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
925 h_papercolumns = "2";
929 // some size options are know to any document classes, other sizes
930 // are handled by the \geometry command of the geometry package
931 handle_opt(opts, known_class_paper_sizes, h_papersize);
932 delete_opt(opts, known_class_paper_sizes);
933 // the remaining options
934 h_options = join(opts, ",");
935 h_textclass = p.getArg('{', '}');
938 else if (t.cs() == "usepackage") {
939 string const options = p.getArg('[', ']');
940 string const name = p.getArg('{', '}');
941 vector<string> vecnames;
942 split(name, vecnames, ',');
943 vector<string>::const_iterator it = vecnames.begin();
944 vector<string>::const_iterator end = vecnames.end();
945 for (; it != end; ++it)
946 handle_package(p, trim(*it), options,
950 else if (t.cs() == "inputencoding") {
951 string const encoding = p.getArg('{','}');
952 h_inputencoding = encoding;
953 p.setEncoding(encoding);
956 else if (t.cs() == "newenvironment") {
957 string const name = p.getArg('{', '}');
959 ss << "\\newenvironment{" << name << "}";
962 ss << '{' << p.verbatim_item() << '}';
963 ss << '{' << p.verbatim_item() << '}';
964 if (!in_lyx_preamble)
965 h_preamble << ss.str();
968 else if (t.cs() == "def") {
969 string name = p.get_token().cs();
970 while (p.next_token().cat() != catBegin)
971 name += p.get_token().cs();
972 if (!in_lyx_preamble)
973 h_preamble << "\\def\\" << name << '{'
974 << p.verbatim_item() << "}";
977 else if (t.cs() == "newcolumntype") {
978 string const name = p.getArg('{', '}');
981 string opts = p.getOpt();
983 istringstream is(string(opts, 1));
986 special_columns[name[0]] = nargs;
987 h_preamble << "\\newcolumntype{" << name << "}";
989 h_preamble << "[" << nargs << "]";
990 h_preamble << "{" << p.verbatim_item() << "}";
993 else if (t.cs() == "setcounter") {
994 string const name = p.getArg('{', '}');
995 string const content = p.getArg('{', '}');
996 if (name == "secnumdepth")
997 h_secnumdepth = content;
998 else if (name == "tocdepth")
999 h_tocdepth = content;
1001 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
1004 else if (t.cs() == "setlength") {
1005 string const name = p.verbatim_item();
1006 string const content = p.verbatim_item();
1007 // the paragraphs are only not indented when \parindent is set to zero
1008 if (name == "\\parindent" && content != "") {
1009 if (content[0] == '0')
1010 h_paragraph_separation = "skip";
1011 else if (LYX_FORMAT >= 365)
1012 h_paragraph_indentation = translate_len(content);
1014 h_preamble << "\\setlength{" << name
1015 << "}{" << content << "}";
1016 } else if (name == "\\parskip") {
1017 if (content == "\\smallskipamount")
1018 h_defskip = "smallskip";
1019 else if (content == "\\medskipamount")
1020 h_defskip = "medskip";
1021 else if (content == "\\bigskipamount")
1022 h_defskip = "bigskip";
1024 h_defskip = content;
1026 h_preamble << "\\setlength{" << name << "}{" << content << "}";
1029 else if (t.cs() == "onehalfspacing")
1030 h_spacing = "onehalf";
1032 else if (t.cs() == "doublespacing")
1033 h_spacing = "double";
1035 else if (t.cs() == "setstretch")
1036 h_spacing = "other " + p.verbatim_item();
1038 else if (t.cs() == "begin") {
1039 string const name = p.getArg('{', '}');
1040 if (name == "document")
1042 h_preamble << "\\begin{" << name << "}";
1045 else if (t.cs() == "geometry") {
1046 h_use_geometry = "true";
1047 vector<string> opts = split_options(p.getArg('{', '}'));
1048 vector<string>::iterator it;
1049 // paper orientation
1050 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
1051 h_paperorientation = "landscape";
1055 handle_opt(opts, known_paper_sizes, h_papersize);
1056 delete_opt(opts, known_paper_sizes);
1058 char const * const * margin = known_paper_margins;
1060 for (; *margin; ++margin) {
1062 // search for the "=" in e.g. "lmargin=2cm" to get the value
1063 for(size_t i = 0; i != opts.size(); i++) {
1064 if (opts.at(i).find(*margin) != string::npos) {
1065 string::size_type pos = opts.at(i).find("=");
1066 string value = opts.at(i).substr(pos + 1);
1067 string name = known_coded_paper_margins[k];
1068 h_margins += "\\" + name + " " + value + "\n";
1074 else if (t.cs() == "definecolor") {
1075 string const color = p.getArg('{', '}');
1076 string const space = p.getArg('{', '}');
1077 string const value = p.getArg('{', '}');
1078 if (LYX_FORMAT >= 382 &&
1079 color == "note_fontcolor" && space == "rgb") {
1080 RGBColor c(RGBColorFromLaTeX(value));
1081 h_notefontcolor = X11hexname(c);
1083 h_preamble << "\\definecolor{" << color
1084 << "}{" << space << "}{" << value
1089 else if (t.cs() == "jurabibsetup") {
1090 // FIXME p.getArg('{', '}') is most probably wrong (it
1091 // does not handle nested braces).
1092 // Use p.verbatim_item() instead.
1093 vector<string> jurabibsetup =
1094 split_options(p.getArg('{', '}'));
1095 // add jurabibsetup to the jurabib package options
1096 add_package("jurabib", jurabibsetup);
1097 if (!jurabibsetup.empty()) {
1098 h_preamble << "\\jurabibsetup{"
1099 << join(jurabibsetup, ",") << '}';
1103 else if (t.cs() == "hypersetup") {
1104 vector<string> hypersetup =
1105 split_options(p.verbatim_item());
1106 // add hypersetup to the hyperref package options
1107 handle_hyperref(hypersetup);
1108 if (!hypersetup.empty()) {
1109 h_preamble << "\\hypersetup{"
1110 << join(hypersetup, ",") << '}';
1114 else if (is_known(t.cs(), known_if_3arg_commands)) {
1115 // prevent misparsing of \usepackage if it is used
1116 // as an argument (see e.g. our own output of
1117 // \@ifundefined above)
1118 string const arg1 = p.verbatim_item();
1119 string const arg2 = p.verbatim_item();
1120 string const arg3 = p.verbatim_item();
1121 if (!in_lyx_preamble) {
1122 h_preamble << t.asInput()
1123 << '{' << arg1 << '}'
1124 << '{' << arg2 << '}'
1125 << '{' << arg3 << '}';
1129 else if (is_known(t.cs(), known_if_commands)) {
1130 // must not parse anything in conditional code, since
1131 // LyX would output the parsed contents unconditionally
1132 if (!in_lyx_preamble)
1133 h_preamble << t.asInput();
1134 handle_if(p, in_lyx_preamble);
1137 else if (!t.cs().empty() && !in_lyx_preamble)
1138 h_preamble << '\\' << t.cs();
1141 // remove the whitespace
1144 // Force textclass if the user wanted it
1145 if (!forceclass.empty())
1146 h_textclass = forceclass;
1147 if (noweb_mode && !prefixIs(h_textclass, "literate-"))
1148 h_textclass.insert(0, "literate-");
1149 FileName layoutfilename = libFileSearch("layouts", h_textclass, "layout");
1150 if (layoutfilename.empty()) {
1151 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
1154 tc.read(layoutfilename);
1155 if (h_papersides.empty()) {
1158 h_papersides = ss.str();
1160 end_preamble(os, tc);
1164 /// translates a babel language name to a LyX language name
1165 string babel2lyx(string const & language)
1167 char const * const * where = is_known(language, known_languages);
1169 return known_coded_languages[where - known_languages];