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"
36 using namespace lyx::support;
40 // special columntypes
41 extern map<char, int> special_columns;
43 map<string, vector<string> > used_packages;
45 // needed to handle encodings with babel
46 bool one_language = true;
48 // to avoid that the babel options overwrite the documentclass options
49 bool documentclass_language;
53 const char * const known_languages[] = { "afrikaans", "american", "arabic",
54 "austrian", "bahasa", "basque", "belarusian", "brazil", "breton", "british",
55 "bulgarian", "canadian", "canadien", "catalan", "croatian", "czech", "danish",
56 "dutch", "english", "esperanto", "estonian", "finnish", "francais", "french",
57 "frenchb", "frenchle", "frenchpro", "galician", "german", "germanb", "greek",
58 "hebrew", "icelandic", "irish", "italian", "lsorbian", "magyar", "naustrian",
59 "ngerman", "ngermanb", "norsk", "nynorsk", "polish", "portuges", "romanian",
60 "russian", "russianb", "scottish", "serbian", "slovak", "slovene", "spanish",
61 "swedish", "thai", "turkish", "ukraineb", "ukrainian", "usorbian", "welsh", 0};
63 //note this when updating to lyxformat 305:
64 //bahasai, indonesian, and indon = equal to bahasa
65 //malay, and meyalu = equal to bahasam
67 const char * const known_french_languages[] = {"french", "frenchb", "francais",
68 "frenchle", "frenchpro", 0};
69 const char * const known_german_languages[] = {"german", "germanb", 0};
70 const char * const known_ngerman_languages[] = {"ngerman", "ngermanb", 0};
71 const char * const known_russian_languages[] = {"russian", "russianb", 0};
72 const char * const known_ukrainian_languages[] = {"ukrainian", "ukraineb", 0};
74 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
76 const char * const known_roman_fonts[] = { "ae", "bookman", "charter",
77 "cmr", "fourier", "lmodern", "mathpazo", "mathptmx", "newcent", 0};
79 const char * const known_sans_fonts[] = { "avant", "berasans", "cmbr", "cmss",
82 const char * const known_typewriter_fonts[] = { "beramono", "cmtl", "cmtt",
83 "courier", "lmtt", "luximono", "fourier", "lmodern", "mathpazo", "mathptmx",
86 const char * const known_paper_sizes[] = { "a3paper", "b3paper", "a4paper",
87 "b4paper", "a5paper", "b5paper", "executivepaper", "legalpaper",
90 const char * const known_class_paper_sizes[] = { "a4paper", "a5paper",
91 "executivepaper", "legalpaper", "letterpaper", 0};
93 const char * const known_paper_margins[] = { "lmargin", "tmargin", "rmargin",
94 "bmargin", "headheight", "headsep", "footskip", "columnsep", 0};
96 const char * const known_coded_paper_margins[] = { "leftmargin", "topmargin",
97 "rightmargin", "bottommargin", "headheight", "headsep", "footskip",
101 ostringstream h_preamble;
102 string h_textclass = "article";
103 string h_options = string();
104 string h_language = "english";
105 string h_inputencoding = "auto";
106 string h_font_roman = "default";
107 string h_font_sans = "default";
108 string h_font_typewriter = "default";
109 string h_font_default_family = "default";
110 string h_font_sc = "false";
111 string h_font_osf = "false";
112 string h_font_sf_scale = "100";
113 string h_font_tt_scale = "100";
114 string h_graphics = "default";
115 string h_paperfontsize = "default";
116 string h_spacing = "single";
117 string h_papersize = "default";
118 string h_use_geometry = "false";
119 string h_use_amsmath = "0";
120 string h_cite_engine = "basic";
121 string h_use_bibtopic = "false";
122 string h_paperorientation = "portrait";
123 string h_secnumdepth = "3";
124 string h_tocdepth = "3";
125 string h_paragraph_separation = "indent";
126 string h_defskip = "medskip";
127 string h_quotes_language = "english";
128 string h_papercolumns = "1";
129 string h_papersides = string();
130 string h_paperpagestyle = "default";
131 string h_tracking_changes = "false";
132 string h_output_changes = "false";
133 string h_margins = "";
136 void handle_opt(vector<string> & opts, char const * const * what, string & target)
141 // the last language option is the document language (for babel and LyX)
142 // the last size option is the document font size
143 vector<string>::iterator it;
144 vector<string>::iterator position = opts.begin();
145 for (; *what; ++what) {
146 it = find(opts.begin(), opts.end(), *what);
147 if (it != opts.end()) {
148 documentclass_language = true;
149 if (it >= position) {
158 void delete_opt(vector<string> & opts, char const * const * what)
163 // remove found options from the list
164 // do this after handle_opt to avoid potential memory leaks and to be able
165 // to find in every case the last language option
166 vector<string>::iterator it;
167 for (; *what; ++what) {
168 it = find(opts.begin(), opts.end(), *what);
169 if (it != opts.end())
176 * Split a package options string (keyval format) into a vector.
178 * authorformat=smallcaps,
180 * titleformat=colonsep,
181 * bibformat={tabular,ibidem,numbered}
183 vector<string> split_options(string const & input)
185 vector<string> options;
189 Token const & t = p.get_token();
190 if (t.asInput() == ",") {
191 options.push_back(trim(option));
193 } else if (t.asInput() == "=") {
196 if (p.next_token().asInput() == "{")
197 option += '{' + p.getArg('{', '}') + '}';
198 } else if (t.cat() != catSpace)
199 option += t.asInput();
203 options.push_back(trim(option));
210 * Add package \p name with options \p options to used_packages.
211 * Remove options from \p options that we don't want to output.
213 void add_package(string const & name, vector<string> & options)
215 // every package inherits the global options
216 if (used_packages.find(name) == used_packages.end())
217 used_packages[name] = split_options(h_options);
219 vector<string> & v = used_packages[name];
220 v.insert(v.end(), options.begin(), options.end());
221 if (name == "jurabib") {
222 // Don't output the order argument (see the cite command
223 // handling code in text.cpp).
224 vector<string>::iterator end =
225 remove(options.begin(), options.end(), "natbiborder");
226 end = remove(options.begin(), end, "jurabiborder");
227 options.erase(end, options.end());
232 // Given is a string like "scaled=0.9", return 0.9 * 100
233 string const scale_as_percentage(string const & scale)
235 string::size_type pos = scale.find('=');
236 if (pos != string::npos) {
237 string value = scale.substr(pos + 1);
239 return convert<string>(100 * convert<double>(value));
241 // If the input string didn't match our expectations.
242 // return the default value "100"
247 void handle_package(string const & name, string const & opts)
249 vector<string> options = split_options(opts);
250 add_package(name, options);
254 if (is_known(name, known_roman_fonts))
257 if (name == "fourier") {
258 h_font_roman = "utopia";
259 // when font uses real small capitals
260 if (opts == "expert")
263 if (name == "mathpazo")
264 h_font_roman = "palatino";
266 if (name == "mathptmx")
267 h_font_roman = "times";
270 if (is_known(name, known_sans_fonts)) {
274 h_font_sf_scale = scale_as_percentage(scale);
278 if (is_known(name, known_typewriter_fonts)) {
279 h_font_typewriter = name;
282 h_font_tt_scale = scale_as_percentage(scale);
285 // font uses old-style figure
289 else if (name == "amsmath" || name == "amssymb")
292 else if (name == "babel" && !opts.empty()) {
293 // check if more than one option was used - used later for inputenc
294 // in case inputenc is parsed before babel, set the encoding to auto
295 if (options.begin() != options.end() - 1) {
296 one_language = false;
297 h_inputencoding = "auto";
299 // only set the document language when there was not already one set
300 // via the documentclass options
301 // babel takes the the last language given in the documentclass options
302 // as document language. If there is no such language option, the last
303 // option of its \usepackage call is used.
304 if (documentclass_language == false) {
305 handle_opt(options, known_languages, h_language);
306 delete_opt(options, known_languages);
307 if (is_known(h_language, known_french_languages))
308 h_language = "french";
309 else if (is_known(h_language, known_german_languages))
310 h_language = "german";
311 else if (is_known(h_language, known_ngerman_languages))
312 h_language = "ngerman";
313 else if (is_known(h_language, known_russian_languages))
314 h_language = "russian";
315 else if (is_known(h_language, known_ukrainian_languages))
316 h_language = "ukrainian";
317 h_quotes_language = h_language;
320 else if (name == "fontenc")
323 else if (name == "inputenc") {
324 // only set when there is not more than one inputenc option
325 // therefore check for the "," character
326 // also only set when there is not more then one babel language option
327 if (opts.find(",") == string::npos && one_language == true)
329 //change ascii to auto to be in the unicode range, see
330 //http://bugzilla.lyx.org/show_bug.cgi?id=4719
331 h_inputencoding = "auto";
333 h_inputencoding = opts;
336 else if (name == "makeidx")
339 else if (name == "verbatim")
342 else if (name == "color")
343 // with the following command this package is only loaded when needed for
344 // undefined colors, since we only support the predefined colors
345 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
347 else if (name == "graphicx")
350 else if (name == "setspace")
353 else if (name == "geometry")
354 ; // Ignore this, the geometry settings are made by the \geometry
355 // command. This command is handled below.
357 else if (is_known(name, known_languages)) {
358 if (is_known(name, known_french_languages))
359 h_language = "french";
360 else if (is_known(name, known_german_languages))
361 h_language = "german";
362 else if (is_known(name, known_ngerman_languages))
363 h_language = "ngerman";
364 else if (is_known(name, known_russian_languages))
365 h_language = "russian";
366 else if (is_known(name, known_ukrainian_languages))
367 h_language = "ukrainian";
370 h_quotes_language = h_language;
372 else if (name == "natbib") {
373 h_cite_engine = "natbib_authoryear";
374 vector<string>::iterator it =
375 find(options.begin(), options.end(), "authoryear");
376 if (it != options.end())
379 it = find(options.begin(), options.end(), "numbers");
380 if (it != options.end()) {
381 h_cite_engine = "natbib_numerical";
386 else if (name == "jurabib")
387 h_cite_engine = "jurabib";
389 else if (options.empty())
390 h_preamble << "\\usepackage{" << name << "}\n";
392 h_preamble << "\\usepackage[" << opts << "]{" << name << "}\n";
395 // We need to do something with the options...
396 if (!options.empty())
397 cerr << "Ignoring options '" << join(options, ",")
398 << "' of package " << name << '.' << endl;
403 void end_preamble(ostream & os, TextClass const & /*textclass*/)
405 os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
406 << "\\lyxformat 247\n"
407 << "\\begin_document\n"
408 << "\\begin_header\n"
409 << "\\textclass " << h_textclass << "\n";
410 if (!h_preamble.str().empty())
411 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
412 if (!h_options.empty())
413 os << "\\options " << h_options << "\n";
414 os << "\\language " << h_language << "\n"
415 << "\\inputencoding " << h_inputencoding << "\n"
416 << "\\font_roman " << h_font_roman << "\n"
417 << "\\font_sans " << h_font_sans << "\n"
418 << "\\font_typewriter " << h_font_typewriter << "\n"
419 << "\\font_default_family " << h_font_default_family << "\n"
420 << "\\font_sc " << h_font_sc << "\n"
421 << "\\font_osf " << h_font_osf << "\n"
422 << "\\font_sf_scale " << h_font_sf_scale << "\n"
423 << "\\font_tt_scale " << h_font_tt_scale << "\n"
424 << "\\graphics " << h_graphics << "\n"
425 << "\\paperfontsize " << h_paperfontsize << "\n"
426 << "\\spacing " << h_spacing << "\n"
427 << "\\papersize " << h_papersize << "\n"
428 << "\\use_geometry " << h_use_geometry << "\n"
429 << "\\use_amsmath " << h_use_amsmath << "\n"
430 << "\\cite_engine " << h_cite_engine << "\n"
431 << "\\use_bibtopic " << h_use_bibtopic << "\n"
432 << "\\paperorientation " << h_paperorientation << "\n"
434 << "\\secnumdepth " << h_secnumdepth << "\n"
435 << "\\tocdepth " << h_tocdepth << "\n"
436 << "\\paragraph_separation " << h_paragraph_separation << "\n"
437 << "\\defskip " << h_defskip << "\n"
438 << "\\quotes_language " << h_quotes_language << "\n"
439 << "\\papercolumns " << h_papercolumns << "\n"
440 << "\\papersides " << h_papersides << "\n"
441 << "\\paperpagestyle " << h_paperpagestyle << "\n"
442 << "\\tracking_changes " << h_tracking_changes << "\n"
443 << "\\output_changes " << h_output_changes << "\n"
444 << "\\end_header\n\n"
446 // clear preamble for subdocuments
450 } // anonymous namespace
452 void parse_preamble(Parser & p, ostream & os,
453 string const & forceclass, TeX2LyXDocClass & tc)
455 // initialize fixed types
456 special_columns['D'] = 3;
457 bool is_full_document = false;
459 // determine whether this is a full document or a fragment for inclusion
461 Token const & t = p.get_token();
463 if (t.cat() == catEscape && t.cs() == "documentclass") {
464 is_full_document = true;
470 while (is_full_document && p.good()) {
471 Token const & t = p.get_token();
474 cerr << "t: " << t << "\n";
480 if (t.cat() == catLetter ||
481 t.cat() == catSuper ||
483 t.cat() == catOther ||
484 t.cat() == catMath ||
485 t.cat() == catActive ||
486 t.cat() == catBegin ||
488 t.cat() == catAlign ||
489 t.cat() == catParameter)
490 h_preamble << t.character();
492 else if (t.cat() == catSpace || t.cat() == catNewline)
493 h_preamble << t.asInput();
495 else if (t.cat() == catComment)
496 h_preamble << t.asInput();
498 else if (t.cs() == "pagestyle")
499 h_paperpagestyle = p.verbatim_item();
501 else if (t.cs() == "makeatletter") {
502 p.setCatCode('@', catLetter);
505 else if (t.cs() == "makeatother") {
506 p.setCatCode('@', catOther);
509 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
510 || t.cs() == "providecommand") {
512 if (p.next_token().character() == '*') {
516 string const name = p.verbatim_item();
517 string const opt1 = p.getOpt();
518 string const opt2 = p.getFullOpt();
519 string const body = p.verbatim_item();
521 if (name == "\\rmdefault")
522 if (is_known(body, known_roman_fonts))
525 if (name == "\\sfdefault")
526 if (is_known(body, known_sans_fonts))
529 if (name == "\\ttdefault")
530 if (is_known(body, known_typewriter_fonts))
531 h_font_typewriter = body;
533 if (name == "\\familydefault") {
534 string family = body;
535 // remove leading "\"
536 h_font_default_family = family.erase(0,1);
538 // only non-lyxspecific stuff
539 if ( name != "\\noun"
540 && name != "\\tabularnewline"
542 && name != "\\lyxline"
543 && name != "\\lyxaddress"
544 && name != "\\lyxrightaddress"
545 && name != "\\lyxdot"
546 && name != "\\boldsymbol"
547 && name != "\\lyxarrow"
548 && name != "\\rmdefault"
549 && name != "\\sfdefault"
550 && name != "\\ttdefault"
551 && name != "\\familydefault") {
553 ss << '\\' << t.cs();
556 ss << '{' << name << '}' << opt1 << opt2
557 << '{' << body << "}";
558 h_preamble << ss.str();
560 // Add the command to the known commands
561 add_known_command(name, opt1, !opt2.empty());
563 ostream & out = in_preamble ? h_preamble : os;
564 out << "\\" << t.cs() << "{" << name << "}"
565 << opts << "{" << body << "}";
570 else if (t.cs() == "documentclass") {
571 vector<string>::iterator it;
572 vector<string> opts = split_options(p.getArg('[', ']'));
573 handle_opt(opts, known_fontsizes, h_paperfontsize);
574 delete_opt(opts, known_fontsizes);
575 // delete "pt" at the end
576 string::size_type i = h_paperfontsize.find("pt");
577 if (i != string::npos)
578 h_paperfontsize.erase(i);
579 // to avoid that the babel options overwrite the documentclass options
580 documentclass_language = false;
581 handle_opt(opts, known_languages, h_language);
582 delete_opt(opts, known_languages);
583 if (is_known(h_language, known_french_languages))
584 h_language = "french";
585 else if (is_known(h_language, known_german_languages))
586 h_language = "german";
587 else if (is_known(h_language, known_ngerman_languages))
588 h_language = "ngerman";
589 else if (is_known(h_language, known_russian_languages))
590 h_language = "russian";
591 else if (is_known(h_language, known_ukrainian_languages))
592 h_language = "ukrainian";
593 h_quotes_language = h_language;
595 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
596 h_paperorientation = "landscape";
600 if ((it = find(opts.begin(), opts.end(), "oneside"))
605 if ((it = find(opts.begin(), opts.end(), "twoside"))
611 if ((it = find(opts.begin(), opts.end(), "onecolumn"))
613 h_papercolumns = "1";
616 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
618 h_papercolumns = "2";
622 // some size options are know to any document classes, other sizes
623 // are handled by the \geometry command of the geometry package
624 handle_opt(opts, known_class_paper_sizes, h_papersize);
625 delete_opt(opts, known_class_paper_sizes);
626 // the remaining options
627 h_options = join(opts, ",");
628 h_textclass = p.getArg('{', '}');
631 else if (t.cs() == "usepackage") {
632 string const options = p.getArg('[', ']');
633 string const name = p.getArg('{', '}');
634 if (options.empty() && name.find(',')) {
635 vector<string> vecnames;
636 split(name, vecnames, ',');
637 vector<string>::const_iterator it = vecnames.begin();
638 vector<string>::const_iterator end = vecnames.end();
639 for (; it != end; ++it)
640 handle_package(trim(*it), string());
642 handle_package(name, options);
646 else if (t.cs() == "newenvironment") {
647 string const name = p.getArg('{', '}');
649 ss << "\\newenvironment{" << name << "}";
652 ss << '{' << p.verbatim_item() << '}';
653 ss << '{' << p.verbatim_item() << '}';
654 if (name != "lyxcode" && name != "lyxlist" &&
655 name != "lyxrightadress" &&
656 name != "lyxaddress" && name != "lyxgreyedout")
657 h_preamble << ss.str();
660 else if (t.cs() == "def") {
661 string name = p.get_token().cs();
662 while (p.next_token().cat() != catBegin)
663 name += p.get_token().asString();
664 h_preamble << "\\def\\" << name << '{'
665 << p.verbatim_item() << "}";
668 else if (t.cs() == "newcolumntype") {
669 string const name = p.getArg('{', '}');
672 string opts = p.getOpt();
674 istringstream is(string(opts, 1));
677 special_columns[name[0]] = nargs;
678 h_preamble << "\\newcolumntype{" << name << "}";
680 h_preamble << "[" << nargs << "]";
681 h_preamble << "{" << p.verbatim_item() << "}";
684 else if (t.cs() == "setcounter") {
685 string const name = p.getArg('{', '}');
686 string const content = p.getArg('{', '}');
687 if (name == "secnumdepth")
688 h_secnumdepth = content;
689 else if (name == "tocdepth")
690 h_tocdepth = content;
692 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
695 else if (t.cs() == "setlength") {
696 string const name = p.verbatim_item();
697 string const content = p.verbatim_item();
698 // the paragraphs are only not indented when \parindent is set to zero
699 if (name == "\\parindent" && content != "") {
700 if (content[0] == '0')
701 h_paragraph_separation = "skip";
702 } else if (name == "\\parskip") {
703 if (content == "\\smallskipamount")
704 h_defskip = "smallskip";
705 else if (content == "\\medskipamount")
706 h_defskip = "medskip";
707 else if (content == "\\bigskipamount")
708 h_defskip = "bigskip";
712 h_preamble << "\\setlength{" << name << "}{" << content << "}";
715 else if (t.cs() == "onehalfspacing")
716 h_spacing = "onehalf";
718 else if (t.cs() == "doublespacing")
719 h_spacing = "double";
721 else if (t.cs() == "setstretch")
722 h_spacing = "other " + p.verbatim_item();
724 else if (t.cs() == "begin") {
725 string const name = p.getArg('{', '}');
726 if (name == "document")
728 h_preamble << "\\begin{" << name << "}";
731 else if (t.cs() == "geometry") {
732 h_use_geometry = "true";
733 vector<string> opts = split_options(p.getArg('{', '}'));
734 vector<string>::iterator it;
736 if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
737 h_paperorientation = "landscape";
741 handle_opt(opts, known_paper_sizes, h_papersize);
742 delete_opt(opts, known_paper_sizes);
744 char const * const * margin = known_paper_margins;
746 for (; *margin; ++margin) {
748 // search for the "=" in e.g. "lmargin=2cm" to get the value
749 for(size_t i = 0; i != opts.size(); i++) {
750 if (opts.at(i).find(*margin) != string::npos) {
751 string::size_type pos = opts.at(i).find("=");
752 string value = opts.at(i).substr(pos + 1);
753 string name = known_coded_paper_margins[k];
754 h_margins += "\\" + name + " " + value + "\n";
760 else if (t.cs() == "jurabibsetup") {
761 vector<string> jurabibsetup =
762 split_options(p.getArg('{', '}'));
763 // add jurabibsetup to the jurabib package options
764 add_package("jurabib", jurabibsetup);
765 if (!jurabibsetup.empty()) {
766 h_preamble << "\\jurabibsetup{"
767 << join(jurabibsetup, ",") << '}';
771 else if (!t.cs().empty())
772 h_preamble << '\\' << t.cs();
776 // Force textclass if the user wanted it
777 if (!forceclass.empty())
778 h_textclass = forceclass;
779 if (noweb_mode && !prefixIs(h_textclass, "literate-"))
780 h_textclass.insert(0, "literate-");
781 FileName layoutfilename = libFileSearch("layouts", h_textclass, "layout");
782 if (layoutfilename.empty()) {
783 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
786 tc.read(layoutfilename);
787 if (h_papersides.empty()) {
790 h_papersides = ss.str();
792 end_preamble(os, tc);