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 <boost/regex.hpp>
38 using namespace lyx::support;
44 // special columntypes
45 extern map<char, int> special_columns;
47 map<string, vector<string> > used_packages;
49 // needed to handle encodings with babel
50 bool one_language = true;
52 // to avoid that the babel options overwrite the documentclass options
53 bool documentclass_language;
57 const char * const known_languages[] = { "afrikaans", "american", "arabic",
58 "austrian", "bahasa", "basque", "belarusian", "brazil", "breton", "british",
59 "bulgarian", "canadian", "canadien", "catalan", "croatian", "czech", "danish",
60 "dutch", "english", "esperanto", "estonian", "finnish", "francais", "french",
61 "frenchb", "frenchle", "frenchpro", "galician", "german", "germanb", "greek",
62 "hebrew", "icelandic", "irish", "italian", "lsorbian", "magyar", "naustrian",
63 "ngerman", "ngermanb", "norsk", "nynorsk", "polish", "portuges", "romanian",
64 "russian", "russianb", "scottish", "serbian", "slovak", "slovene", "spanish",
65 "swedish", "thai", "turkish", "ukraineb", "ukrainian", "usorbian", "welsh", 0};
67 //note this when updating to lyxformat 305:
68 //bahasai, indonesian, and indon = equal to bahasa
69 //malay, and meyalu = equal to bahasam
71 const char * const known_french_languages[] = {"french", "frenchb", "francais",
72 "frenchle", "frenchpro", 0};
73 const char * const known_german_languages[] = {"german", "germanb", 0};
74 const char * const known_ngerman_languages[] = {"ngerman", "ngermanb", 0};
75 const char * const known_russian_languages[] = {"russian", "russianb", 0};
76 const char * const known_ukrainian_languages[] = {"ukrainian", "ukraineb", 0};
78 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
80 const char * const known_roman_fonts[] = { "ae", "bookman", "charter",
81 "cmr", "fourier", "lmodern", "mathpazo", "mathptmx", "newcent", 0};
83 const char * const known_sans_fonts[] = { "avant", "berasans", "cmbr", "cmss",
86 const char * const known_typewriter_fonts[] = { "beramono", "cmtl", "cmtt",
87 "courier", "lmtt", "luximono", "fourier", "lmodern", "mathpazo", "mathptmx",
90 const char * const known_paper_sizes[] = { "a3paper", "b3paper", "a4paper",
91 "b4paper", "a5paper", "b5paper", "executivepaper", "legalpaper",
94 const char * const known_class_paper_sizes[] = { "a4paper", "a5paper",
95 "executivepaper", "legalpaper", "letterpaper", 0};
97 const char * const known_paper_margins[] = { "lmargin", "tmargin", "rmargin",
98 "bmargin", "headheight", "headsep", "footskip", "columnsep", 0};
100 const char * const known_coded_paper_margins[] = { "leftmargin", "topmargin",
101 "rightmargin", "bottommargin", "headheight", "headsep", "footskip",
105 ostringstream h_preamble;
106 string h_textclass = "article";
107 string h_options = string();
108 string h_language = "english";
109 string h_inputencoding = "auto";
110 string h_font_roman = "default";
111 string h_font_sans = "default";
112 string h_font_typewriter = "default";
113 string h_font_default_family = "default";
114 string h_font_sc = "false";
115 string h_font_osf = "false";
116 string h_font_sf_scale = "100";
117 string h_font_tt_scale = "100";
118 string h_graphics = "default";
119 string h_paperfontsize = "default";
120 string h_spacing = "single";
121 string h_papersize = "default";
122 string h_use_geometry = "false";
123 string h_use_amsmath = "1";
124 string h_use_esint = "1";
125 string h_cite_engine = "basic";
126 string h_use_bibtopic = "false";
127 string h_paperorientation = "portrait";
128 string h_secnumdepth = "3";
129 string h_tocdepth = "3";
130 string h_paragraph_separation = "indent";
131 string h_defskip = "medskip";
132 string h_quotes_language = "english";
133 string h_papercolumns = "1";
134 string h_papersides = string();
135 string h_paperpagestyle = "default";
136 string h_tracking_changes = "false";
137 string h_output_changes = "false";
138 string h_margins = "";
141 void handle_opt(vector<string> & opts, char const * const * what, string & target)
146 // the last language option is the document language (for babel and LyX)
147 // the last size option is the document font size
148 vector<string>::iterator it;
149 vector<string>::iterator position = opts.begin();
150 for (; *what; ++what) {
151 it = find(opts.begin(), opts.end(), *what);
152 if (it != opts.end()) {
153 documentclass_language = true;
154 if (it >= position) {
163 void delete_opt(vector<string> & opts, char const * const * what)
168 // remove found options from the list
169 // do this after handle_opt to avoid potential memory leaks and to be able
170 // to find in every case the last language option
171 vector<string>::iterator it;
172 for (; *what; ++what) {
173 it = find(opts.begin(), opts.end(), *what);
174 if (it != opts.end())
181 * Split a package options string (keyval format) into a vector.
183 * authorformat=smallcaps,
185 * titleformat=colonsep,
186 * bibformat={tabular,ibidem,numbered}
188 vector<string> split_options(string const & input)
190 vector<string> options;
194 Token const & t = p.get_token();
195 if (t.asInput() == ",") {
196 options.push_back(trim(option));
198 } else if (t.asInput() == "=") {
201 if (p.next_token().asInput() == "{")
202 option += '{' + p.getArg('{', '}') + '}';
203 } else if (t.cat() != catSpace)
204 option += t.asInput();
208 options.push_back(trim(option));
215 * Add package \p name with options \p options to used_packages.
216 * Remove options from \p options that we don't want to output.
218 void add_package(string const & name, vector<string> & options)
220 // every package inherits the global options
221 if (used_packages.find(name) == used_packages.end())
222 used_packages[name] = split_options(h_options);
224 vector<string> & v = used_packages[name];
225 v.insert(v.end(), options.begin(), options.end());
226 if (name == "jurabib") {
227 // Don't output the order argument (see the cite command
228 // handling code in text.cpp).
229 vector<string>::iterator end =
230 remove(options.begin(), options.end(), "natbiborder");
231 end = remove(options.begin(), end, "jurabiborder");
232 options.erase(end, options.end());
237 // Given is a string like "scaled=0.9", return 0.9 * 100
238 string const scale_as_percentage(string const & scale)
240 string::size_type pos = scale.find('=');
241 if (pos != string::npos) {
242 string value = scale.substr(pos + 1);
244 return convert<string>(100 * convert<double>(value));
246 // If the input string didn't match our expectations.
247 // return the default value "100"
252 void handle_package(Parser &p, string const & name, string const & opts,
253 bool in_lyx_preamble)
255 vector<string> options = split_options(opts);
256 add_package(name, options);
260 if (is_known(name, known_roman_fonts)) {
265 if (name == "fourier") {
266 h_font_roman = "utopia";
267 // when font uses real small capitals
268 if (opts == "expert")
273 if (name == "mathpazo") {
274 h_font_roman = "palatino";
278 if (name == "mathptmx") {
279 h_font_roman = "times";
284 if (is_known(name, known_sans_fonts)) {
288 h_font_sf_scale = scale_as_percentage(scale);
294 if (is_known(name, known_typewriter_fonts)) {
295 h_font_typewriter = name;
298 h_font_tt_scale = scale_as_percentage(scale);
303 // font uses old-style figure
309 else if (name == "amsmath" || name == "amssymb") {
314 else if (name == "esint") {
319 else if (name == "babel" && !opts.empty()) {
320 // check if more than one option was used - used later for inputenc
321 // in case inputenc is parsed before babel, set the encoding to auto
322 if (options.begin() != options.end() - 1) {
323 one_language = false;
324 h_inputencoding = "auto";
326 // only set the document language when there was not already one set
327 // via the documentclass options
328 // babel takes the the last language given in the documentclass options
329 // as document language. If there is no such language option, the last
330 // option of its \usepackage call is used.
331 if (documentclass_language == false) {
332 handle_opt(options, known_languages, h_language);
333 delete_opt(options, known_languages);
334 if (is_known(h_language, known_french_languages))
335 h_language = "french";
336 else if (is_known(h_language, known_german_languages))
337 h_language = "german";
338 else if (is_known(h_language, known_ngerman_languages))
339 h_language = "ngerman";
340 else if (is_known(h_language, known_russian_languages))
341 h_language = "russian";
342 else if (is_known(h_language, known_ukrainian_languages))
343 h_language = "ukrainian";
344 h_quotes_language = h_language;
348 else if (name == "fontenc")
349 p.skip_spaces(); // ignore this
351 else if (name == "inputenc") {
352 // only set when there is not more than one inputenc
353 // option therefore check for the "," character also
354 // only set when there is not more then one babel
356 if (opts.find(",") == string::npos && one_language == true) {
358 //change ascii to auto to be in the unicode range, see
359 //http://bugzilla.lyx.org/show_bug.cgi?id=4719
360 h_inputencoding = "auto";
361 else if (!opts.empty())
362 h_inputencoding = opts;
364 if (!options.empty())
365 p.setEncoding(options.back());
370 else if (name == "makeidx")
371 p.skip_spaces(); // ignore this
373 else if (name == "prettyref")
374 p.skip_spaces(); // ignore this
376 else if (name == "varioref")
377 p.skip_spaces(); // ignore this
379 else if (name == "verbatim")
380 p.skip_spaces(); // ignore this
382 else if (name == "url")
383 p.skip_spaces(); // ignore this
385 else if (name == "color") {
386 // with the following command this package is only loaded when needed for
387 // undefined colors, since we only support the predefined colors
388 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
392 else if (name == "graphicx")
393 p.skip_spaces(); // ignore this
395 else if (name == "setspace")
396 p.skip_spaces(); // ignore this
398 else if (name == "geometry")
399 p.skip_spaces(); // Ignore this, the geometry settings are made by the \geometry
400 // command. This command is handled below.
402 else if (is_known(name, known_languages)) {
403 if (is_known(name, known_french_languages))
404 h_language = "french";
405 else if (is_known(name, known_german_languages))
406 h_language = "german";
407 else if (is_known(name, known_ngerman_languages))
408 h_language = "ngerman";
409 else if (is_known(name, known_russian_languages))
410 h_language = "russian";
411 else if (is_known(name, known_ukrainian_languages))
412 h_language = "ukrainian";
415 h_quotes_language = h_language;
419 else if (name == "natbib") {
420 h_cite_engine = "natbib_authoryear";
421 vector<string>::iterator it =
422 find(options.begin(), options.end(), "authoryear");
423 if (it != options.end())
426 it = find(options.begin(), options.end(), "numbers");
427 if (it != options.end()) {
428 h_cite_engine = "natbib_numerical";
435 else if (name == "jurabib") {
436 h_cite_engine = "jurabib";
440 else if (!in_lyx_preamble) {
442 h_preamble << "\\usepackage{" << name << "}";
444 h_preamble << "\\usepackage[" << opts << "]{"
450 // We need to do something with the options...
451 if (!options.empty())
452 cerr << "Ignoring options '" << join(options, ",")
453 << "' of package " << name << '.' << endl;
458 void end_preamble(ostream & os, TextClass const & /*textclass*/)
460 os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
461 << "\\lyxformat 256\n"
462 << "\\begin_document\n"
463 << "\\begin_header\n"
464 << "\\textclass " << h_textclass << "\n";
465 if (!h_preamble.str().empty())
466 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
467 if (!h_options.empty())
468 os << "\\options " << h_options << "\n";
469 os << "\\language " << h_language << "\n"
470 << "\\inputencoding " << h_inputencoding << "\n"
471 << "\\font_roman " << h_font_roman << "\n"
472 << "\\font_sans " << h_font_sans << "\n"
473 << "\\font_typewriter " << h_font_typewriter << "\n"
474 << "\\font_default_family " << h_font_default_family << "\n"
475 << "\\font_sc " << h_font_sc << "\n"
476 << "\\font_osf " << h_font_osf << "\n"
477 << "\\font_sf_scale " << h_font_sf_scale << "\n"
478 << "\\font_tt_scale " << h_font_tt_scale << "\n"
479 << "\\graphics " << h_graphics << "\n"
480 << "\\paperfontsize " << h_paperfontsize << "\n"
481 << "\\spacing " << h_spacing << "\n"
482 << "\\papersize " << h_papersize << "\n"
483 << "\\use_geometry " << h_use_geometry << "\n"
484 << "\\use_amsmath " << h_use_amsmath << "\n"
485 << "\\use_esint " << h_use_esint << "\n"
486 << "\\cite_engine " << h_cite_engine << "\n"
487 << "\\use_bibtopic " << h_use_bibtopic << "\n"
488 << "\\paperorientation " << h_paperorientation << "\n"
490 << "\\secnumdepth " << h_secnumdepth << "\n"
491 << "\\tocdepth " << h_tocdepth << "\n"
492 << "\\paragraph_separation " << h_paragraph_separation << "\n"
493 << "\\defskip " << h_defskip << "\n"
494 << "\\quotes_language " << h_quotes_language << "\n"
495 << "\\papercolumns " << h_papercolumns << "\n"
496 << "\\papersides " << h_papersides << "\n"
497 << "\\paperpagestyle " << h_paperpagestyle << "\n"
498 << "\\tracking_changes " << h_tracking_changes << "\n"
499 << "\\output_changes " << h_output_changes << "\n"
500 << "\\end_header\n\n"
502 // clear preamble for subdocuments
506 } // anonymous namespace
508 void parse_preamble(Parser & p, ostream & os,
509 string const & forceclass, TeX2LyXDocClass & tc)
511 // initialize fixed types
512 special_columns['D'] = 3;
513 bool is_full_document = false;
514 bool is_lyx_file = false;
515 bool in_lyx_preamble = false;
517 // determine whether this is a full document or a fragment for inclusion
519 Token const & t = p.get_token();
521 if (t.cat() == catEscape && t.cs() == "documentclass") {
522 is_full_document = true;
528 while (is_full_document && p.good()) {
529 Token const & t = p.get_token();
532 cerr << "t: " << t << "\n";
538 if (!in_lyx_preamble &&
539 (t.cat() == catLetter ||
540 t.cat() == catSuper ||
542 t.cat() == catOther ||
543 t.cat() == catMath ||
544 t.cat() == catActive ||
545 t.cat() == catBegin ||
547 t.cat() == catAlign ||
548 t.cat() == catParameter))
549 h_preamble << t.character();
551 else if (!in_lyx_preamble &&
552 (t.cat() == catSpace || t.cat() == catNewline))
553 h_preamble << t.asInput();
555 else if (t.cat() == catComment) {
556 // regex to parse comments
557 static regex const islyxfile("%% LyX .* created this file");
558 static regex const usercommands("User specified LaTeX commands");
560 string const comment = t.asInput();
562 // magically switch encoding default if it looks like XeLaTeX
563 static string const magicXeLaTeX =
564 "% This document must be compiled with XeLaTeX ";
565 if (comment.size() > magicXeLaTeX.size()
566 && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
567 && h_inputencoding == "auto") {
568 cerr << "XeLaTeX comment found, switching to UTF8\n";
569 h_inputencoding = "utf8";
573 if (regex_search(comment, sub, islyxfile)) {
575 in_lyx_preamble = true;
576 } else if (is_lyx_file
577 && regex_search(comment, sub, usercommands))
578 in_lyx_preamble = false;
579 else if (!in_lyx_preamble)
580 h_preamble << t.asInput();
583 else if (t.cs() == "pagestyle")
584 h_paperpagestyle = p.verbatim_item();
586 else if (t.cs() == "makeatletter") {
587 if (!is_lyx_file || !in_lyx_preamble
588 || p.getCatCode('@') != catLetter)
589 h_preamble << "\\makeatletter";
590 p.setCatCode('@', catLetter);
593 else if (t.cs() == "makeatother") {
594 if (!is_lyx_file || !in_lyx_preamble
595 || p.getCatCode('@') != catOther)
596 h_preamble << "\\makeatother";
597 p.setCatCode('@', catOther);
600 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
601 || t.cs() == "providecommand") {
603 if (p.next_token().character() == '*') {
607 string const name = p.verbatim_item();
608 string const opt1 = p.getOpt();
609 string const opt2 = p.getFullOpt();
610 string const body = p.verbatim_item();
612 if (name == "\\rmdefault")
613 if (is_known(body, known_roman_fonts))
616 if (name == "\\sfdefault")
617 if (is_known(body, known_sans_fonts))
620 if (name == "\\ttdefault")
621 if (is_known(body, known_typewriter_fonts))
622 h_font_typewriter = body;
624 if (name == "\\familydefault") {
625 string family = body;
626 // remove leading "\"
627 h_font_default_family = family.erase(0,1);
629 // only non-lyxspecific stuff
630 if (!in_lyx_preamble) {
632 ss << '\\' << t.cs();
635 ss << '{' << name << '}' << opt1 << opt2
636 << '{' << body << "}";
637 h_preamble << ss.str();
639 // Add the command to the known commands
640 add_known_command(name, opt1, !opt2.empty());
642 ostream & out = in_preamble ? h_preamble : os;
643 out << "\\" << t.cs() << "{" << name << "}"
644 << opts << "{" << body << "}";
649 else if (t.cs() == "documentclass") {
650 vector<string>::iterator it;
651 vector<string> opts = split_options(p.getArg('[', ']'));
652 handle_opt(opts, known_fontsizes, h_paperfontsize);
653 delete_opt(opts, known_fontsizes);
654 // delete "pt" at the end
655 string::size_type i = h_paperfontsize.find("pt");
656 if (i != string::npos)
657 h_paperfontsize.erase(i);
658 // to avoid that the babel options overwrite the documentclass options
659 documentclass_language = false;
660 handle_opt(opts, known_languages, h_language);
661 delete_opt(opts, known_languages);
662 if (is_known(h_language, known_french_languages))
663 h_language = "french";
664 else if (is_known(h_language, known_german_languages))
665 h_language = "german";
666 else if (is_known(h_language, known_ngerman_languages))
667 h_language = "ngerman";
668 else if (is_known(h_language, known_russian_languages))
669 h_language = "russian";
670 else if (is_known(h_language, known_ukrainian_languages))
671 h_language = "ukrainian";
672 h_quotes_language = h_language;
674 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
675 h_paperorientation = "landscape";
679 if ((it = find(opts.begin(), opts.end(), "oneside"))
684 if ((it = find(opts.begin(), opts.end(), "twoside"))
690 if ((it = find(opts.begin(), opts.end(), "onecolumn"))
692 h_papercolumns = "1";
695 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
697 h_papercolumns = "2";
701 // some size options are know to any document classes, other sizes
702 // are handled by the \geometry command of the geometry package
703 handle_opt(opts, known_class_paper_sizes, h_papersize);
704 delete_opt(opts, known_class_paper_sizes);
705 // the remaining options
706 h_options = join(opts, ",");
707 h_textclass = p.getArg('{', '}');
710 else if (t.cs() == "usepackage") {
711 string const options = p.getArg('[', ']');
712 string const name = p.getArg('{', '}');
713 vector<string> vecnames;
714 split(name, vecnames, ',');
715 vector<string>::const_iterator it = vecnames.begin();
716 vector<string>::const_iterator end = vecnames.end();
717 for (; it != end; ++it)
718 handle_package(p, trim(*it), options,
722 else if (t.cs() == "inputencoding") {
723 string const encoding = p.getArg('{','}');
724 h_inputencoding = encoding;
725 p.setEncoding(encoding);
728 else if (t.cs() == "newenvironment") {
729 string const name = p.getArg('{', '}');
731 ss << "\\newenvironment{" << name << "}";
734 ss << '{' << p.verbatim_item() << '}';
735 ss << '{' << p.verbatim_item() << '}';
736 if (!in_lyx_preamble)
737 h_preamble << ss.str();
740 else if (t.cs() == "def") {
741 string name = p.get_token().cs();
742 while (p.next_token().cat() != catBegin)
743 name += p.get_token().asString();
744 if (!in_lyx_preamble)
745 h_preamble << "\\def\\" << name << '{'
746 << p.verbatim_item() << "}";
749 else if (t.cs() == "newcolumntype") {
750 string const name = p.getArg('{', '}');
753 string opts = p.getOpt();
755 istringstream is(string(opts, 1));
758 special_columns[name[0]] = nargs;
759 h_preamble << "\\newcolumntype{" << name << "}";
761 h_preamble << "[" << nargs << "]";
762 h_preamble << "{" << p.verbatim_item() << "}";
765 else if (t.cs() == "setcounter") {
766 string const name = p.getArg('{', '}');
767 string const content = p.getArg('{', '}');
768 if (name == "secnumdepth")
769 h_secnumdepth = content;
770 else if (name == "tocdepth")
771 h_tocdepth = content;
773 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
776 else if (t.cs() == "setlength") {
777 string const name = p.verbatim_item();
778 string const content = p.verbatim_item();
779 // the paragraphs are only not indented when \parindent is set to zero
780 if (name == "\\parindent" && content != "") {
781 if (content[0] == '0')
782 h_paragraph_separation = "skip";
783 } else if (name == "\\parskip") {
784 if (content == "\\smallskipamount")
785 h_defskip = "smallskip";
786 else if (content == "\\medskipamount")
787 h_defskip = "medskip";
788 else if (content == "\\bigskipamount")
789 h_defskip = "bigskip";
793 h_preamble << "\\setlength{" << name << "}{" << content << "}";
796 else if (t.cs() == "onehalfspacing")
797 h_spacing = "onehalf";
799 else if (t.cs() == "doublespacing")
800 h_spacing = "double";
802 else if (t.cs() == "setstretch")
803 h_spacing = "other " + p.verbatim_item();
805 else if (t.cs() == "begin") {
806 string const name = p.getArg('{', '}');
807 if (name == "document")
809 h_preamble << "\\begin{" << name << "}";
812 else if (t.cs() == "geometry") {
813 h_use_geometry = "true";
814 vector<string> opts = split_options(p.getArg('{', '}'));
815 vector<string>::iterator it;
817 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
818 h_paperorientation = "landscape";
822 handle_opt(opts, known_paper_sizes, h_papersize);
823 delete_opt(opts, known_paper_sizes);
825 char const * const * margin = known_paper_margins;
827 for (; *margin; ++margin) {
829 // search for the "=" in e.g. "lmargin=2cm" to get the value
830 for(size_t i = 0; i != opts.size(); i++) {
831 if (opts.at(i).find(*margin) != string::npos) {
832 string::size_type pos = opts.at(i).find("=");
833 string value = opts.at(i).substr(pos + 1);
834 string name = known_coded_paper_margins[k];
835 h_margins += "\\" + name + " " + value + "\n";
841 else if (t.cs() == "jurabibsetup") {
842 vector<string> jurabibsetup =
843 split_options(p.getArg('{', '}'));
844 // add jurabibsetup to the jurabib package options
845 add_package("jurabib", jurabibsetup);
846 if (!jurabibsetup.empty()) {
847 h_preamble << "\\jurabibsetup{"
848 << join(jurabibsetup, ",") << '}';
852 else if (!t.cs().empty() && !in_lyx_preamble)
853 h_preamble << '\\' << t.cs();
857 // Force textclass if the user wanted it
858 if (!forceclass.empty())
859 h_textclass = forceclass;
860 if (noweb_mode && !prefixIs(h_textclass, "literate-"))
861 h_textclass.insert(0, "literate-");
862 FileName layoutfilename = libFileSearch("layouts", h_textclass, "layout");
863 if (layoutfilename.empty()) {
864 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
867 tc.read(layoutfilename);
868 if (h_papersides.empty()) {
871 h_papersides = ss.str();
873 end_preamble(os, tc);