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",
87 ostringstream h_preamble;
88 string h_textclass = "article";
89 string h_options = string();
90 string h_language = "english";
91 string h_inputencoding = "auto";
92 string h_font_roman = "default";
93 string h_font_sans = "default";
94 string h_font_typewriter = "default";
95 string h_font_default_family = "default";
96 string h_font_sc = "false";
97 string h_font_osf = "false";
98 string h_font_sf_scale = "100";
99 string h_font_tt_scale = "100";
100 string h_graphics = "default";
101 string h_paperfontsize = "default";
102 string h_spacing = "single";
103 string h_papersize = "default";
104 string h_use_geometry = "false";
105 string h_use_amsmath = "0";
106 string h_cite_engine = "basic";
107 string h_use_bibtopic = "false";
108 string h_paperorientation = "portrait";
109 string h_secnumdepth = "3";
110 string h_tocdepth = "3";
111 string h_paragraph_separation = "indent";
112 string h_defskip = "medskip";
113 string h_quotes_language = "english";
114 string h_papercolumns = "1";
115 string h_papersides = string();
116 string h_paperpagestyle = "default";
117 string h_tracking_changes = "false";
118 string h_output_changes = "false";
121 void handle_opt(vector<string> & opts, char const * const * what, string & target)
126 // the last language option is the document language (for babel and LyX)
127 // the last size option is the document font size
128 vector<string>::iterator it;
129 vector<string>::iterator position = opts.begin();
130 for (; *what; ++what) {
131 it = find(opts.begin(), opts.end(), *what);
132 if (it != opts.end()) {
133 documentclass_language = true;
134 if (it >= position) {
143 void delete_opt(vector<string> & opts, char const * const * what)
148 // remove found options from the list
149 // do this after handle_opt to avoid potential memory leaks and to be able
150 // to find in every case the last language option
151 vector<string>::iterator it;
152 for (; *what; ++what) {
153 it = find(opts.begin(), opts.end(), *what);
154 if (it != opts.end())
161 * Split a package options string (keyval format) into a vector.
163 * authorformat=smallcaps,
165 * titleformat=colonsep,
166 * bibformat={tabular,ibidem,numbered}
168 vector<string> split_options(string const & input)
170 vector<string> options;
174 Token const & t = p.get_token();
175 if (t.asInput() == ",") {
176 options.push_back(trim(option));
178 } else if (t.asInput() == "=") {
181 if (p.next_token().asInput() == "{")
182 option += '{' + p.getArg('{', '}') + '}';
183 } else if (t.cat() != catSpace)
184 option += t.asInput();
188 options.push_back(trim(option));
195 * Add package \p name with options \p options to used_packages.
196 * Remove options from \p options that we don't want to output.
198 void add_package(string const & name, vector<string> & options)
200 // every package inherits the global options
201 if (used_packages.find(name) == used_packages.end())
202 used_packages[name] = split_options(h_options);
204 vector<string> & v = used_packages[name];
205 v.insert(v.end(), options.begin(), options.end());
206 if (name == "jurabib") {
207 // Don't output the order argument (see the cite command
208 // handling code in text.cpp).
209 vector<string>::iterator end =
210 remove(options.begin(), options.end(), "natbiborder");
211 end = remove(options.begin(), end, "jurabiborder");
212 options.erase(end, options.end());
217 // Given is a string like "scaled=0.9", return 0.9 * 100
218 string const scale_as_percentage(string const & scale)
220 string::size_type pos = scale.find('=');
221 if (pos != string::npos) {
222 string value = scale.substr(pos + 1);
224 return convert<string>(100 * convert<double>(value));
226 // If the input string didn't match our expectations.
227 // return the default value "100"
232 void handle_package(string const & name, string const & opts)
234 vector<string> options = split_options(opts);
235 add_package(name, options);
239 if (is_known(name, known_roman_fonts))
242 if (name == "fourier") {
243 h_font_roman = "utopia";
244 // when font uses real small capitals
245 if (opts == "expert")
248 if (name == "mathpazo")
249 h_font_roman = "palatino";
251 if (name == "mathptmx")
252 h_font_roman = "times";
255 if (is_known(name, known_sans_fonts)) {
259 h_font_sf_scale = scale_as_percentage(scale);
263 if (is_known(name, known_typewriter_fonts)) {
264 h_font_typewriter = name;
267 h_font_tt_scale = scale_as_percentage(scale);
270 // font uses old-style figure
274 else if (name == "amsmath" || name == "amssymb")
277 else if (name == "babel" && !opts.empty()) {
278 // check if more than one option was used - used later for inputenc
279 // in case inputenc is parsed before babel, set the encoding to auto
280 if (options.begin() != options.end() - 1) {
281 one_language = false;
282 h_inputencoding = "auto";
284 // only set the document language when there was not already one set
285 // via the documentclass options
286 // babel takes the the last language given in the documentclass options
287 // as document language. If there is no such language option, the last
288 // option of its \usepackage call is used.
289 if (documentclass_language == false) {
290 handle_opt(options, known_languages, h_language);
291 delete_opt(options, known_languages);
292 if (is_known(h_language, known_french_languages))
293 h_language = "french";
294 else if (is_known(h_language, known_german_languages))
295 h_language = "german";
296 else if (is_known(h_language, known_ngerman_languages))
297 h_language = "ngerman";
298 else if (is_known(h_language, known_russian_languages))
299 h_language = "russian";
300 else if (is_known(h_language, known_ukrainian_languages))
301 h_language = "ukrainian";
302 h_quotes_language = h_language;
305 else if (name == "fontenc")
308 else if (name == "inputenc") {
309 // only set when there is not more than one inputenc option
310 // therefore check for the "," character
311 // also only set when there is not more then one babel language option
312 if (opts.find(",") == string::npos && one_language == true)
314 //change ascii to auto to be in the unicode range, see
315 //http://bugzilla.lyx.org/show_bug.cgi?id=4719
316 h_inputencoding = "auto";
318 h_inputencoding = opts;
321 else if (name == "makeidx")
324 else if (name == "verbatim")
327 else if (name == "color")
328 // with the following command this package is only loaded when needed for
329 // undefined colors, since we only support the predefined colors
330 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
332 else if (name == "graphicx")
335 else if (name == "setspace")
338 else if (is_known(name, known_languages)) {
339 if (is_known(name, known_french_languages))
340 h_language = "french";
341 else if (is_known(name, known_german_languages))
342 h_language = "german";
343 else if (is_known(name, known_ngerman_languages))
344 h_language = "ngerman";
345 else if (is_known(name, known_russian_languages))
346 h_language = "russian";
347 else if (is_known(name, known_ukrainian_languages))
348 h_language = "ukrainian";
351 h_quotes_language = h_language;
353 else if (name == "natbib") {
354 h_cite_engine = "natbib_authoryear";
355 vector<string>::iterator it =
356 find(options.begin(), options.end(), "authoryear");
357 if (it != options.end())
360 it = find(options.begin(), options.end(), "numbers");
361 if (it != options.end()) {
362 h_cite_engine = "natbib_numerical";
367 else if (name == "jurabib")
368 h_cite_engine = "jurabib";
370 else if (options.empty())
371 h_preamble << "\\usepackage{" << name << "}\n";
373 h_preamble << "\\usepackage[" << opts << "]{" << name << "}\n";
376 // We need to do something with the options...
377 if (!options.empty())
378 cerr << "Ignoring options '" << join(options, ",")
379 << "' of package " << name << '.' << endl;
384 void end_preamble(ostream & os, TextClass const & /*textclass*/)
386 os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
387 << "\\lyxformat 247\n"
388 << "\\begin_document\n"
389 << "\\begin_header\n"
390 << "\\textclass " << h_textclass << "\n";
391 if (!h_preamble.str().empty())
392 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
393 if (!h_options.empty())
394 os << "\\options " << h_options << "\n";
395 os << "\\language " << h_language << "\n"
396 << "\\inputencoding " << h_inputencoding << "\n"
397 << "\\font_roman " << h_font_roman << "\n"
398 << "\\font_sans " << h_font_sans << "\n"
399 << "\\font_typewriter " << h_font_typewriter << "\n"
400 << "\\font_default_family " << h_font_default_family << "\n"
401 << "\\font_sc " << h_font_sc << "\n"
402 << "\\font_osf " << h_font_osf << "\n"
403 << "\\font_sf_scale " << h_font_sf_scale << "\n"
404 << "\\font_tt_scale " << h_font_tt_scale << "\n"
405 << "\\graphics " << h_graphics << "\n"
406 << "\\paperfontsize " << h_paperfontsize << "\n"
407 << "\\spacing " << h_spacing << "\n"
408 << "\\papersize " << h_papersize << "\n"
409 << "\\use_geometry " << h_use_geometry << "\n"
410 << "\\use_amsmath " << h_use_amsmath << "\n"
411 << "\\cite_engine " << h_cite_engine << "\n"
412 << "\\use_bibtopic " << h_use_bibtopic << "\n"
413 << "\\paperorientation " << h_paperorientation << "\n"
414 << "\\secnumdepth " << h_secnumdepth << "\n"
415 << "\\tocdepth " << h_tocdepth << "\n"
416 << "\\paragraph_separation " << h_paragraph_separation << "\n"
417 << "\\defskip " << h_defskip << "\n"
418 << "\\quotes_language " << h_quotes_language << "\n"
419 << "\\papercolumns " << h_papercolumns << "\n"
420 << "\\papersides " << h_papersides << "\n"
421 << "\\paperpagestyle " << h_paperpagestyle << "\n"
422 << "\\tracking_changes " << h_tracking_changes << "\n"
423 << "\\output_changes " << h_output_changes << "\n"
424 << "\\end_header\n\n"
426 // clear preamble for subdocuments
430 } // anonymous namespace
432 void parse_preamble(Parser & p, ostream & os,
433 string const & forceclass, TeX2LyXDocClass & tc)
435 // initialize fixed types
436 special_columns['D'] = 3;
437 bool is_full_document = false;
439 // determine whether this is a full document or a fragment for inclusion
441 Token const & t = p.get_token();
443 if (t.cat() == catEscape && t.cs() == "documentclass") {
444 is_full_document = true;
450 while (is_full_document && p.good()) {
451 Token const & t = p.get_token();
454 cerr << "t: " << t << "\n";
460 if (t.cat() == catLetter ||
461 t.cat() == catSuper ||
463 t.cat() == catOther ||
464 t.cat() == catMath ||
465 t.cat() == catActive ||
466 t.cat() == catBegin ||
468 t.cat() == catAlign ||
469 t.cat() == catParameter)
470 h_preamble << t.character();
472 else if (t.cat() == catSpace || t.cat() == catNewline)
473 h_preamble << t.asInput();
475 else if (t.cat() == catComment)
476 h_preamble << t.asInput();
478 else if (t.cs() == "pagestyle")
479 h_paperpagestyle = p.verbatim_item();
481 else if (t.cs() == "makeatletter") {
482 p.setCatCode('@', catLetter);
485 else if (t.cs() == "makeatother") {
486 p.setCatCode('@', catOther);
489 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
490 || t.cs() == "providecommand") {
492 if (p.next_token().character() == '*') {
496 string const name = p.verbatim_item();
497 string const opt1 = p.getOpt();
498 string const opt2 = p.getFullOpt();
499 string const body = p.verbatim_item();
501 if (name == "\\rmdefault")
502 if (is_known(body, known_roman_fonts))
505 if (name == "\\sfdefault")
506 if (is_known(body, known_sans_fonts))
509 if (name == "\\ttdefault")
510 if (is_known(body, known_typewriter_fonts))
511 h_font_typewriter = body;
513 if (name == "\\familydefault") {
514 string family = body;
515 // remove leading "\"
516 h_font_default_family = family.erase(0,1);
518 // only non-lyxspecific stuff
519 if ( name != "\\noun"
520 && name != "\\tabularnewline"
522 && name != "\\lyxline"
523 && name != "\\lyxaddress"
524 && name != "\\lyxrightaddress"
525 && name != "\\lyxdot"
526 && name != "\\boldsymbol"
527 && name != "\\lyxarrow"
528 && name != "\\rmdefault"
529 && name != "\\sfdefault"
530 && name != "\\ttdefault"
531 && name != "\\familydefault") {
533 ss << '\\' << t.cs();
536 ss << '{' << name << '}' << opt1 << opt2
537 << '{' << body << "}";
538 h_preamble << ss.str();
540 // Add the command to the known commands
541 add_known_command(name, opt1, !opt2.empty());
543 ostream & out = in_preamble ? h_preamble : os;
544 out << "\\" << t.cs() << "{" << name << "}"
545 << opts << "{" << body << "}";
550 else if (t.cs() == "documentclass") {
551 vector<string>::iterator it;
552 vector<string> opts = split_options(p.getArg('[', ']'));
553 handle_opt(opts, known_fontsizes, h_paperfontsize);
554 delete_opt(opts, known_fontsizes);
555 // delete "pt" at the end
556 string::size_type i = h_paperfontsize.find("pt");
557 if (i != string::npos)
558 h_paperfontsize.erase(i);
559 // to avoid that the babel options overwrite the documentclass options
560 documentclass_language = false;
561 handle_opt(opts, known_languages, h_language);
562 delete_opt(opts, known_languages);
563 if (is_known(h_language, known_french_languages))
564 h_language = "french";
565 else if (is_known(h_language, known_german_languages))
566 h_language = "german";
567 else if (is_known(h_language, known_ngerman_languages))
568 h_language = "ngerman";
569 else if (is_known(h_language, known_russian_languages))
570 h_language = "russian";
571 else if (is_known(h_language, known_ukrainian_languages))
572 h_language = "ukrainian";
573 h_quotes_language = h_language;
575 if ((it = find(opts.begin(), opts.end(), "twoside"))
581 if ((it = find(opts.begin(), opts.end(), "twocolumn"))
583 h_papercolumns = "2";
586 // the remaining options
587 h_options = join(opts, ",");
588 h_textclass = p.getArg('{', '}');
591 else if (t.cs() == "usepackage") {
592 string const options = p.getArg('[', ']');
593 string const name = p.getArg('{', '}');
594 if (options.empty() && name.find(',')) {
595 vector<string> vecnames;
596 split(name, vecnames, ',');
597 vector<string>::const_iterator it = vecnames.begin();
598 vector<string>::const_iterator end = vecnames.end();
599 for (; it != end; ++it)
600 handle_package(trim(*it), string());
602 handle_package(name, options);
606 else if (t.cs() == "newenvironment") {
607 string const name = p.getArg('{', '}');
609 ss << "\\newenvironment{" << name << "}";
612 ss << '{' << p.verbatim_item() << '}';
613 ss << '{' << p.verbatim_item() << '}';
614 if (name != "lyxcode" && name != "lyxlist" &&
615 name != "lyxrightadress" &&
616 name != "lyxaddress" && name != "lyxgreyedout")
617 h_preamble << ss.str();
620 else if (t.cs() == "def") {
621 string name = p.get_token().cs();
622 while (p.next_token().cat() != catBegin)
623 name += p.get_token().asString();
624 h_preamble << "\\def\\" << name << '{'
625 << p.verbatim_item() << "}";
628 else if (t.cs() == "newcolumntype") {
629 string const name = p.getArg('{', '}');
632 string opts = p.getOpt();
634 istringstream is(string(opts, 1));
637 special_columns[name[0]] = nargs;
638 h_preamble << "\\newcolumntype{" << name << "}";
640 h_preamble << "[" << nargs << "]";
641 h_preamble << "{" << p.verbatim_item() << "}";
644 else if (t.cs() == "setcounter") {
645 string const name = p.getArg('{', '}');
646 string const content = p.getArg('{', '}');
647 if (name == "secnumdepth")
648 h_secnumdepth = content;
649 else if (name == "tocdepth")
650 h_tocdepth = content;
652 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
655 else if (t.cs() == "setlength") {
656 string const name = p.verbatim_item();
657 string const content = p.verbatim_item();
658 // the paragraphs are only not indented when \parindent is set to zero
659 if (name == "\\parindent" && content != "") {
660 if (content[0] == '0')
661 h_paragraph_separation = "skip";
662 } else if (name == "\\parskip") {
663 if (content == "\\smallskipamount")
664 h_defskip = "smallskip";
665 else if (content == "\\medskipamount")
666 h_defskip = "medskip";
667 else if (content == "\\bigskipamount")
668 h_defskip = "bigskip";
672 h_preamble << "\\setlength{" << name << "}{" << content << "}";
675 else if (t.cs() == "onehalfspacing")
676 h_spacing = "onehalf";
678 else if (t.cs() == "doublespacing")
679 h_spacing = "double";
681 else if (t.cs() == "setstretch")
682 h_spacing = "other " + p.verbatim_item();
684 else if (t.cs() == "begin") {
685 string const name = p.getArg('{', '}');
686 if (name == "document")
688 h_preamble << "\\begin{" << name << "}";
691 else if (t.cs() == "jurabibsetup") {
692 vector<string> jurabibsetup =
693 split_options(p.getArg('{', '}'));
694 // add jurabibsetup to the jurabib package options
695 add_package("jurabib", jurabibsetup);
696 if (!jurabibsetup.empty()) {
697 h_preamble << "\\jurabibsetup{"
698 << join(jurabibsetup, ",") << '}';
702 else if (!t.cs().empty())
703 h_preamble << '\\' << t.cs();
707 // Force textclass if the user wanted it
708 if (!forceclass.empty())
709 h_textclass = forceclass;
710 if (noweb_mode && !prefixIs(h_textclass, "literate-"))
711 h_textclass.insert(0, "literate-");
712 FileName layoutfilename = libFileSearch("layouts", h_textclass, "layout");
713 if (layoutfilename.empty()) {
714 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
717 tc.read(layoutfilename);
718 if (h_papersides.empty()) {
721 h_papersides = ss.str();
723 end_preamble(os, tc);