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 = "0";
124 string h_cite_engine = "basic";
125 string h_use_bibtopic = "false";
126 string h_paperorientation = "portrait";
127 string h_secnumdepth = "3";
128 string h_tocdepth = "3";
129 string h_paragraph_separation = "indent";
130 string h_defskip = "medskip";
131 string h_quotes_language = "english";
132 string h_papercolumns = "1";
133 string h_papersides = string();
134 string h_paperpagestyle = "default";
135 string h_tracking_changes = "false";
136 string h_output_changes = "false";
137 string h_margins = "";
140 void handle_opt(vector<string> & opts, char const * const * what, string & target)
145 // the last language option is the document language (for babel and LyX)
146 // the last size option is the document font size
147 vector<string>::iterator it;
148 vector<string>::iterator position = opts.begin();
149 for (; *what; ++what) {
150 it = find(opts.begin(), opts.end(), *what);
151 if (it != opts.end()) {
152 documentclass_language = true;
153 if (it >= position) {
162 void delete_opt(vector<string> & opts, char const * const * what)
167 // remove found options from the list
168 // do this after handle_opt to avoid potential memory leaks and to be able
169 // to find in every case the last language option
170 vector<string>::iterator it;
171 for (; *what; ++what) {
172 it = find(opts.begin(), opts.end(), *what);
173 if (it != opts.end())
180 * Split a package options string (keyval format) into a vector.
182 * authorformat=smallcaps,
184 * titleformat=colonsep,
185 * bibformat={tabular,ibidem,numbered}
187 vector<string> split_options(string const & input)
189 vector<string> options;
193 Token const & t = p.get_token();
194 if (t.asInput() == ",") {
195 options.push_back(trim(option));
197 } else if (t.asInput() == "=") {
200 if (p.next_token().asInput() == "{")
201 option += '{' + p.getArg('{', '}') + '}';
202 } else if (t.cat() != catSpace)
203 option += t.asInput();
207 options.push_back(trim(option));
214 * Add package \p name with options \p options to used_packages.
215 * Remove options from \p options that we don't want to output.
217 void add_package(string const & name, vector<string> & options)
219 // every package inherits the global options
220 if (used_packages.find(name) == used_packages.end())
221 used_packages[name] = split_options(h_options);
223 vector<string> & v = used_packages[name];
224 v.insert(v.end(), options.begin(), options.end());
225 if (name == "jurabib") {
226 // Don't output the order argument (see the cite command
227 // handling code in text.cpp).
228 vector<string>::iterator end =
229 remove(options.begin(), options.end(), "natbiborder");
230 end = remove(options.begin(), end, "jurabiborder");
231 options.erase(end, options.end());
236 // Given is a string like "scaled=0.9", return 0.9 * 100
237 string const scale_as_percentage(string const & scale)
239 string::size_type pos = scale.find('=');
240 if (pos != string::npos) {
241 string value = scale.substr(pos + 1);
243 return convert<string>(100 * convert<double>(value));
245 // If the input string didn't match our expectations.
246 // return the default value "100"
251 void handle_package(Parser &p, string const & name, string const & opts,
252 bool in_lyx_preamble)
254 vector<string> options = split_options(opts);
255 add_package(name, options);
259 if (is_known(name, known_roman_fonts))
262 if (name == "fourier") {
263 h_font_roman = "utopia";
264 // when font uses real small capitals
265 if (opts == "expert")
268 if (name == "mathpazo")
269 h_font_roman = "palatino";
271 if (name == "mathptmx")
272 h_font_roman = "times";
275 if (is_known(name, known_sans_fonts)) {
279 h_font_sf_scale = scale_as_percentage(scale);
283 if (is_known(name, known_typewriter_fonts)) {
284 h_font_typewriter = name;
287 h_font_tt_scale = scale_as_percentage(scale);
290 // font uses old-style figure
294 else if (name == "amsmath" || name == "amssymb")
297 else if (name == "babel" && !opts.empty()) {
298 // check if more than one option was used - used later for inputenc
299 // in case inputenc is parsed before babel, set the encoding to auto
300 if (options.begin() != options.end() - 1) {
301 one_language = false;
302 h_inputencoding = "auto";
304 // only set the document language when there was not already one set
305 // via the documentclass options
306 // babel takes the the last language given in the documentclass options
307 // as document language. If there is no such language option, the last
308 // option of its \usepackage call is used.
309 if (documentclass_language == false) {
310 handle_opt(options, known_languages, h_language);
311 delete_opt(options, known_languages);
312 if (is_known(h_language, known_french_languages))
313 h_language = "french";
314 else if (is_known(h_language, known_german_languages))
315 h_language = "german";
316 else if (is_known(h_language, known_ngerman_languages))
317 h_language = "ngerman";
318 else if (is_known(h_language, known_russian_languages))
319 h_language = "russian";
320 else if (is_known(h_language, known_ukrainian_languages))
321 h_language = "ukrainian";
322 h_quotes_language = h_language;
325 else if (name == "fontenc")
328 else if (name == "inputenc") {
329 // only set when there is not more than one inputenc
330 // option therefore check for the "," character also
331 // only set when there is not more then one babel
333 if (opts.find(",") == string::npos && one_language == true) {
335 //change ascii to auto to be in the unicode range, see
336 //http://bugzilla.lyx.org/show_bug.cgi?id=4719
337 h_inputencoding = "auto";
338 else if (!opts.empty())
339 h_inputencoding = opts;
341 if (!options.empty())
342 p.setEncoding(options.back());
346 else if (name == "makeidx")
349 else if (name == "verbatim")
352 else if (name == "color")
353 // with the following command this package is only loaded when needed for
354 // undefined colors, since we only support the predefined colors
355 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
357 else if (name == "graphicx")
360 else if (name == "setspace")
363 else if (name == "geometry")
364 ; // Ignore this, the geometry settings are made by the \geometry
365 // command. This command is handled below.
367 else if (is_known(name, known_languages)) {
368 if (is_known(name, known_french_languages))
369 h_language = "french";
370 else if (is_known(name, known_german_languages))
371 h_language = "german";
372 else if (is_known(name, known_ngerman_languages))
373 h_language = "ngerman";
374 else if (is_known(name, known_russian_languages))
375 h_language = "russian";
376 else if (is_known(name, known_ukrainian_languages))
377 h_language = "ukrainian";
380 h_quotes_language = h_language;
382 else if (name == "natbib") {
383 h_cite_engine = "natbib_authoryear";
384 vector<string>::iterator it =
385 find(options.begin(), options.end(), "authoryear");
386 if (it != options.end())
389 it = find(options.begin(), options.end(), "numbers");
390 if (it != options.end()) {
391 h_cite_engine = "natbib_numerical";
396 else if (name == "jurabib")
397 h_cite_engine = "jurabib";
398 else if (!in_lyx_preamble) {
400 h_preamble << "\\usepackage{" << name << "}";
402 h_preamble << "\\usepackage[" << opts << "]{"
408 // We need to do something with the options...
409 if (!options.empty())
410 cerr << "Ignoring options '" << join(options, ",")
411 << "' of package " << name << '.' << endl;
416 void end_preamble(ostream & os, TextClass const & /*textclass*/)
418 os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
419 << "\\lyxformat 249\n"
420 << "\\begin_document\n"
421 << "\\begin_header\n"
422 << "\\textclass " << h_textclass << "\n";
423 if (!h_preamble.str().empty())
424 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
425 if (!h_options.empty())
426 os << "\\options " << h_options << "\n";
427 os << "\\language " << h_language << "\n"
428 << "\\inputencoding " << h_inputencoding << "\n"
429 << "\\font_roman " << h_font_roman << "\n"
430 << "\\font_sans " << h_font_sans << "\n"
431 << "\\font_typewriter " << h_font_typewriter << "\n"
432 << "\\font_default_family " << h_font_default_family << "\n"
433 << "\\font_sc " << h_font_sc << "\n"
434 << "\\font_osf " << h_font_osf << "\n"
435 << "\\font_sf_scale " << h_font_sf_scale << "\n"
436 << "\\font_tt_scale " << h_font_tt_scale << "\n"
437 << "\\graphics " << h_graphics << "\n"
438 << "\\paperfontsize " << h_paperfontsize << "\n"
439 << "\\spacing " << h_spacing << "\n"
440 << "\\papersize " << h_papersize << "\n"
441 << "\\use_geometry " << h_use_geometry << "\n"
442 << "\\use_amsmath " << h_use_amsmath << "\n"
443 << "\\cite_engine " << h_cite_engine << "\n"
444 << "\\use_bibtopic " << h_use_bibtopic << "\n"
445 << "\\paperorientation " << h_paperorientation << "\n"
447 << "\\secnumdepth " << h_secnumdepth << "\n"
448 << "\\tocdepth " << h_tocdepth << "\n"
449 << "\\paragraph_separation " << h_paragraph_separation << "\n"
450 << "\\defskip " << h_defskip << "\n"
451 << "\\quotes_language " << h_quotes_language << "\n"
452 << "\\papercolumns " << h_papercolumns << "\n"
453 << "\\papersides " << h_papersides << "\n"
454 << "\\paperpagestyle " << h_paperpagestyle << "\n"
455 << "\\tracking_changes " << h_tracking_changes << "\n"
456 << "\\output_changes " << h_output_changes << "\n"
457 << "\\end_header\n\n"
459 // clear preamble for subdocuments
463 } // anonymous namespace
465 void parse_preamble(Parser & p, ostream & os,
466 string const & forceclass, TeX2LyXDocClass & tc)
468 // initialize fixed types
469 special_columns['D'] = 3;
470 bool is_full_document = false;
471 bool is_lyx_file = false;
472 bool in_lyx_preamble = false;
474 // determine whether this is a full document or a fragment for inclusion
476 Token const & t = p.get_token();
478 if (t.cat() == catEscape && t.cs() == "documentclass") {
479 is_full_document = true;
485 while (is_full_document && p.good()) {
486 Token const & t = p.get_token();
489 cerr << "t: " << t << "\n";
495 if (!in_lyx_preamble &&
496 (t.cat() == catLetter ||
497 t.cat() == catSuper ||
499 t.cat() == catOther ||
500 t.cat() == catMath ||
501 t.cat() == catActive ||
502 t.cat() == catBegin ||
504 t.cat() == catAlign ||
505 t.cat() == catParameter))
506 h_preamble << t.character();
508 else if (!in_lyx_preamble &&
509 (t.cat() == catSpace || t.cat() == catNewline))
510 h_preamble << t.asInput();
512 else if (t.cat() == catComment) {
513 // regex to parse comments
514 static regex const islyxfile("%% LyX .* created this file");
515 static regex const usercommands("User specified LaTeX commands");
517 string const comment = t.asInput();
519 // magically switch encoding default if it looks like XeLaTeX
520 static string const magicXeLaTeX =
521 "% This document must be compiled with XeLaTeX ";
522 if (comment.size() > magicXeLaTeX.size()
523 && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
524 && h_inputencoding == "auto") {
525 cerr << "XeLaTeX comment found, switching to UTF8\n";
526 h_inputencoding = "utf8";
530 if (regex_search(comment, sub, islyxfile)) {
532 in_lyx_preamble = true;
533 } else if (is_lyx_file
534 && regex_search(comment, sub, usercommands))
535 in_lyx_preamble = false;
536 else if (!in_lyx_preamble)
537 h_preamble << t.asInput();
540 else if (t.cs() == "pagestyle")
541 h_paperpagestyle = p.verbatim_item();
543 else if (t.cs() == "makeatletter") {
544 if (!is_lyx_file || !in_lyx_preamble
545 || p.getCatCode('@') != catLetter)
546 h_preamble << "\\makeatletter";
547 p.setCatCode('@', catLetter);
550 else if (t.cs() == "makeatother") {
551 if (!is_lyx_file || !in_lyx_preamble
552 || p.getCatCode('@') != catOther)
553 h_preamble << "\\makeatother";
554 p.setCatCode('@', catOther);
557 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
558 || t.cs() == "providecommand") {
560 if (p.next_token().character() == '*') {
564 string const name = p.verbatim_item();
565 string const opt1 = p.getOpt();
566 string const opt2 = p.getFullOpt();
567 string const body = p.verbatim_item();
569 if (name == "\\rmdefault")
570 if (is_known(body, known_roman_fonts))
573 if (name == "\\sfdefault")
574 if (is_known(body, known_sans_fonts))
577 if (name == "\\ttdefault")
578 if (is_known(body, known_typewriter_fonts))
579 h_font_typewriter = body;
581 if (name == "\\familydefault") {
582 string family = body;
583 // remove leading "\"
584 h_font_default_family = family.erase(0,1);
586 // only non-lyxspecific stuff
587 if (!in_lyx_preamble) {
589 ss << '\\' << t.cs();
592 ss << '{' << name << '}' << opt1 << opt2
593 << '{' << body << "}";
594 h_preamble << ss.str();
596 // Add the command to the known commands
597 add_known_command(name, opt1, !opt2.empty());
599 ostream & out = in_preamble ? h_preamble : os;
600 out << "\\" << t.cs() << "{" << name << "}"
601 << opts << "{" << body << "}";
606 else if (t.cs() == "documentclass") {
607 vector<string>::iterator it;
608 vector<string> opts = split_options(p.getArg('[', ']'));
609 handle_opt(opts, known_fontsizes, h_paperfontsize);
610 delete_opt(opts, known_fontsizes);
611 // delete "pt" at the end
612 string::size_type i = h_paperfontsize.find("pt");
613 if (i != string::npos)
614 h_paperfontsize.erase(i);
615 // to avoid that the babel options overwrite the documentclass options
616 documentclass_language = false;
617 handle_opt(opts, known_languages, h_language);
618 delete_opt(opts, known_languages);
619 if (is_known(h_language, known_french_languages))
620 h_language = "french";
621 else if (is_known(h_language, known_german_languages))
622 h_language = "german";
623 else if (is_known(h_language, known_ngerman_languages))
624 h_language = "ngerman";
625 else if (is_known(h_language, known_russian_languages))
626 h_language = "russian";
627 else if (is_known(h_language, known_ukrainian_languages))
628 h_language = "ukrainian";
629 h_quotes_language = h_language;
631 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
632 h_paperorientation = "landscape";
636 if ((it = find(opts.begin(), opts.end(), "oneside"))
641 if ((it = find(opts.begin(), opts.end(), "twoside"))
647 if ((it = find(opts.begin(), opts.end(), "onecolumn"))
649 h_papercolumns = "1";
652 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
654 h_papercolumns = "2";
658 // some size options are know to any document classes, other sizes
659 // are handled by the \geometry command of the geometry package
660 handle_opt(opts, known_class_paper_sizes, h_papersize);
661 delete_opt(opts, known_class_paper_sizes);
662 // the remaining options
663 h_options = join(opts, ",");
664 h_textclass = p.getArg('{', '}');
667 else if (t.cs() == "usepackage") {
668 string const options = p.getArg('[', ']');
669 string const name = p.getArg('{', '}');
670 vector<string> vecnames;
671 split(name, vecnames, ',');
672 vector<string>::const_iterator it = vecnames.begin();
673 vector<string>::const_iterator end = vecnames.end();
674 for (; it != end; ++it)
675 handle_package(p, trim(*it), options,
679 else if (t.cs() == "inputencoding") {
680 string const encoding = p.getArg('{','}');
681 h_inputencoding = encoding;
682 p.setEncoding(encoding);
685 else if (t.cs() == "newenvironment") {
686 string const name = p.getArg('{', '}');
688 ss << "\\newenvironment{" << name << "}";
691 ss << '{' << p.verbatim_item() << '}';
692 ss << '{' << p.verbatim_item() << '}';
693 if (!in_lyx_preamble)
694 h_preamble << ss.str();
697 else if (t.cs() == "def") {
698 string name = p.get_token().cs();
699 while (p.next_token().cat() != catBegin)
700 name += p.get_token().asString();
701 if (!in_lyx_preamble)
702 h_preamble << "\\def\\" << name << '{'
703 << p.verbatim_item() << "}";
706 else if (t.cs() == "newcolumntype") {
707 string const name = p.getArg('{', '}');
710 string opts = p.getOpt();
712 istringstream is(string(opts, 1));
715 special_columns[name[0]] = nargs;
716 h_preamble << "\\newcolumntype{" << name << "}";
718 h_preamble << "[" << nargs << "]";
719 h_preamble << "{" << p.verbatim_item() << "}";
722 else if (t.cs() == "setcounter") {
723 string const name = p.getArg('{', '}');
724 string const content = p.getArg('{', '}');
725 if (name == "secnumdepth")
726 h_secnumdepth = content;
727 else if (name == "tocdepth")
728 h_tocdepth = content;
730 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
733 else if (t.cs() == "setlength") {
734 string const name = p.verbatim_item();
735 string const content = p.verbatim_item();
736 // the paragraphs are only not indented when \parindent is set to zero
737 if (name == "\\parindent" && content != "") {
738 if (content[0] == '0')
739 h_paragraph_separation = "skip";
740 } else if (name == "\\parskip") {
741 if (content == "\\smallskipamount")
742 h_defskip = "smallskip";
743 else if (content == "\\medskipamount")
744 h_defskip = "medskip";
745 else if (content == "\\bigskipamount")
746 h_defskip = "bigskip";
750 h_preamble << "\\setlength{" << name << "}{" << content << "}";
753 else if (t.cs() == "onehalfspacing")
754 h_spacing = "onehalf";
756 else if (t.cs() == "doublespacing")
757 h_spacing = "double";
759 else if (t.cs() == "setstretch")
760 h_spacing = "other " + p.verbatim_item();
762 else if (t.cs() == "begin") {
763 string const name = p.getArg('{', '}');
764 if (name == "document")
766 h_preamble << "\\begin{" << name << "}";
769 else if (t.cs() == "geometry") {
770 h_use_geometry = "true";
771 vector<string> opts = split_options(p.getArg('{', '}'));
772 vector<string>::iterator it;
774 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
775 h_paperorientation = "landscape";
779 handle_opt(opts, known_paper_sizes, h_papersize);
780 delete_opt(opts, known_paper_sizes);
782 char const * const * margin = known_paper_margins;
784 for (; *margin; ++margin) {
786 // search for the "=" in e.g. "lmargin=2cm" to get the value
787 for(size_t i = 0; i != opts.size(); i++) {
788 if (opts.at(i).find(*margin) != string::npos) {
789 string::size_type pos = opts.at(i).find("=");
790 string value = opts.at(i).substr(pos + 1);
791 string name = known_coded_paper_margins[k];
792 h_margins += "\\" + name + " " + value + "\n";
798 else if (t.cs() == "jurabibsetup") {
799 vector<string> jurabibsetup =
800 split_options(p.getArg('{', '}'));
801 // add jurabibsetup to the jurabib package options
802 add_package("jurabib", jurabibsetup);
803 if (!jurabibsetup.empty()) {
804 h_preamble << "\\jurabibsetup{"
805 << join(jurabibsetup, ",") << '}';
809 else if (!t.cs().empty() && !in_lyx_preamble)
810 h_preamble << '\\' << t.cs();
814 // Force textclass if the user wanted it
815 if (!forceclass.empty())
816 h_textclass = forceclass;
817 if (noweb_mode && !prefixIs(h_textclass, "literate-"))
818 h_textclass.insert(0, "literate-");
819 FileName layoutfilename = libFileSearch("layouts", h_textclass, "layout");
820 if (layoutfilename.empty()) {
821 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
824 tc.read(layoutfilename);
825 if (h_papersides.empty()) {
828 h_papersides = ss.str();
830 end_preamble(os, tc);