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;
47 const char * const modules_placeholder = "\001modules\001";
49 // needed to handle encodings with babel
50 bool one_language = true;
51 string h_inputencoding = "auto";
52 string h_paragraph_separation = "indent";
56 //add this to known_languages when updating to lyxformat 266:
57 // "armenian" (needs special handling since not supported by standard babel)
58 //add these to known_languages when updating to lyxformat 268:
59 //"chinese-simplified", "chinese-traditional", "japanese", "korean"
60 // Both changes require first that support for non-babel languages (CJK,
62 // add turkmen for lyxformat 383
64 * known babel language names (including synonyms)
65 * not in standard babel: arabic, arabtex, armenian, belarusian, serbian-latin, thai
66 * not yet supported by LyX: kurmanji
67 * please keep this in sync with known_coded_languages line by line!
69 const char * const known_languages[] = {"acadian", "afrikaans", "albanian",
70 "american", "arabic", "arabtex", "austrian", "bahasa", "bahasai", "bahasam",
71 "basque", "belarusian", "brazil", "brazilian", "breton", "british", "bulgarian",
72 "canadian", "canadien", "catalan", "croatian", "czech", "danish", "dutch",
73 "english", "esperanto", "estonian", "farsi", "finnish", "francais", "french",
74 "frenchb", "frenchle", "frenchpro", "galician", "german", "germanb", "greek",
75 "hebrew", "hungarian", "icelandic", "indon", "indonesian", "interlingua",
76 "irish", "italian", "kazakh", "latin", "latvian", "lithuanian", "lowersorbian",
77 "lsorbian", "magyar", "malay", "meyalu", "mongolian", "naustrian", "newzealand",
78 "ngerman", "ngermanb", "norsk", "nynorsk", "polutonikogreek", "polish",
79 "portuges", "portuguese", "romanian", "russian", "russianb", "samin",
80 "scottish", "serbian", "serbian-latin", "slovak", "slovene", "spanish",
81 "swedish", "thai", "turkish", "turkmen", "ukraineb", "ukrainian",
82 "uppersorbian", "UKenglish", "USenglish", "usorbian", "vietnam", "welsh",
86 * the same as known_languages with .lyx names
87 * please keep this in sync with known_languages line by line!
89 const char * const known_coded_languages[] = {"french", "afrikaans", "albanian",
90 "american", "arabic_arabi", "arabic_arabtex", "austrian", "bahasa", "bahasa", "bahasam",
91 "basque", "belarusian", "brazilian", "brazilian", "breton", "british", "bulgarian",
92 "canadian", "canadien", "catalan", "croatian", "czech", "danish", "dutch",
93 "english", "esperanto", "estonian", "farsi", "finnish", "french", "french",
94 "french", "french", "french", "galician", "german", "german", "greek",
95 "hebrew", "magyar", "icelandic", "bahasa", "bahasa", "interlingua",
96 "irish", "italian", "kazakh", "latin", "latvian", "lithuanian", "lowersorbian",
97 "lowersorbian", "magyar", "bahasam", "bahasam", "mongolian", "naustrian", "english",
98 "ngerman", "ngerman", "norsk", "nynorsk", "polutonikogreek", "polish",
99 "portuguese", "portuguese", "romanian", "russian", "russian", "samin",
100 "scottish", "serbian", "serbian-latin", "slovak", "slovene", "spanish",
101 "swedish", "thai", "turkish", "turkmen", "ukrainian", "ukrainian",
102 "uppersorbian", "uppersorbian", "english", "english", "vietnamese", "welsh",
105 /// languages with english quotes (.lyx names)
106 const char * const known_english_quotes_languages[] = {"american", "bahasa",
107 "bahasam", "brazilian", "canadian", "chinese-simplified", "english",
108 "esperanto", "hebrew", "irish", "korean", "portuguese", "scottish", "thai", 0};
110 /// languages with french quotes (.lyx names)
111 const char * const known_french_quotes_languages[] = {"albanian",
112 "arabic_arabi", "arabic_arabtex", "basque", "canadien", "catalan", "french",
113 "galician", "greek", "italian", "norsk", "nynorsk", "polutonikogreek",
114 "russian", "spanish", "spanish-mexico", "turkish", "turkmen", "ukrainian",
117 /// languages with german quotes (.lyx names)
118 const char * const known_german_quotes_languages[] = {"austrian", "bulgarian",
119 "czech", "german", "icelandic", "lithuanian", "lowersorbian", "naustrian",
120 "ngerman", "serbian", "serbian-latin", "slovak", "slovene", "uppersorbian", 0};
122 /// languages with polish quotes (.lyx names)
123 const char * const known_polish_quotes_languages[] = {"afrikaans", "croatian",
124 "dutch", "estonian", "magyar", "polish", "romanian", 0};
126 /// languages with swedish quotes (.lyx names)
127 const char * const known_swedish_quotes_languages[] = {"finnish",
130 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
132 const char * const known_roman_fonts[] = { "ae", "bookman", "charter",
133 "cmr", "fourier", "lmodern", "mathpazo", "mathptmx", "newcent", 0};
135 const char * const known_sans_fonts[] = { "avant", "berasans", "cmbr", "cmss",
136 "helvet", "lmss", 0};
138 const char * const known_typewriter_fonts[] = { "beramono", "cmtl", "cmtt",
139 "courier", "lmtt", "luximono", "fourier", "lmodern", "mathpazo", "mathptmx",
142 const char * const known_paper_sizes[] = { "a3paper", "b3paper", "a4paper",
143 "b4paper", "a5paper", "b5paper", "executivepaper", "legalpaper",
146 const char * const known_class_paper_sizes[] = { "a4paper", "a5paper",
147 "executivepaper", "legalpaper", "letterpaper", 0};
149 const char * const known_paper_margins[] = { "lmargin", "tmargin", "rmargin",
150 "bmargin", "headheight", "headsep", "footskip", "columnsep", 0};
152 const char * const known_coded_paper_margins[] = { "leftmargin", "topmargin",
153 "rightmargin", "bottommargin", "headheight", "headsep", "footskip",
156 /// commands that can start an \if...\else...\endif sequence
157 const char * const known_if_commands[] = {"if", "ifarydshln", "ifbraket",
158 "ifcancel", "ifcolortbl", "ifeurosym", "ifmarginnote", "ifmmode", "ifpdf",
159 "ifsidecap", "ifupgreek", 0};
161 /// conditional commands with three arguments like \@ifundefined{}{}{}
162 const char * const known_if_3arg_commands[] = {"@ifundefined", "IfFileExists",
166 ostringstream h_preamble;
167 string h_textclass = "article";
168 string h_use_default_options = "false";
170 string h_language = "english";
171 string h_font_roman = "default";
172 string h_font_sans = "default";
173 string h_font_typewriter = "default";
174 string h_font_default_family = "default";
175 string h_font_sc = "false";
176 string h_font_osf = "false";
177 string h_font_sf_scale = "100";
178 string h_font_tt_scale = "100";
179 string h_graphics = "default";
180 string h_float_placement;
181 string h_paperfontsize = "default";
182 string h_spacing = "single";
183 string h_use_hyperref = "0";
186 string h_pdf_subject;
187 string h_pdf_keywords;
188 string h_pdf_bookmarks = "1";
189 string h_pdf_bookmarksnumbered = "0";
190 string h_pdf_bookmarksopen = "0";
191 string h_pdf_bookmarksopenlevel = "1";
192 string h_pdf_breaklinks = "0";
193 string h_pdf_pdfborder = "0";
194 string h_pdf_colorlinks = "0";
195 string h_pdf_backref = "section";
196 string h_pdf_pdfusetitle = "1";
197 string h_pdf_pagemode;
198 string h_pdf_quoted_options;
199 string h_papersize = "default";
200 string h_use_geometry = "false";
201 string h_use_amsmath = "1";
202 string h_use_esint = "1";
203 string h_use_mhchem = "0";
204 string h_use_mathdots = "0";
205 string h_cite_engine = "basic";
206 string h_use_bibtopic = "false";
207 string h_paperorientation = "portrait";
208 string h_notefontcolor;
209 string h_secnumdepth = "3";
210 string h_tocdepth = "3";
211 string h_defskip = "medskip";
212 string h_paragraph_indentation = "default";
213 string h_quotes_language = "english";
214 string h_papercolumns = "1";
216 string h_paperpagestyle = "default";
217 string h_listings_params;
218 string h_tracking_changes = "false";
219 string h_output_changes = "false";
220 string h_html_math_output = "0";
221 string h_html_be_strict = "false";
225 // returns true if at least one of the options in what has been found
226 bool handle_opt(vector<string> & opts, char const * const * what, string & target)
232 // the last language option is the document language (for babel and LyX)
233 // the last size option is the document font size
234 vector<string>::iterator it;
235 vector<string>::iterator position = opts.begin();
236 for (; *what; ++what) {
237 it = find(opts.begin(), opts.end(), *what);
238 if (it != opts.end()) {
239 if (it >= position) {
250 void delete_opt(vector<string> & opts, char const * const * what)
255 // remove found options from the list
256 // do this after handle_opt to avoid potential memory leaks
257 vector<string>::iterator it;
258 for (; *what; ++what) {
259 it = find(opts.begin(), opts.end(), *what);
260 if (it != opts.end())
267 * Split a package options string (keyval format) into a vector.
269 * authorformat=smallcaps,
271 * titleformat=colonsep,
272 * bibformat={tabular,ibidem,numbered}
274 vector<string> split_options(string const & input)
276 vector<string> options;
280 Token const & t = p.get_token();
281 if (t.asInput() == ",") {
282 options.push_back(trimSpaceAndEol(option));
284 } else if (t.asInput() == "=") {
287 if (p.next_token().asInput() == "{")
288 option += '{' + p.getArg('{', '}') + '}';
289 } else if (t.cat() != catSpace)
290 option += t.asInput();
294 options.push_back(trimSpaceAndEol(option));
301 * Retrieve a keyval option "name={value with=sign}" named \p name from
302 * \p options and return the value.
303 * The found option is also removed from \p options.
305 string process_keyval_opt(vector<string> & options, string name)
307 for (size_t i = 0; i < options.size(); ++i) {
308 vector<string> option;
309 split(options[i], option, '=');
310 if (option.size() < 2)
312 if (option[0] == name) {
313 options.erase(options.begin() + i);
314 option.erase(option.begin());
315 return join(option, "=");
323 * Add package \p name with options \p options to used_packages.
324 * Remove options from \p options that we don't want to output.
326 void add_package(string const & name, vector<string> & options)
328 // every package inherits the global options
329 if (used_packages.find(name) == used_packages.end())
330 used_packages[name] = split_options(h_options);
332 vector<string> & v = used_packages[name];
333 v.insert(v.end(), options.begin(), options.end());
334 if (name == "jurabib") {
335 // Don't output the order argument (see the cite command
336 // handling code in text.cpp).
337 vector<string>::iterator end =
338 remove(options.begin(), options.end(), "natbiborder");
339 end = remove(options.begin(), end, "jurabiborder");
340 options.erase(end, options.end());
345 // Given is a string like "scaled=0.9", return 0.9 * 100
346 string const scale_as_percentage(string const & scale)
348 string::size_type pos = scale.find('=');
349 if (pos != string::npos) {
350 string value = scale.substr(pos + 1);
352 return convert<string>(100 * convert<double>(value));
354 // If the input string didn't match our expectations.
355 // return the default value "100"
360 string remove_braces(string const & value)
364 if (value[0] == '{' && value[value.length()-1] == '}')
365 return value.substr(1, value.length()-2);
370 void handle_hyperref(vector<string> & options)
372 // FIXME swallow inputencoding changes that might surround the
373 // hyperref setup if it was written by LyX
374 h_use_hyperref = "1";
375 // swallow "unicode=true", since LyX does always write that
376 vector<string>::iterator it =
377 find(options.begin(), options.end(), "unicode=true");
378 if (it != options.end())
380 it = find(options.begin(), options.end(), "pdfusetitle");
381 if (it != options.end()) {
382 h_pdf_pdfusetitle = "1";
385 string bookmarks = process_keyval_opt(options, "bookmarks");
386 if (bookmarks == "true")
387 h_pdf_bookmarks = "1";
388 else if (bookmarks == "false")
389 h_pdf_bookmarks = "0";
390 if (h_pdf_bookmarks == "1") {
391 string bookmarksnumbered =
392 process_keyval_opt(options, "bookmarksnumbered");
393 if (bookmarksnumbered == "true")
394 h_pdf_bookmarksnumbered = "1";
395 else if (bookmarksnumbered == "false")
396 h_pdf_bookmarksnumbered = "0";
397 string bookmarksopen =
398 process_keyval_opt(options, "bookmarksopen");
399 if (bookmarksopen == "true")
400 h_pdf_bookmarksopen = "1";
401 else if (bookmarksopen == "false")
402 h_pdf_bookmarksopen = "0";
403 if (h_pdf_bookmarksopen == "1") {
404 string bookmarksopenlevel =
405 process_keyval_opt(options, "bookmarksopenlevel");
406 if (!bookmarksopenlevel.empty())
407 h_pdf_bookmarksopenlevel = bookmarksopenlevel;
410 string breaklinks = process_keyval_opt(options, "breaklinks");
411 if (breaklinks == "true")
412 h_pdf_breaklinks = "1";
413 else if (breaklinks == "false")
414 h_pdf_breaklinks = "0";
415 string pdfborder = process_keyval_opt(options, "pdfborder");
416 if (pdfborder == "{0 0 0}")
417 h_pdf_pdfborder = "1";
418 else if (pdfborder == "{0 0 1}")
419 h_pdf_pdfborder = "0";
420 string backref = process_keyval_opt(options, "backref");
421 if (!backref.empty())
422 h_pdf_backref = backref;
423 string colorlinks = process_keyval_opt(options, "colorlinks");
424 if (colorlinks == "true")
425 h_pdf_colorlinks = "1";
426 else if (colorlinks == "false")
427 h_pdf_colorlinks = "0";
428 string pdfpagemode = process_keyval_opt(options, "pdfpagemode");
429 if (!pdfpagemode.empty())
430 h_pdf_pagemode = pdfpagemode;
431 string pdftitle = process_keyval_opt(options, "pdftitle");
432 if (!pdftitle.empty()) {
433 h_pdf_title = remove_braces(pdftitle);
435 string pdfauthor = process_keyval_opt(options, "pdfauthor");
436 if (!pdfauthor.empty()) {
437 h_pdf_author = remove_braces(pdfauthor);
439 string pdfsubject = process_keyval_opt(options, "pdfsubject");
440 if (!pdfsubject.empty())
441 h_pdf_subject = remove_braces(pdfsubject);
442 string pdfkeywords = process_keyval_opt(options, "pdfkeywords");
443 if (!pdfkeywords.empty())
444 h_pdf_keywords = remove_braces(pdfkeywords);
445 if (!options.empty()) {
446 if (!h_pdf_quoted_options.empty())
447 h_pdf_quoted_options += ',';
448 h_pdf_quoted_options += join(options, ",");
454 void handle_package(Parser &p, string const & name, string const & opts,
455 bool in_lyx_preamble)
457 vector<string> options = split_options(opts);
458 add_package(name, options);
462 if (is_known(name, known_roman_fonts)) {
467 if (name == "fourier") {
468 h_font_roman = "utopia";
469 // when font uses real small capitals
470 if (opts == "expert")
474 if (name == "mathpazo")
475 h_font_roman = "palatino";
477 if (name == "mathptmx")
478 h_font_roman = "times";
481 if (is_known(name, known_sans_fonts)) {
485 h_font_sf_scale = scale_as_percentage(scale);
490 if (is_known(name, known_typewriter_fonts)) {
491 h_font_typewriter = name;
494 h_font_tt_scale = scale_as_percentage(scale);
498 // font uses old-style figure
502 else if (name == "amsmath" || name == "amssymb")
505 else if (name == "esint")
508 else if (name == "mhchem")
511 else if (name == "mathdots")
512 h_use_mathdots = "2";
514 else if (name == "babel" && !opts.empty()) {
515 // check if more than one option was used - used later for inputenc
516 // in case inputenc is parsed before babel, set the encoding to auto
517 if (options.begin() != options.end() - 1) {
518 one_language = false;
519 h_inputencoding = "auto";
521 // babel takes the last language of the option of its \usepackage
522 // call as document language. If there is no such language option, the
523 // last language in the documentclass options is used.
524 handle_opt(options, known_languages, h_language);
525 delete_opt(options, known_languages);
528 else if (name == "fontenc")
531 else if (name == "inputenc" || name == "luainputenc") {
532 // h_inputencoding is only set when there is not more than one
533 // inputenc option because otherwise h_inputencoding must be
534 // set to "auto" (the default encoding of the document language)
535 // Therefore check for the "," character.
536 // It is also only set when there is not more then one babel
537 // language option but this is handled in the routine for babel.
538 if (opts.find(",") == string::npos && one_language == true)
539 h_inputencoding = opts;
540 if (!options.empty())
541 p.setEncoding(options.back());
545 else if (name == "makeidx")
548 else if (name == "prettyref")
551 else if (name == "varioref")
554 else if (name == "verbatim")
557 else if (name == "nomencl")
560 else if (name == "textcomp")
563 else if (name == "url")
566 else if (LYX_FORMAT >= 408 && name == "subscript")
569 else if (name == "color") {
570 // with the following command this package is only loaded when needed for
571 // undefined colors, since we only support the predefined colors
572 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
575 else if (name == "graphicx")
578 else if (name == "setspace")
581 else if (name == "geometry")
582 ; // Ignore this, the geometry settings are made by the \geometry
583 // command. This command is handled below.
585 else if (is_known(name, known_languages))
588 else if (name == "natbib") {
589 h_cite_engine = "natbib_authoryear";
590 vector<string>::iterator it =
591 find(options.begin(), options.end(), "authoryear");
592 if (it != options.end())
595 it = find(options.begin(), options.end(), "numbers");
596 if (it != options.end()) {
597 h_cite_engine = "natbib_numerical";
603 else if (name == "jurabib")
604 h_cite_engine = "jurabib";
606 else if (name == "hyperref")
607 handle_hyperref(options);
609 else if (!in_lyx_preamble) {
611 h_preamble << "\\usepackage{" << name << "}";
613 h_preamble << "\\usepackage[" << opts << "]{"
619 // We need to do something with the options...
620 if (!options.empty())
621 cerr << "Ignoring options '" << join(options, ",")
622 << "' of package " << name << '.' << endl;
624 // remove the whitespace
629 void handle_if(Parser & p, bool in_lyx_preamble)
632 Token t = p.get_token();
633 if (t.cat() == catEscape &&
634 is_known(t.cs(), known_if_commands))
635 handle_if(p, in_lyx_preamble);
637 if (!in_lyx_preamble)
638 h_preamble << t.asInput();
639 if (t.cat() == catEscape && t.cs() == "fi")
646 void end_preamble(ostream & os, TextClass const & /*textclass*/)
648 // translate from babel to LyX names
649 h_language = babel2lyx(h_language);
651 // set the quote language
652 // LyX only knows the following quotes languages:
653 // english, swedish, german, polish, french and danish
654 // (quotes for "japanese" and "chinese-traditional" are missing because
655 // they wouldn't be useful: http://www.lyx.org/trac/ticket/6383)
656 // conversion list taken from
657 // http://en.wikipedia.org/wiki/Quotation_mark,_non-English_usage
658 // (quotes for kazakh and interlingua are unknown)
660 if (h_language == "danish")
661 h_quotes_language = "danish";
663 else if (is_known(h_language, known_french_quotes_languages))
664 h_quotes_language = "french";
666 else if (is_known(h_language, known_german_quotes_languages))
667 h_quotes_language = "german";
669 else if (is_known(h_language, known_polish_quotes_languages))
670 h_quotes_language = "polish";
672 else if (is_known(h_language, known_swedish_quotes_languages))
673 h_quotes_language = "swedish";
675 else if (is_known(h_language, known_english_quotes_languages))
676 h_quotes_language = "english";
678 // output the LyX file settings
679 os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
680 << "\\lyxformat " << LYX_FORMAT << '\n'
681 << "\\begin_document\n"
682 << "\\begin_header\n"
683 << "\\textclass " << h_textclass << "\n";
684 if (!h_preamble.str().empty())
685 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
686 if (!h_options.empty())
687 os << "\\options " << h_options << "\n";
688 os << "\\use_default_options " << h_use_default_options << "\n"
689 << modules_placeholder
690 << "\\language " << h_language << "\n"
691 << "\\inputencoding " << h_inputencoding << "\n"
692 << "\\font_roman " << h_font_roman << "\n"
693 << "\\font_sans " << h_font_sans << "\n"
694 << "\\font_typewriter " << h_font_typewriter << "\n"
695 << "\\font_default_family " << h_font_default_family << "\n"
696 << "\\font_sc " << h_font_sc << "\n"
697 << "\\font_osf " << h_font_osf << "\n"
698 << "\\font_sf_scale " << h_font_sf_scale << "\n"
699 << "\\font_tt_scale " << h_font_tt_scale << "\n"
700 << "\\graphics " << h_graphics << "\n";
701 if (!h_float_placement.empty())
702 os << "\\float_placement " << h_float_placement << "\n";
703 os << "\\paperfontsize " << h_paperfontsize << "\n"
704 << "\\spacing " << h_spacing << "\n"
705 << "\\use_hyperref " << h_use_hyperref << '\n';
706 if (h_use_hyperref == "1") {
707 if (!h_pdf_title.empty())
708 os << "\\pdf_title \"" << h_pdf_title << "\"\n";
709 if (!h_pdf_author.empty())
710 os << "\\pdf_author \"" << h_pdf_author << "\"\n";
711 if (!h_pdf_subject.empty())
712 os << "\\pdf_subject \"" << h_pdf_subject << "\"\n";
713 if (!h_pdf_keywords.empty())
714 os << "\\pdf_keywords \"" << h_pdf_keywords << "\"\n";
715 os << "\\pdf_bookmarks " << h_pdf_bookmarks << "\n"
716 "\\pdf_bookmarksnumbered " << h_pdf_bookmarksnumbered << "\n"
717 "\\pdf_bookmarksopen " << h_pdf_bookmarksopen << "\n"
718 "\\pdf_bookmarksopenlevel " << h_pdf_bookmarksopenlevel << "\n"
719 "\\pdf_breaklinks " << h_pdf_breaklinks << "\n"
720 "\\pdf_pdfborder " << h_pdf_pdfborder << "\n"
721 "\\pdf_colorlinks " << h_pdf_colorlinks << "\n"
722 "\\pdf_backref " << h_pdf_backref << "\n"
723 "\\pdf_pdfusetitle " << h_pdf_pdfusetitle << '\n';
724 if (!h_pdf_pagemode.empty())
725 os << "\\pdf_pagemode " << h_pdf_pagemode << '\n';
726 if (!h_pdf_quoted_options.empty())
727 os << "\\pdf_quoted_options \"" << h_pdf_quoted_options << "\"\n";
729 os << "\\papersize " << h_papersize << "\n"
730 << "\\use_geometry " << h_use_geometry << "\n"
731 << "\\use_amsmath " << h_use_amsmath << "\n"
732 << "\\use_esint " << h_use_esint << "\n"
733 << "\\use_mhchem " << h_use_mhchem << "\n"
734 << "\\use_mathdots " << h_use_mathdots << "\n"
735 << "\\cite_engine " << h_cite_engine << "\n"
736 << "\\use_bibtopic " << h_use_bibtopic << "\n"
737 << "\\paperorientation " << h_paperorientation << '\n';
738 if (!h_notefontcolor.empty())
739 os << "\\notefontcolor " << h_notefontcolor << '\n';
741 << "\\secnumdepth " << h_secnumdepth << "\n"
742 << "\\tocdepth " << h_tocdepth << "\n"
743 << "\\paragraph_separation " << h_paragraph_separation << "\n";
744 if (h_paragraph_separation == "skip")
745 os << "\\defskip " << h_defskip << "\n";
747 os << "\\paragraph_indentation " << h_paragraph_indentation << "\n";
748 os << "\\quotes_language " << h_quotes_language << "\n"
749 << "\\papercolumns " << h_papercolumns << "\n"
750 << "\\papersides " << h_papersides << "\n"
751 << "\\paperpagestyle " << h_paperpagestyle << "\n";
752 if (!h_listings_params.empty())
753 os << "\\listings_params " << h_listings_params << "\n";
754 os << "\\tracking_changes " << h_tracking_changes << "\n"
755 << "\\output_changes " << h_output_changes << "\n"
756 << "\\html_math_output " << h_html_math_output << "\n"
757 << "\\html_be_strict " << h_html_be_strict << "\n"
758 << "\\end_header\n\n"
760 // clear preamble for subdocuments
764 } // anonymous namespace
767 void parse_preamble(Parser & p, ostream & os,
768 string const & forceclass, TeX2LyXDocClass & tc)
770 // initialize fixed types
771 special_columns['D'] = 3;
772 bool is_full_document = false;
773 bool is_lyx_file = false;
774 bool in_lyx_preamble = false;
776 // determine whether this is a full document or a fragment for inclusion
778 Token const & t = p.get_token();
780 if (t.cat() == catEscape && t.cs() == "documentclass") {
781 is_full_document = true;
787 while (is_full_document && p.good()) {
788 Token const & t = p.get_token();
791 cerr << "t: " << t << "\n";
797 if (!in_lyx_preamble &&
798 (t.cat() == catLetter ||
799 t.cat() == catSuper ||
801 t.cat() == catOther ||
802 t.cat() == catMath ||
803 t.cat() == catActive ||
804 t.cat() == catBegin ||
806 t.cat() == catAlign ||
807 t.cat() == catParameter))
808 h_preamble << t.cs();
810 else if (!in_lyx_preamble &&
811 (t.cat() == catSpace || t.cat() == catNewline))
812 h_preamble << t.asInput();
814 else if (t.cat() == catComment) {
815 static regex const islyxfile("%% LyX .* created this file");
816 static regex const usercommands("User specified LaTeX commands");
818 string const comment = t.asInput();
820 // magically switch encoding default if it looks like XeLaTeX
821 static string const magicXeLaTeX =
822 "% This document must be compiled with XeLaTeX ";
823 if (comment.size() > magicXeLaTeX.size()
824 && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
825 && h_inputencoding == "auto") {
826 cerr << "XeLaTeX comment found, switching to UTF8\n";
827 h_inputencoding = "utf8";
830 if (regex_search(comment, sub, islyxfile)) {
832 in_lyx_preamble = true;
833 } else if (is_lyx_file
834 && regex_search(comment, sub, usercommands))
835 in_lyx_preamble = false;
836 else if (!in_lyx_preamble)
837 h_preamble << t.asInput();
840 else if (t.cs() == "pagestyle")
841 h_paperpagestyle = p.verbatim_item();
843 else if (t.cs() == "makeatletter") {
844 // LyX takes care of this
845 p.setCatCode('@', catLetter);
848 else if (t.cs() == "makeatother") {
849 // LyX takes care of this
850 p.setCatCode('@', catOther);
853 else if (t.cs() == "newcommand" || t.cs() == "newcommandx"
854 || t.cs() == "renewcommand" || t.cs() == "renewcommandx"
855 || t.cs() == "providecommand" || t.cs() == "providecommandx"
856 || t.cs() == "DeclareRobustCommand"
857 || t.cs() == "DeclareRobustCommandx"
858 || t.cs() == "ProvideTextCommandDefault"
859 || t.cs() == "DeclareMathAccent") {
861 if (p.next_token().character() == '*') {
865 string const name = p.verbatim_item();
866 string const opt1 = p.getFullOpt();
867 string const opt2 = p.getFullOpt();
868 string const body = p.verbatim_item();
870 if (name == "\\rmdefault")
871 if (is_known(body, known_roman_fonts))
873 if (name == "\\sfdefault")
874 if (is_known(body, known_sans_fonts))
876 if (name == "\\ttdefault")
877 if (is_known(body, known_typewriter_fonts))
878 h_font_typewriter = body;
879 if (name == "\\familydefault") {
880 string family = body;
881 // remove leading "\"
882 h_font_default_family = family.erase(0,1);
885 // Add the command to the known commands
886 add_known_command(name, opt1, !opt2.empty(), from_utf8(body));
888 // only non-lyxspecific stuff
889 if (!in_lyx_preamble) {
891 ss << '\\' << t.cs();
894 ss << '{' << name << '}' << opt1 << opt2
895 << '{' << body << "}";
896 h_preamble << ss.str();
898 ostream & out = in_preamble ? h_preamble : os;
899 out << "\\" << t.cs() << "{" << name << "}"
900 << opts << "{" << body << "}";
905 else if (t.cs() == "documentclass") {
906 vector<string>::iterator it;
907 vector<string> opts = split_options(p.getArg('[', ']'));
908 handle_opt(opts, known_fontsizes, h_paperfontsize);
909 delete_opt(opts, known_fontsizes);
910 // delete "pt" at the end
911 string::size_type i = h_paperfontsize.find("pt");
912 if (i != string::npos)
913 h_paperfontsize.erase(i);
914 // The documentclass options are always parsed before the options
915 // of the babel call so that a language cannot overwrite the babel
917 handle_opt(opts, known_languages, h_language);
918 delete_opt(opts, known_languages);
921 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
922 h_paperorientation = "landscape";
926 if ((it = find(opts.begin(), opts.end(), "oneside"))
931 if ((it = find(opts.begin(), opts.end(), "twoside"))
937 if ((it = find(opts.begin(), opts.end(), "onecolumn"))
939 h_papercolumns = "1";
942 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
944 h_papercolumns = "2";
948 // some size options are know to any document classes, other sizes
949 // are handled by the \geometry command of the geometry package
950 handle_opt(opts, known_class_paper_sizes, h_papersize);
951 delete_opt(opts, known_class_paper_sizes);
952 // the remaining options
953 h_options = join(opts, ",");
954 // FIXME This does not work for classes that have a
955 // different name in LyX than in LaTeX
956 h_textclass = p.getArg('{', '}');
959 else if (t.cs() == "usepackage") {
960 string const options = p.getArg('[', ']');
961 string const name = p.getArg('{', '}');
962 vector<string> vecnames;
963 split(name, vecnames, ',');
964 vector<string>::const_iterator it = vecnames.begin();
965 vector<string>::const_iterator end = vecnames.end();
966 for (; it != end; ++it)
967 handle_package(p, trimSpaceAndEol(*it), options,
971 else if (t.cs() == "inputencoding") {
972 string const encoding = p.getArg('{','}');
973 h_inputencoding = encoding;
974 p.setEncoding(encoding);
977 else if (t.cs() == "newenvironment") {
978 string const name = p.getArg('{', '}');
979 string const opt1 = p.getFullOpt();
980 string const opt2 = p.getFullOpt();
981 string const beg = p.verbatim_item();
982 string const end = p.verbatim_item();
983 if (!in_lyx_preamble) {
984 h_preamble << "\\newenvironment{" << name
985 << '}' << opt1 << opt2 << '{'
986 << beg << "}{" << end << '}';
988 add_known_environment(name, opt1, !opt2.empty(),
989 from_utf8(beg), from_utf8(end));
993 else if (t.cs() == "def") {
994 string name = p.get_token().cs();
995 while (p.next_token().cat() != catBegin)
996 name += p.get_token().cs();
997 if (!in_lyx_preamble)
998 h_preamble << "\\def\\" << name << '{'
999 << p.verbatim_item() << "}";
1002 else if (t.cs() == "newcolumntype") {
1003 string const name = p.getArg('{', '}');
1004 trimSpaceAndEol(name);
1006 string opts = p.getOpt();
1007 if (!opts.empty()) {
1008 istringstream is(string(opts, 1));
1011 special_columns[name[0]] = nargs;
1012 h_preamble << "\\newcolumntype{" << name << "}";
1014 h_preamble << "[" << nargs << "]";
1015 h_preamble << "{" << p.verbatim_item() << "}";
1018 else if (t.cs() == "setcounter") {
1019 string const name = p.getArg('{', '}');
1020 string const content = p.getArg('{', '}');
1021 if (name == "secnumdepth")
1022 h_secnumdepth = content;
1023 else if (name == "tocdepth")
1024 h_tocdepth = content;
1026 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
1029 else if (t.cs() == "setlength") {
1030 string const name = p.verbatim_item();
1031 string const content = p.verbatim_item();
1032 // the paragraphs are only not indented when \parindent is set to zero
1033 if (name == "\\parindent" && content != "") {
1034 if (content[0] == '0')
1035 h_paragraph_separation = "skip";
1037 h_paragraph_indentation = translate_len(content);
1038 } else if (name == "\\parskip") {
1039 if (content == "\\smallskipamount")
1040 h_defskip = "smallskip";
1041 else if (content == "\\medskipamount")
1042 h_defskip = "medskip";
1043 else if (content == "\\bigskipamount")
1044 h_defskip = "bigskip";
1046 h_defskip = content;
1048 h_preamble << "\\setlength{" << name << "}{" << content << "}";
1051 else if (t.cs() == "onehalfspacing")
1052 h_spacing = "onehalf";
1054 else if (t.cs() == "doublespacing")
1055 h_spacing = "double";
1057 else if (t.cs() == "setstretch")
1058 h_spacing = "other " + p.verbatim_item();
1060 else if (t.cs() == "begin") {
1061 string const name = p.getArg('{', '}');
1062 if (name == "document")
1064 h_preamble << "\\begin{" << name << "}";
1067 else if (t.cs() == "geometry") {
1068 h_use_geometry = "true";
1069 vector<string> opts = split_options(p.getArg('{', '}'));
1070 vector<string>::iterator it;
1071 // paper orientation
1072 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
1073 h_paperorientation = "landscape";
1077 handle_opt(opts, known_paper_sizes, h_papersize);
1078 delete_opt(opts, known_paper_sizes);
1080 char const * const * margin = known_paper_margins;
1082 for (; *margin; ++margin) {
1084 // search for the "=" in e.g. "lmargin=2cm" to get the value
1085 for(size_t i = 0; i != opts.size(); i++) {
1086 if (opts.at(i).find(*margin) != string::npos) {
1087 string::size_type pos = opts.at(i).find("=");
1088 string value = opts.at(i).substr(pos + 1);
1089 string name = known_coded_paper_margins[k];
1090 h_margins += "\\" + name + " " + value + "\n";
1096 else if (t.cs() == "definecolor") {
1097 string const color = p.getArg('{', '}');
1098 string const space = p.getArg('{', '}');
1099 string const value = p.getArg('{', '}');
1100 if (color == "note_fontcolor" && space == "rgb") {
1101 RGBColor c(RGBColorFromLaTeX(value));
1102 h_notefontcolor = X11hexname(c);
1104 h_preamble << "\\definecolor{" << color
1105 << "}{" << space << "}{" << value
1110 else if (t.cs() == "jurabibsetup") {
1111 // FIXME p.getArg('{', '}') is most probably wrong (it
1112 // does not handle nested braces).
1113 // Use p.verbatim_item() instead.
1114 vector<string> jurabibsetup =
1115 split_options(p.getArg('{', '}'));
1116 // add jurabibsetup to the jurabib package options
1117 add_package("jurabib", jurabibsetup);
1118 if (!jurabibsetup.empty()) {
1119 h_preamble << "\\jurabibsetup{"
1120 << join(jurabibsetup, ",") << '}';
1124 else if (t.cs() == "hypersetup") {
1125 vector<string> hypersetup =
1126 split_options(p.verbatim_item());
1127 // add hypersetup to the hyperref package options
1128 handle_hyperref(hypersetup);
1129 if (!hypersetup.empty()) {
1130 h_preamble << "\\hypersetup{"
1131 << join(hypersetup, ",") << '}';
1135 else if (is_known(t.cs(), known_if_3arg_commands)) {
1136 // prevent misparsing of \usepackage if it is used
1137 // as an argument (see e.g. our own output of
1138 // \@ifundefined above)
1139 string const arg1 = p.verbatim_item();
1140 string const arg2 = p.verbatim_item();
1141 string const arg3 = p.verbatim_item();
1142 if (!in_lyx_preamble) {
1143 h_preamble << t.asInput()
1144 << '{' << arg1 << '}'
1145 << '{' << arg2 << '}'
1146 << '{' << arg3 << '}';
1150 else if (is_known(t.cs(), known_if_commands)) {
1151 // must not parse anything in conditional code, since
1152 // LyX would output the parsed contents unconditionally
1153 if (!in_lyx_preamble)
1154 h_preamble << t.asInput();
1155 handle_if(p, in_lyx_preamble);
1158 else if (!t.cs().empty() && !in_lyx_preamble)
1159 h_preamble << '\\' << t.cs();
1162 // remove the whitespace
1165 // Force textclass if the user wanted it
1166 if (!forceclass.empty())
1167 h_textclass = forceclass;
1168 if (noweb_mode && !prefixIs(h_textclass, "literate-"))
1169 h_textclass.insert(0, "literate-");
1170 tc.setName(h_textclass);
1172 cerr << "Error: Could not read layout file for textclass \"" << h_textclass << "\"." << endl;
1175 if (h_papersides.empty()) {
1178 h_papersides = ss.str();
1180 end_preamble(os, tc);
1184 /// translates a babel language name to a LyX language name
1185 string babel2lyx(string const & language)
1187 char const * const * where = is_known(language, known_languages);
1189 return known_coded_languages[where - known_languages];