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",
153 ostringstream h_preamble;
154 string h_textclass = "article";
155 string h_use_default_options = "false";
157 string h_language = "english";
158 string h_inputencoding = "auto";
159 string h_font_roman = "default";
160 string h_font_sans = "default";
161 string h_font_typewriter = "default";
162 string h_font_default_family = "default";
163 string h_font_sc = "false";
164 string h_font_osf = "false";
165 string h_font_sf_scale = "100";
166 string h_font_tt_scale = "100";
167 string h_graphics = "default";
168 string h_float_placement;
169 string h_paperfontsize = "default";
170 string h_spacing = "single";
171 string h_use_hyperref = "0";
174 string h_pdf_subject;
175 string h_pdf_keywords;
176 string h_pdf_bookmarks = "1";
177 string h_pdf_bookmarksnumbered = "0";
178 string h_pdf_bookmarksopen = "0";
179 string h_pdf_bookmarksopenlevel = "1";
180 string h_pdf_breaklinks = "0";
181 string h_pdf_pdfborder = "0";
182 string h_pdf_colorlinks = "0";
183 string h_pdf_backref = "section";
184 string h_pdf_pdfusetitle = "1";
185 string h_pdf_pagemode;
186 string h_pdf_quoted_options;
187 string h_papersize = "default";
188 string h_use_geometry = "false";
189 string h_use_amsmath = "1";
190 string h_use_esint = "1";
191 string h_cite_engine = "basic";
192 string h_use_bibtopic = "false";
193 string h_paperorientation = "portrait";
194 string h_secnumdepth = "3";
195 string h_tocdepth = "3";
196 string h_paragraph_separation = "indent";
197 string h_defskip = "medskip";
198 string h_paragraph_indentation = "default";
199 string h_quotes_language = "english";
200 string h_papercolumns = "1";
202 string h_paperpagestyle = "default";
203 string h_listings_params;
204 string h_tracking_changes = "false";
205 string h_output_changes = "false";
209 // returns true if at least one of the options in what has been found
210 bool handle_opt(vector<string> & opts, char const * const * what, string & target)
216 // the last language option is the document language (for babel and LyX)
217 // the last size option is the document font size
218 vector<string>::iterator it;
219 vector<string>::iterator position = opts.begin();
220 for (; *what; ++what) {
221 it = find(opts.begin(), opts.end(), *what);
222 if (it != opts.end()) {
223 if (it >= position) {
234 void delete_opt(vector<string> & opts, char const * const * what)
239 // remove found options from the list
240 // do this after handle_opt to avoid potential memory leaks
241 vector<string>::iterator it;
242 for (; *what; ++what) {
243 it = find(opts.begin(), opts.end(), *what);
244 if (it != opts.end())
251 * Split a package options string (keyval format) into a vector.
253 * authorformat=smallcaps,
255 * titleformat=colonsep,
256 * bibformat={tabular,ibidem,numbered}
258 vector<string> split_options(string const & input)
260 vector<string> options;
264 Token const & t = p.get_token();
265 if (t.asInput() == ",") {
266 options.push_back(trim(option));
268 } else if (t.asInput() == "=") {
271 if (p.next_token().asInput() == "{")
272 option += '{' + p.getArg('{', '}') + '}';
273 } else if (t.cat() != catSpace)
274 option += t.asInput();
278 options.push_back(trim(option));
285 * Retrieve a keyval option "name={value with=sign}" named \p name from
286 * \p options and return the value.
287 * The found option is also removed from \p options.
289 string process_keyval_opt(vector<string> & options, string name)
291 for (size_t i = 0; i < options.size(); ++i) {
292 vector<string> option;
293 split(options[i], option, '=');
294 if (option.size() < 2)
296 if (option[0] == name) {
297 options.erase(options.begin() + i);
298 option.erase(option.begin());
299 return join(option, "=");
307 * Add package \p name with options \p options to used_packages.
308 * Remove options from \p options that we don't want to output.
310 void add_package(string const & name, vector<string> & options)
312 // every package inherits the global options
313 if (used_packages.find(name) == used_packages.end())
314 used_packages[name] = split_options(h_options);
316 vector<string> & v = used_packages[name];
317 v.insert(v.end(), options.begin(), options.end());
318 if (name == "jurabib") {
319 // Don't output the order argument (see the cite command
320 // handling code in text.cpp).
321 vector<string>::iterator end =
322 remove(options.begin(), options.end(), "natbiborder");
323 end = remove(options.begin(), end, "jurabiborder");
324 options.erase(end, options.end());
329 // Given is a string like "scaled=0.9", return 0.9 * 100
330 string const scale_as_percentage(string const & scale)
332 string::size_type pos = scale.find('=');
333 if (pos != string::npos) {
334 string value = scale.substr(pos + 1);
336 return convert<string>(100 * convert<double>(value));
338 // If the input string didn't match our expectations.
339 // return the default value "100"
344 string remove_braces(string const & value)
348 if (value[0] == '{' && value[value.length()-1] == '}')
349 return value.substr(1, value.length()-2);
354 void handle_hyperref(vector<string> & options)
356 // FIXME swallow inputencoding changes that might surround the
357 // hyperref setup if it was written by LyX
358 h_use_hyperref = "1";
359 // swallow "unicode=true", since LyX does always write that
360 vector<string>::iterator it =
361 find(options.begin(), options.end(), "unicode=true");
362 if (it != options.end())
364 it = find(options.begin(), options.end(), "pdfusetitle");
365 if (it != options.end()) {
366 h_pdf_pdfusetitle = "1";
369 string bookmarks = process_keyval_opt(options, "bookmarks");
370 if (bookmarks == "true")
371 h_pdf_bookmarks = "1";
372 else if (bookmarks == "false")
373 h_pdf_bookmarks = "0";
374 if (h_pdf_bookmarks == "1") {
375 string bookmarksnumbered =
376 process_keyval_opt(options, "bookmarksnumbered");
377 if (bookmarksnumbered == "true")
378 h_pdf_bookmarksnumbered = "1";
379 else if (bookmarksnumbered == "false")
380 h_pdf_bookmarksnumbered = "0";
381 string bookmarksopen =
382 process_keyval_opt(options, "bookmarksopen");
383 if (bookmarksopen == "true")
384 h_pdf_bookmarksopen = "1";
385 else if (bookmarksopen == "false")
386 h_pdf_bookmarksopen = "0";
387 if (h_pdf_bookmarksopen == "1") {
388 string bookmarksopenlevel =
389 process_keyval_opt(options, "bookmarksopenlevel");
390 if (!bookmarksopenlevel.empty())
391 h_pdf_bookmarksopenlevel = bookmarksopenlevel;
394 string breaklinks = process_keyval_opt(options, "breaklinks");
395 if (breaklinks == "true")
396 h_pdf_breaklinks = "1";
397 else if (breaklinks == "false")
398 h_pdf_breaklinks = "0";
399 string pdfborder = process_keyval_opt(options, "pdfborder");
400 if (pdfborder == "{0 0 0}")
401 h_pdf_pdfborder = "1";
402 else if (pdfborder == "{0 0 1}")
403 h_pdf_pdfborder = "0";
404 string backref = process_keyval_opt(options, "backref");
405 if (!backref.empty())
406 h_pdf_backref = backref;
407 string colorlinks = process_keyval_opt(options, "colorlinks");
408 if (colorlinks == "true")
409 h_pdf_colorlinks = "1";
410 else if (colorlinks == "false")
411 h_pdf_colorlinks = "0";
412 string pdfpagemode = process_keyval_opt(options, "pdfpagemode");
413 if (!pdfpagemode.empty())
414 h_pdf_pagemode = pdfpagemode;
415 string pdftitle = process_keyval_opt(options, "pdftitle");
416 if (!pdftitle.empty()) {
417 h_pdf_title = remove_braces(pdftitle);
419 string pdfauthor = process_keyval_opt(options, "pdfauthor");
420 if (!pdfauthor.empty()) {
421 h_pdf_author = remove_braces(pdfauthor);
423 string pdfsubject = process_keyval_opt(options, "pdfsubject");
424 if (!pdfsubject.empty())
425 h_pdf_subject = remove_braces(pdfsubject);
426 string pdfkeywords = process_keyval_opt(options, "pdfkeywords");
427 if (!pdfkeywords.empty())
428 h_pdf_keywords = remove_braces(pdfkeywords);
429 if (!options.empty()) {
430 if (!h_pdf_quoted_options.empty())
431 h_pdf_quoted_options += ',';
432 h_pdf_quoted_options += join(options, ",");
438 void handle_package(Parser &p, string const & name, string const & opts,
439 bool in_lyx_preamble)
441 vector<string> options = split_options(opts);
442 add_package(name, options);
446 if (is_known(name, known_roman_fonts)) {
451 if (name == "fourier") {
452 h_font_roman = "utopia";
453 // when font uses real small capitals
454 if (opts == "expert")
458 if (name == "mathpazo")
459 h_font_roman = "palatino";
461 if (name == "mathptmx")
462 h_font_roman = "times";
465 if (is_known(name, known_sans_fonts)) {
469 h_font_sf_scale = scale_as_percentage(scale);
474 if (is_known(name, known_typewriter_fonts)) {
475 h_font_typewriter = name;
478 h_font_tt_scale = scale_as_percentage(scale);
482 // font uses old-style figure
486 else if (name == "amsmath" || name == "amssymb")
489 else if (name == "esint")
492 else if (name == "babel" && !opts.empty()) {
493 // check if more than one option was used - used later for inputenc
494 // in case inputenc is parsed before babel, set the encoding to auto
495 if (options.begin() != options.end() - 1) {
496 one_language = false;
497 h_inputencoding = "auto";
499 // babel takes the last language of the option of its \usepackage
500 // call as document language. If there is no such language option, the
501 // last language in the documentclass options is used.
502 handle_opt(options, known_languages, h_language);
503 delete_opt(options, known_languages);
506 else if (name == "fontenc")
509 else if (name == "inputenc") {
510 // h_inputencoding is only set when there is not more than one
511 // inputenc option because otherwise h_inputencoding must be
512 // set to "auto" (the default encoding of the document language)
513 // Therefore check for the "," character.
514 // It is also only set when there is not more then one babel
515 // language option but this is handled in the routine for babel.
516 if (opts.find(",") == string::npos && one_language == true)
517 h_inputencoding = opts;
518 if (!options.empty())
519 p.setEncoding(options.back());
523 else if (name == "makeidx")
526 else if (name == "prettyref")
529 else if (name == "varioref")
532 else if (name == "verbatim")
535 else if (name == "nomencl")
538 else if (name == "textcomp")
541 else if (name == "url")
544 else if (LYX_FORMAT >= 408 && name == "subscript")
547 else if (name == "color") {
548 // with the following command this package is only loaded when needed for
549 // undefined colors, since we only support the predefined colors
550 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
553 else if (name == "graphicx")
556 else if (name == "setspace")
559 else if (name == "geometry")
560 ; // Ignore this, the geometry settings are made by the \geometry
561 // command. This command is handled below.
563 else if (is_known(name, known_languages))
566 else if (name == "natbib") {
567 h_cite_engine = "natbib_authoryear";
568 vector<string>::iterator it =
569 find(options.begin(), options.end(), "authoryear");
570 if (it != options.end())
573 it = find(options.begin(), options.end(), "numbers");
574 if (it != options.end()) {
575 h_cite_engine = "natbib_numerical";
581 else if (name == "jurabib")
582 h_cite_engine = "jurabib";
584 else if (name == "hyperref")
585 handle_hyperref(options);
587 else if (!in_lyx_preamble) {
589 h_preamble << "\\usepackage{" << name << "}";
591 h_preamble << "\\usepackage[" << opts << "]{"
597 // We need to do something with the options...
598 if (!options.empty())
599 cerr << "Ignoring options '" << join(options, ",")
600 << "' of package " << name << '.' << endl;
602 // remove the whitespace
608 void end_preamble(ostream & os, TextClass const & /*textclass*/)
610 // translate from babel to LyX names
611 h_language = babel2lyx(h_language);
613 // set the quote language
614 // LyX only knows the following quotes languages:
615 // english, swedish, german, polish, french and danish
616 // (quotes for "japanese" and "chinese-traditional" are missing because
617 // they wouldn't be useful: http://www.lyx.org/trac/ticket/6383)
618 // conversion list taken from
619 // http://en.wikipedia.org/wiki/Quotation_mark,_non-English_usage
620 // (quotes for kazakh and interlingua are unknown)
622 if (h_language == "danish")
623 h_quotes_language = "danish";
625 else if (is_known(h_language, known_french_quotes_languages))
626 h_quotes_language = "french";
628 else if (is_known(h_language, known_german_quotes_languages))
629 h_quotes_language = "german";
631 else if (is_known(h_language, known_polish_quotes_languages))
632 h_quotes_language = "polish";
634 else if (is_known(h_language, known_swedish_quotes_languages))
635 h_quotes_language = "swedish";
637 else if (is_known(h_language, known_english_quotes_languages))
638 h_quotes_language = "english";
640 // output the LyX file settings
641 os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
642 << "\\lyxformat " << LYX_FORMAT << '\n'
643 << "\\begin_document\n"
644 << "\\begin_header\n"
645 << "\\textclass " << h_textclass << "\n";
646 if (!h_preamble.str().empty())
647 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
648 if (!h_options.empty())
649 os << "\\options " << h_options << "\n";
650 os << "\\use_default_options " << h_use_default_options << "\n"
651 << "\\language " << h_language << "\n"
652 << "\\inputencoding " << h_inputencoding << "\n"
653 << "\\font_roman " << h_font_roman << "\n"
654 << "\\font_sans " << h_font_sans << "\n"
655 << "\\font_typewriter " << h_font_typewriter << "\n"
656 << "\\font_default_family " << h_font_default_family << "\n"
657 << "\\font_sc " << h_font_sc << "\n"
658 << "\\font_osf " << h_font_osf << "\n"
659 << "\\font_sf_scale " << h_font_sf_scale << "\n"
660 << "\\font_tt_scale " << h_font_tt_scale << "\n"
661 << "\\graphics " << h_graphics << "\n";
662 if (!h_float_placement.empty())
663 os << "\\float_placement " << h_float_placement << "\n";
664 os << "\\paperfontsize " << h_paperfontsize << "\n"
665 << "\\spacing " << h_spacing << "\n"
666 << "\\use_hyperref " << h_use_hyperref << '\n';
667 if (h_use_hyperref == "1") {
668 if (!h_pdf_title.empty())
669 os << "\\pdf_title \"" << h_pdf_title << "\"\n";
670 if (!h_pdf_author.empty())
671 os << "\\pdf_author \"" << h_pdf_author << "\"\n";
672 if (!h_pdf_subject.empty())
673 os << "\\pdf_subject \"" << h_pdf_subject << "\"\n";
674 if (!h_pdf_keywords.empty())
675 os << "\\pdf_keywords \"" << h_pdf_keywords << "\"\n";
676 os << "\\pdf_bookmarks " << h_pdf_bookmarks << "\n"
677 "\\pdf_bookmarksnumbered " << h_pdf_bookmarksnumbered << "\n"
678 "\\pdf_bookmarksopen " << h_pdf_bookmarksopen << "\n"
679 "\\pdf_bookmarksopenlevel " << h_pdf_bookmarksopenlevel << "\n"
680 "\\pdf_breaklinks " << h_pdf_breaklinks << "\n"
681 "\\pdf_pdfborder " << h_pdf_pdfborder << "\n"
682 "\\pdf_colorlinks " << h_pdf_colorlinks << "\n"
683 "\\pdf_backref " << h_pdf_backref << "\n"
684 "\\pdf_pdfusetitle " << h_pdf_pdfusetitle << '\n';
685 if (!h_pdf_pagemode.empty())
686 os << "\\pdf_pagemode " << h_pdf_pagemode << '\n';
687 if (!h_pdf_quoted_options.empty())
688 os << "\\pdf_quoted_options \"" << h_pdf_quoted_options << "\"\n";
690 os << "\\papersize " << h_papersize << "\n"
691 << "\\use_geometry " << h_use_geometry << "\n"
692 << "\\use_amsmath " << h_use_amsmath << "\n"
693 << "\\use_esint " << h_use_esint << "\n"
694 << "\\cite_engine " << h_cite_engine << "\n"
695 << "\\use_bibtopic " << h_use_bibtopic << "\n"
696 << "\\paperorientation " << h_paperorientation << "\n"
698 << "\\secnumdepth " << h_secnumdepth << "\n"
699 << "\\tocdepth " << h_tocdepth << "\n"
700 << "\\paragraph_separation " << h_paragraph_separation << "\n";
701 if (LYX_FORMAT < 365 || h_paragraph_separation == "skip")
702 os << "\\defskip " << h_defskip << "\n";
704 os << "\\paragraph_indentation " << h_paragraph_indentation << "\n";
705 os << "\\quotes_language " << h_quotes_language << "\n"
706 << "\\papercolumns " << h_papercolumns << "\n"
707 << "\\papersides " << h_papersides << "\n"
708 << "\\paperpagestyle " << h_paperpagestyle << "\n";
709 if (!h_listings_params.empty())
710 os << "\\listings_params " << h_listings_params << "\n";
711 os << "\\tracking_changes " << h_tracking_changes << "\n"
712 << "\\output_changes " << h_output_changes << "\n"
713 << "\\end_header\n\n"
715 // clear preamble for subdocuments
719 } // anonymous namespace
722 void parse_preamble(Parser & p, ostream & os,
723 string const & forceclass, TeX2LyXDocClass & tc)
725 // initialize fixed types
726 special_columns['D'] = 3;
727 bool is_full_document = false;
728 bool is_lyx_file = false;
729 bool in_lyx_preamble = false;
731 // determine whether this is a full document or a fragment for inclusion
733 Token const & t = p.get_token();
735 if (t.cat() == catEscape && t.cs() == "documentclass") {
736 is_full_document = true;
742 while (is_full_document && p.good()) {
743 Token const & t = p.get_token();
746 cerr << "t: " << t << "\n";
752 if (!in_lyx_preamble &&
753 (t.cat() == catLetter ||
754 t.cat() == catSuper ||
756 t.cat() == catOther ||
757 t.cat() == catMath ||
758 t.cat() == catActive ||
759 t.cat() == catBegin ||
761 t.cat() == catAlign ||
762 t.cat() == catParameter))
763 h_preamble << t.cs();
765 else if (!in_lyx_preamble &&
766 (t.cat() == catSpace || t.cat() == catNewline))
767 h_preamble << t.asInput();
769 else if (t.cat() == catComment) {
770 // regex to parse comments (currently not used)
771 static regex const islyxfile("%% LyX .* created this file");
772 static regex const usercommands("User specified LaTeX commands");
774 string const comment = t.asInput();
776 // magically switch encoding default if it looks like XeLaTeX
777 static string const magicXeLaTeX =
778 "% This document must be compiled with XeLaTeX ";
779 if (comment.size() > magicXeLaTeX.size()
780 && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
781 && h_inputencoding == "auto") {
782 cerr << "XeLaTeX comment found, switching to UTF8\n";
783 h_inputencoding = "utf8";
786 if (regex_search(comment, sub, islyxfile)) {
788 in_lyx_preamble = true;
789 } else if (is_lyx_file
790 && regex_search(comment, sub, usercommands))
791 in_lyx_preamble = false;
792 else if (!in_lyx_preamble)
793 h_preamble << t.asInput();
796 else if (t.cs() == "pagestyle")
797 h_paperpagestyle = p.verbatim_item();
799 else if (t.cs() == "makeatletter") {
800 // LyX takes care of this
801 p.setCatCode('@', catLetter);
804 else if (t.cs() == "makeatother") {
805 // LyX takes care of this
806 p.setCatCode('@', catOther);
809 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
810 || t.cs() == "providecommand"
811 || t.cs() == "DeclareRobustCommand"
812 || t.cs() == "ProvideTextCommandDefault"
813 || t.cs() == "DeclareMathAccent") {
815 if (p.next_token().character() == '*') {
819 string const name = p.verbatim_item();
820 string const opt1 = p.getOpt();
821 string const opt2 = p.getFullOpt();
822 string const body = p.verbatim_item();
824 if (name == "\\rmdefault")
825 if (is_known(body, known_roman_fonts))
827 if (name == "\\sfdefault")
828 if (is_known(body, known_sans_fonts))
830 if (name == "\\ttdefault")
831 if (is_known(body, known_typewriter_fonts))
832 h_font_typewriter = body;
833 if (name == "\\familydefault") {
834 string family = body;
835 // remove leading "\"
836 h_font_default_family = family.erase(0,1);
838 // only non-lyxspecific stuff
839 if (!in_lyx_preamble) {
841 ss << '\\' << t.cs();
844 ss << '{' << name << '}' << opt1 << opt2
845 << '{' << body << "}";
846 h_preamble << ss.str();
848 // Add the command to the known commands
849 add_known_command(name, opt1, !opt2.empty());
851 ostream & out = in_preamble ? h_preamble : os;
852 out << "\\" << t.cs() << "{" << name << "}"
853 << opts << "{" << body << "}";
858 else if (t.cs() == "documentclass") {
859 vector<string>::iterator it;
860 vector<string> opts = split_options(p.getArg('[', ']'));
861 handle_opt(opts, known_fontsizes, h_paperfontsize);
862 delete_opt(opts, known_fontsizes);
863 // delete "pt" at the end
864 string::size_type i = h_paperfontsize.find("pt");
865 if (i != string::npos)
866 h_paperfontsize.erase(i);
867 // The documentclass options are always parsed before the options
868 // of the babel call so that a language cannot overwrite the babel
870 handle_opt(opts, known_languages, h_language);
871 delete_opt(opts, known_languages);
874 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
875 h_paperorientation = "landscape";
879 if ((it = find(opts.begin(), opts.end(), "oneside"))
884 if ((it = find(opts.begin(), opts.end(), "twoside"))
890 if ((it = find(opts.begin(), opts.end(), "onecolumn"))
892 h_papercolumns = "1";
895 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
897 h_papercolumns = "2";
901 // some size options are know to any document classes, other sizes
902 // are handled by the \geometry command of the geometry package
903 handle_opt(opts, known_class_paper_sizes, h_papersize);
904 delete_opt(opts, known_class_paper_sizes);
905 // the remaining options
906 h_options = join(opts, ",");
907 h_textclass = p.getArg('{', '}');
910 else if (t.cs() == "usepackage") {
911 string const options = p.getArg('[', ']');
912 string const name = p.getArg('{', '}');
913 vector<string> vecnames;
914 split(name, vecnames, ',');
915 vector<string>::const_iterator it = vecnames.begin();
916 vector<string>::const_iterator end = vecnames.end();
917 for (; it != end; ++it)
918 handle_package(p, trim(*it), options,
922 else if (t.cs() == "inputencoding") {
923 string const encoding = p.getArg('{','}');
924 h_inputencoding = encoding;
925 p.setEncoding(encoding);
928 else if (t.cs() == "newenvironment") {
929 string const name = p.getArg('{', '}');
931 ss << "\\newenvironment{" << name << "}";
934 ss << '{' << p.verbatim_item() << '}';
935 ss << '{' << p.verbatim_item() << '}';
936 if (!in_lyx_preamble)
937 h_preamble << ss.str();
940 else if (t.cs() == "def") {
941 string name = p.get_token().cs();
942 while (p.next_token().cat() != catBegin)
943 name += p.get_token().cs();
944 if (!in_lyx_preamble)
945 h_preamble << "\\def\\" << name << '{'
946 << p.verbatim_item() << "}";
949 else if (t.cs() == "newcolumntype") {
950 string const name = p.getArg('{', '}');
953 string opts = p.getOpt();
955 istringstream is(string(opts, 1));
958 special_columns[name[0]] = nargs;
959 h_preamble << "\\newcolumntype{" << name << "}";
961 h_preamble << "[" << nargs << "]";
962 h_preamble << "{" << p.verbatim_item() << "}";
965 else if (t.cs() == "setcounter") {
966 string const name = p.getArg('{', '}');
967 string const content = p.getArg('{', '}');
968 if (name == "secnumdepth")
969 h_secnumdepth = content;
970 else if (name == "tocdepth")
971 h_tocdepth = content;
973 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
976 else if (t.cs() == "setlength") {
977 string const name = p.verbatim_item();
978 string const content = p.verbatim_item();
979 // the paragraphs are only not indented when \parindent is set to zero
980 if (name == "\\parindent" && content != "") {
981 if (content[0] == '0')
982 h_paragraph_separation = "skip";
983 else if (LYX_FORMAT >= 365)
984 h_paragraph_indentation = translate_len(content);
986 h_preamble << "\\setlength{" << name
987 << "}{" << content << "}";
988 } else if (name == "\\parskip") {
989 if (content == "\\smallskipamount")
990 h_defskip = "smallskip";
991 else if (content == "\\medskipamount")
992 h_defskip = "medskip";
993 else if (content == "\\bigskipamount")
994 h_defskip = "bigskip";
998 h_preamble << "\\setlength{" << name << "}{" << content << "}";
1001 else if (t.cs() == "onehalfspacing")
1002 h_spacing = "onehalf";
1004 else if (t.cs() == "doublespacing")
1005 h_spacing = "double";
1007 else if (t.cs() == "setstretch")
1008 h_spacing = "other " + p.verbatim_item();
1010 else if (t.cs() == "begin") {
1011 string const name = p.getArg('{', '}');
1012 if (name == "document")
1014 h_preamble << "\\begin{" << name << "}";
1017 else if (t.cs() == "geometry") {
1018 h_use_geometry = "true";
1019 vector<string> opts = split_options(p.getArg('{', '}'));
1020 vector<string>::iterator it;
1021 // paper orientation
1022 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
1023 h_paperorientation = "landscape";
1027 handle_opt(opts, known_paper_sizes, h_papersize);
1028 delete_opt(opts, known_paper_sizes);
1030 char const * const * margin = known_paper_margins;
1032 for (; *margin; ++margin) {
1034 // search for the "=" in e.g. "lmargin=2cm" to get the value
1035 for(size_t i = 0; i != opts.size(); i++) {
1036 if (opts.at(i).find(*margin) != string::npos) {
1037 string::size_type pos = opts.at(i).find("=");
1038 string value = opts.at(i).substr(pos + 1);
1039 string name = known_coded_paper_margins[k];
1040 h_margins += "\\" + name + " " + value + "\n";
1046 else if (t.cs() == "jurabibsetup") {
1047 // FIXME p.getArg('{', '}') is most probably wrong (it
1048 // does not handle nested braces).
1049 // Use p.verbatim_item() instead.
1050 vector<string> jurabibsetup =
1051 split_options(p.getArg('{', '}'));
1052 // add jurabibsetup to the jurabib package options
1053 add_package("jurabib", jurabibsetup);
1054 if (!jurabibsetup.empty()) {
1055 h_preamble << "\\jurabibsetup{"
1056 << join(jurabibsetup, ",") << '}';
1060 else if (t.cs() == "hypersetup") {
1061 vector<string> hypersetup =
1062 split_options(p.verbatim_item());
1063 // add hypersetup to the hyperref package options
1064 handle_hyperref(hypersetup);
1065 if (!hypersetup.empty()) {
1066 h_preamble << "\\hypersetup{"
1067 << join(hypersetup, ",") << '}';
1071 else if (t.cs() == "@ifundefined") {
1072 // prevent misparsing of \usepackage if it is used
1073 // as an argument (see e.g. our own output of
1074 // \@ifundefined above)
1075 h_preamble << t.asInput();
1076 h_preamble << '{' << p.verbatim_item() << '}';
1077 h_preamble << '{' << p.verbatim_item() << '}';
1078 h_preamble << '{' << p.verbatim_item() << '}';
1081 else if (!t.cs().empty() && !in_lyx_preamble)
1082 h_preamble << '\\' << t.cs();
1085 // remove the whitespace
1088 // Force textclass if the user wanted it
1089 if (!forceclass.empty())
1090 h_textclass = forceclass;
1091 if (noweb_mode && !prefixIs(h_textclass, "literate-"))
1092 h_textclass.insert(0, "literate-");
1093 FileName layoutfilename = libFileSearch("layouts", h_textclass, "layout");
1094 if (layoutfilename.empty()) {
1095 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
1098 tc.read(layoutfilename);
1099 if (h_papersides.empty()) {
1102 h_papersides = ss.str();
1104 end_preamble(os, tc);
1108 /// translates a babel language name to a LyX language name
1109 string babel2lyx(string const & language)
1111 char const * const * where = is_known(language, known_languages);
1113 return known_coded_languages[where - known_languages];