]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/preamble.cpp
Increase tex2lyx output format to 297.
[lyx.git] / src / tex2lyx / preamble.cpp
1 /**
2  * \file preamble.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Uwe Stöhr
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 // {[(
13
14 #include <config.h>
15
16 #include "tex2lyx.h"
17
18 #include "LayoutFile.h"
19 #include "Layout.h"
20 #include "Lexer.h"
21 #include "TextClass.h"
22
23 #include "support/convert.h"
24 #include "support/FileName.h"
25 #include "support/filetools.h"
26 #include "support/lstrings.h"
27
28 #include "support/regex.h"
29
30 #include <algorithm>
31 #include <iostream>
32 #include <sstream>
33 #include <string>
34 #include <vector>
35 #include <map>
36
37 using namespace std;
38 using namespace lyx::support;
39
40
41 namespace lyx {
42
43 // special columntypes
44 extern map<char, int> special_columns;
45
46 map<string, vector<string> > used_packages;
47
48 // needed to handle encodings with babel
49 bool one_language = true;
50
51 namespace {
52
53 //add this to known_languages when updating to lyxformat 266:
54 // "armenian"
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,
58 // armtex) is added.
59 const char * const known_languages[] = { "afrikaans", "albanian", "american",
60 "arabic", "arabtex", "austrian", "bahasa", "basque", "belarusian", "brazil",
61 "brazilian", "breton", "british", "bulgarian", "canadian", "canadien",
62 "catalan", "croatian", "czech", "danish", "dutch", "english", "esperanto",
63 "estonian", "finnish", "francais", "french", "frenchb", "frenchle", "frenchpro",
64 "galician", "german", "germanb", "greek", "hebrew", "icelandic", "irish",
65 "italian", "kazakh", "latvian", "lithuanian", "lsorbian", "magyar",
66 "naustrian", "ngerman", "ngermanb", "norsk", "nynorsk", "polish", "portuges",
67 "portuguese", "romanian", "russian", "russianb", "scottish", "serbian", "slovak",
68 "slovene", "spanish", "swedish", "thai", "turkish", "ukraineb", "ukrainian",
69 "usorbian", "welsh", 0};
70
71 //add this when updating to lyxformat 305:
72 //bahasai, indonesian, and indon = equal to bahasa
73 //malay and meyalu = equal to bahasam
74 const char * const known_brazilian_languages[] = {"brazil", "brazilian", 0};
75 const char * const known_french_languages[] = {"french", "frenchb", "francais",
76                                                 "frenchle", "frenchpro", 0};
77 const char * const known_german_languages[] = {"german", "germanb", 0};
78 const char * const known_ngerman_languages[] = {"ngerman", "ngermanb", 0};
79 const char * const known_portuguese_languages[] = {"portuges", "portuguese", 0};
80 const char * const known_russian_languages[] = {"russian", "russianb", 0};
81 const char * const known_ukrainian_languages[] = {"ukrainian", "ukraineb", 0};
82
83 //add these to known_english_quotes_languages when updating to lyxformat 268:
84 //"chinese-simplified", "korean"
85 // This requires first that support for non-babel languages (CJK) is added.
86 const char * const known_english_quotes_languages[] = {"american", "canadian",
87 "english", "esperanto", "hebrew", "irish", "scottish", "thai", 0};
88
89 //add this to known_french_quotes_languages when updating to lyxformat 327:
90 //"spanish-mexico"
91 const char * const known_french_quotes_languages[] = {"albanian", "arabic",
92 "basque", "canadien", "catalan", "galician", "greek", "italian", "norsk",
93 "nynorsk", "spanish", "turkish", 0};
94
95 const char * const known_german_quotes_languages[] = {"austrian", "bulgarian",
96 "czech", "icelandic", "lithuanian", "lsorbian", "naustrian", "serbian",
97 "serbian-latin", "slovak", "slovene", "usorbian",  0};
98
99 const char * const known_polish_quotes_languages[] = {"afrikaans", "croatian",
100 "dutch", "estonian", "magyar", "polish", "romanian", 0};
101
102 const char * const known_swedish_quotes_languages[] = {"bahasa", "finnish", 
103 "swedish", 0};
104
105 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
106
107 const char * const known_roman_fonts[] = { "ae", "bookman", "charter",
108 "cmr", "fourier", "lmodern", "mathpazo", "mathptmx", "newcent", 0};
109
110 const char * const known_sans_fonts[] = { "avant", "berasans", "cmbr", "cmss",
111 "helvet", "lmss", 0};
112
113 const char * const known_typewriter_fonts[] = { "beramono", "cmtl", "cmtt",
114 "courier", "lmtt", "luximono", "fourier", "lmodern", "mathpazo", "mathptmx",
115 "newcent", 0};
116
117 const char * const known_paper_sizes[] = { "a3paper", "b3paper", "a4paper",
118 "b4paper", "a5paper", "b5paper", "executivepaper", "legalpaper",
119 "letterpaper", 0};
120
121 const char * const known_class_paper_sizes[] = { "a4paper", "a5paper",
122 "executivepaper", "legalpaper", "letterpaper", 0};
123
124 const char * const known_paper_margins[] = { "lmargin", "tmargin", "rmargin", 
125 "bmargin", "headheight", "headsep", "footskip", "columnsep", 0};
126
127 const char * const known_coded_paper_margins[] = { "leftmargin", "topmargin",
128 "rightmargin", "bottommargin", "headheight", "headsep", "footskip",
129 "columnsep", 0};
130
131 // default settings
132 ostringstream h_preamble;
133 string h_textclass               = "article";
134 string h_options                 = string();
135 string h_language                = "english";
136 string h_inputencoding           = "auto";
137 string h_font_roman              = "default";
138 string h_font_sans               = "default";
139 string h_font_typewriter         = "default";
140 string h_font_default_family     = "default";
141 string h_font_sc                 = "false";
142 string h_font_osf                = "false";
143 string h_font_sf_scale           = "100";
144 string h_font_tt_scale           = "100";
145 string h_graphics                = "default";
146 string h_float_placement;
147 string h_paperfontsize           = "default";
148 string h_spacing                 = "single";
149 string h_use_hyperref            = "0";
150 string h_pdf_title;
151 string h_pdf_author;
152 string h_pdf_subject;
153 string h_pdf_keywords;
154 string h_pdf_bookmarks           = "1";
155 string h_pdf_bookmarksnumbered   = "0";
156 string h_pdf_bookmarksopen       = "0";
157 string h_pdf_bookmarksopenlevel  = "1";
158 string h_pdf_breaklinks          = "0";
159 string h_pdf_pdfborder           = "0";
160 string h_pdf_colorlinks          = "0";
161 string h_pdf_backref             = "0";
162 string h_pdf_pagebackref         = "0";
163 string h_pdf_pdfusetitle         = "1";
164 string h_pdf_pagemode;
165 string h_pdf_quoted_options;
166 string h_papersize               = "default";
167 string h_use_geometry            = "false";
168 string h_use_amsmath             = "1";
169 string h_use_esint               = "1";
170 string h_cite_engine             = "basic";
171 string h_use_bibtopic            = "false";
172 string h_paperorientation        = "portrait";
173 string h_secnumdepth             = "3";
174 string h_tocdepth                = "3";
175 string h_paragraph_separation    = "indent";
176 string h_defskip                 = "medskip";
177 string h_quotes_language         = "english";
178 string h_papercolumns            = "1";
179 string h_papersides              = string();
180 string h_paperpagestyle          = "default";
181 string h_listings_params;
182 string h_tracking_changes        = "false";
183 string h_output_changes          = "false";
184 string h_margins                 = "";
185
186
187 /// translates a babel language name to a LyX language name
188 string babel2lyx(string language)
189 {
190         if (language == "arabtex")
191                 return "arabic_arabtex";
192         if (language == "arabic")
193                 return "arabic_arabi";
194         if (language == "lsorbian")
195                 return "lowersorbian";
196         if (language == "usorbian")
197                 return "uppersorbian";
198         return language;
199 }
200
201
202 // returns true if at least one of the options in what has been found
203 bool handle_opt(vector<string> & opts, char const * const * what, string & target)
204 {
205         if (opts.empty())
206                 return false;
207
208         bool found = false;
209         // the last language option is the document language (for babel and LyX)
210         // the last size option is the document font size
211         vector<string>::iterator it;
212         vector<string>::iterator position = opts.begin();
213         for (; *what; ++what) {
214                 it = find(opts.begin(), opts.end(), *what);
215                 if (it != opts.end()) {
216                         if (it >= position) {
217                                 found = true;
218                                 target = *what;
219                                 position = it;
220                         }
221                 }
222         }
223         return found;
224 }
225
226
227 void delete_opt(vector<string> & opts, char const * const * what)
228 {
229         if (opts.empty())
230                 return;
231
232         // remove found options from the list
233         // do this after handle_opt to avoid potential memory leaks
234         vector<string>::iterator it;
235         for (; *what; ++what) {
236                 it = find(opts.begin(), opts.end(), *what);
237                 if (it != opts.end())
238                         opts.erase(it);
239         }
240 }
241
242
243 /*!
244  * Split a package options string (keyval format) into a vector.
245  * Example input:
246  *   authorformat=smallcaps,
247  *   commabeforerest,
248  *   titleformat=colonsep,
249  *   bibformat={tabular,ibidem,numbered}
250  */
251 vector<string> split_options(string const & input)
252 {
253         vector<string> options;
254         string option;
255         Parser p(input);
256         while (p.good()) {
257                 Token const & t = p.get_token();
258                 if (t.asInput() == ",") {
259                         options.push_back(trim(option));
260                         option.erase();
261                 } else if (t.asInput() == "=") {
262                         option += '=';
263                         p.skip_spaces(true);
264                         if (p.next_token().asInput() == "{")
265                                 option += '{' + p.getArg('{', '}') + '}';
266                 } else if (t.cat() != catSpace)
267                         option += t.asInput();
268         }
269
270         if (!option.empty())
271                 options.push_back(trim(option));
272
273         return options;
274 }
275
276
277 /*!
278  * Add package \p name with options \p options to used_packages.
279  * Remove options from \p options that we don't want to output.
280  */
281 void add_package(string const & name, vector<string> & options)
282 {
283         // every package inherits the global options
284         if (used_packages.find(name) == used_packages.end())
285                 used_packages[name] = split_options(h_options);
286
287         vector<string> & v = used_packages[name];
288         v.insert(v.end(), options.begin(), options.end());
289         if (name == "jurabib") {
290                 // Don't output the order argument (see the cite command
291                 // handling code in text.cpp).
292                 vector<string>::iterator end =
293                         remove(options.begin(), options.end(), "natbiborder");
294                 end = remove(options.begin(), end, "jurabiborder");
295                 options.erase(end, options.end());
296         }
297 }
298
299
300 // Given is a string like "scaled=0.9", return 0.9 * 100
301 string const scale_as_percentage(string const & scale)
302 {
303         string::size_type pos = scale.find('=');
304         if (pos != string::npos) {
305                 string value = scale.substr(pos + 1);
306                 if (isStrDbl(value))
307                         return convert<string>(100 * convert<double>(value));
308         }
309         // If the input string didn't match our expectations.
310         // return the default value "100"
311         return "100";
312 }
313
314
315 void handle_package(Parser &p, string const & name, string const & opts,
316                     bool in_lyx_preamble)
317 {
318         vector<string> options = split_options(opts);
319         add_package(name, options);
320         string scale;
321
322         // roman fonts
323         if (is_known(name, known_roman_fonts)) {
324                 h_font_roman = name;
325                 p.skip_spaces();
326         }
327
328         if (name == "fourier") {
329                 h_font_roman = "utopia";
330                 // when font uses real small capitals
331                 if (opts == "expert")
332                         h_font_sc = "true";
333         }
334
335         if (name == "mathpazo")
336                 h_font_roman = "palatino";
337
338         if (name == "mathptmx")
339                 h_font_roman = "times";
340
341         // sansserif fonts
342         if (is_known(name, known_sans_fonts)) {
343                 h_font_sans = name;
344                 if (!opts.empty()) {
345                         scale = opts;
346                         h_font_sf_scale = scale_as_percentage(scale);
347                 }
348         }
349
350         // typewriter fonts
351         if (is_known(name, known_typewriter_fonts)) {
352                 h_font_typewriter = name;
353                 if (!opts.empty()) {
354                         scale = opts;
355                         h_font_tt_scale = scale_as_percentage(scale);
356                 }
357         }
358
359         // font uses old-style figure
360         if (name == "eco")
361                 h_font_osf = "true";
362
363         else if (name == "amsmath" || name == "amssymb")
364                 h_use_amsmath = "2";
365
366         else if (name == "esint")
367                 h_use_esint = "2";
368
369         else if (name == "babel" && !opts.empty()) {
370                 // check if more than one option was used - used later for inputenc
371                 // in case inputenc is parsed before babel, set the encoding to auto
372                 if (options.begin() != options.end() - 1) {
373                         one_language = false;
374                         h_inputencoding = "auto";
375                 }
376                 // babel takes the last language of the option of its \usepackage
377                 // call as document language. If there is no such language option, the
378                 // last language in the documentclass options is used.
379                 handle_opt(options, known_languages, h_language);
380                 delete_opt(options, known_languages);
381         }
382
383         else if (name == "fontenc")
384                  ;// ignore this
385
386         else if (name == "inputenc") {
387                 // h_inputencoding is only set when there is not more than one
388                 // inputenc option because otherwise h_inputencoding must be
389                 // set to "auto" (the default encoding of the document language)
390                 // Therefore check for the "," character.
391                 // It is also only set when there is not more then one babel
392                 // language option but this is handled in the routine for babel.
393                 if (opts.find(",") == string::npos && one_language == true)
394                         h_inputencoding = opts;
395                 if (!options.empty())
396                         p.setEncoding(options.back());
397                 options.clear();
398         }
399
400         else if (name == "makeidx")
401                 ; // ignore this
402
403         else if (name == "prettyref")
404                 ; // ignore this
405
406         else if (name == "varioref")
407                 ; // ignore this
408
409         else if (name == "verbatim")
410                 ; // ignore this
411
412         else if (name == "nomencl")
413                 ; // ignore this
414
415         else if (name == "textcomp")
416                 ; // ignore this
417
418         else if (name == "url")
419                 ; // ignore this
420
421         else if (LYX_FORMAT >= 408 && name == "subscript")
422                 ; // ignore this
423
424         else if (name == "color") {
425                 // with the following command this package is only loaded when needed for
426                 // undefined colors, since we only support the predefined colors
427                 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
428         }
429
430         else if (name == "graphicx")
431                 ; // ignore this
432
433         else if (name == "setspace")
434                 ; // ignore this
435
436         else if (name == "geometry")
437                 ; // Ignore this, the geometry settings are made by the \geometry
438                   // command. This command is handled below.
439
440         else if (is_known(name, known_languages))
441                 h_language = name;
442
443         else if (name == "natbib") {
444                 h_cite_engine = "natbib_authoryear";
445                 vector<string>::iterator it =
446                         find(options.begin(), options.end(), "authoryear");
447                 if (it != options.end())
448                         options.erase(it);
449                 else {
450                         it = find(options.begin(), options.end(), "numbers");
451                         if (it != options.end()) {
452                                 h_cite_engine = "natbib_numerical";
453                                 options.erase(it);
454                         }
455                 }
456         }
457
458         else if (name == "jurabib")
459                 h_cite_engine = "jurabib";
460
461         else if (!in_lyx_preamble) {
462                 if (options.empty())
463                         h_preamble << "\\usepackage{" << name << "}";
464                 else {
465                         h_preamble << "\\usepackage[" << opts << "]{" 
466                                    << name << "}";
467                         options.clear();
468                 }
469         }
470
471         // We need to do something with the options...
472         if (!options.empty())
473                 cerr << "Ignoring options '" << join(options, ",")
474                      << "' of package " << name << '.' << endl;
475
476         // remove the whitespace
477         p.skip_spaces();
478 }
479
480
481
482 void end_preamble(ostream & os, TextClass const & /*textclass*/)
483 {
484         // merge synonym languages
485         if (is_known(h_language, known_brazilian_languages))
486                 h_language = "brazilian";
487         else if (is_known(h_language, known_french_languages))
488                 h_language = "french";
489         else if (is_known(h_language, known_german_languages))
490                 h_language = "german";
491         else if (is_known(h_language, known_ngerman_languages))
492                 h_language = "ngerman";
493         else if (is_known(h_language, known_portuguese_languages))
494                 h_language = "portuguese";
495         else if (is_known(h_language, known_russian_languages))
496                 h_language = "russian";
497         else if (is_known(h_language, known_ukrainian_languages))
498                 h_language = "ukrainian";
499
500         // set the quote language
501         // LyX only knows the following quotes languages:
502         // english, swedish, german, polish, french and danish
503         // (quotes for "japanese" and "chinese-traditional" are missing because
504         //  they wouldn't be useful: http://www.lyx.org/trac/ticket/6383)
505         // conversion list taken from
506         // http://en.wikipedia.org/wiki/Quotation_mark,_non-English_usage
507         // (quotes for kazakh and interlingua are unknown)
508         // danish
509         if (h_language == "danish")
510                 h_quotes_language = "danish";
511         // french
512         else if (is_known(h_language, known_french_quotes_languages)
513                 || is_known(h_language, known_french_languages)
514                 || is_known(h_language, known_russian_languages)
515                 || is_known(h_language, known_ukrainian_languages))
516                 h_quotes_language = "french";
517         // german
518         else if (is_known(h_language, known_german_quotes_languages)
519                 || is_known(h_language, known_german_languages)
520                 || is_known(h_language, known_ngerman_languages))
521                 h_quotes_language = "german";
522         // polish
523         else if (is_known(h_language, known_polish_quotes_languages))
524                 h_quotes_language = "polish";
525         // swedish
526         else if (is_known(h_language, known_swedish_quotes_languages))
527                 h_quotes_language = "swedish";
528         //english
529         else if (is_known(h_language, known_english_quotes_languages)
530                 || is_known(h_language, known_brazilian_languages)
531                 || is_known(h_language, known_portuguese_languages))
532                 h_quotes_language = "english";
533
534         h_language = babel2lyx(h_language);
535
536         // output the LyX file settings
537         os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
538            << "\\lyxformat " << LYX_FORMAT << '\n'
539            << "\\begin_document\n"
540            << "\\begin_header\n"
541            << "\\textclass " << h_textclass << "\n";
542         if (!h_preamble.str().empty())
543                 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
544         if (!h_options.empty())
545                 os << "\\options " << h_options << "\n";
546         os << "\\language " << h_language << "\n"
547            << "\\inputencoding " << h_inputencoding << "\n"
548            << "\\font_roman " << h_font_roman << "\n"
549            << "\\font_sans " << h_font_sans << "\n"
550            << "\\font_typewriter " << h_font_typewriter << "\n"
551            << "\\font_default_family " << h_font_default_family << "\n"
552            << "\\font_sc " << h_font_sc << "\n"
553            << "\\font_osf " << h_font_osf << "\n"
554            << "\\font_sf_scale " << h_font_sf_scale << "\n"
555            << "\\font_tt_scale " << h_font_tt_scale << "\n"
556            << "\\graphics " << h_graphics << "\n";
557         if (!h_float_placement.empty())
558                 os << "\\float_placement " << h_float_placement << "\n";
559         os << "\\paperfontsize " << h_paperfontsize << "\n"
560            << "\\spacing " << h_spacing << "\n"
561            << "\\use_hyperref " << h_use_hyperref << '\n';
562         if (h_use_hyperref == "1") {
563                 if (!h_pdf_title.empty())
564                         os << "\\pdf_title \"" << h_pdf_title << "\"\n";
565                 if (!h_pdf_author.empty())
566                         os << "\\pdf_author \"" << h_pdf_author << "\"\n";
567                 if (!h_pdf_subject.empty())
568                         os << "\\pdf_subject \"" << h_pdf_subject << "\"\n";
569                 if (!h_pdf_keywords.empty())
570                         os << "\\pdf_keywords \"" << h_pdf_keywords << "\"\n";
571                 os << "\\pdf_bookmarks " << h_pdf_bookmarks << "\n"
572                       "\\pdf_bookmarksnumbered " << h_pdf_bookmarksnumbered << "\n"
573                       "\\pdf_bookmarksopen " << h_pdf_bookmarksopen << "\n"
574                       "\\pdf_bookmarksopenlevel " << h_pdf_bookmarksopenlevel << "\n"
575                       "\\pdf_breaklinks " << h_pdf_breaklinks << "\n"
576                       "\\pdf_pdfborder " << h_pdf_pdfborder << "\n"
577                       "\\pdf_colorlinks " << h_pdf_colorlinks << "\n"
578                       "\\pdf_backref " << h_pdf_backref << "\n"
579                       "\\pdf_pagebackref " << h_pdf_pagebackref << "\n"
580                       "\\pdf_pdfusetitle " << h_pdf_pdfusetitle << '\n';
581                 if (!h_pdf_pagemode.empty())
582                         os << "\\pdf_pagemode " << h_pdf_pagemode << '\n';
583                 if (!h_pdf_quoted_options.empty())
584                         os << "\\pdf_quoted_options \"" << h_pdf_quoted_options << "\"\n";
585         }
586         os << "\\papersize " << h_papersize << "\n"
587            << "\\use_geometry " << h_use_geometry << "\n"
588            << "\\use_amsmath " << h_use_amsmath << "\n"
589            << "\\use_esint " << h_use_esint << "\n"
590            << "\\cite_engine " << h_cite_engine << "\n"
591            << "\\use_bibtopic " << h_use_bibtopic << "\n"
592            << "\\paperorientation " << h_paperorientation << "\n"
593            << h_margins
594            << "\\secnumdepth " << h_secnumdepth << "\n"
595            << "\\tocdepth " << h_tocdepth << "\n"
596            << "\\paragraph_separation " << h_paragraph_separation << "\n"
597            << "\\defskip " << h_defskip << "\n"
598            << "\\quotes_language " << h_quotes_language << "\n"
599            << "\\papercolumns " << h_papercolumns << "\n"
600            << "\\papersides " << h_papersides << "\n"
601            << "\\paperpagestyle " << h_paperpagestyle << "\n";
602         if (!h_listings_params.empty())
603                 os << "\\listings_params " << h_listings_params << "\n";
604         os << "\\tracking_changes " << h_tracking_changes << "\n"
605            << "\\output_changes " << h_output_changes << "\n"
606            << "\\end_header\n\n"
607            << "\\begin_body\n";
608         // clear preamble for subdocuments
609         h_preamble.str("");
610 }
611
612 } // anonymous namespace
613
614 void parse_preamble(Parser & p, ostream & os, 
615         string const & forceclass, TeX2LyXDocClass & tc)
616 {
617         // initialize fixed types
618         special_columns['D'] = 3;
619         bool is_full_document = false;
620         bool is_lyx_file = false;
621         bool in_lyx_preamble = false;
622
623         // determine whether this is a full document or a fragment for inclusion
624         while (p.good()) {
625                 Token const & t = p.get_token();
626
627                 if (t.cat() == catEscape && t.cs() == "documentclass") {
628                         is_full_document = true;
629                         break;
630                 }
631         }
632         p.reset();
633
634         while (is_full_document && p.good()) {
635                 Token const & t = p.get_token();
636
637 #ifdef FILEDEBUG
638                 cerr << "t: " << t << "\n";
639 #endif
640
641                 //
642                 // cat codes
643                 //
644                 if (!in_lyx_preamble &&
645                     (t.cat() == catLetter ||
646                      t.cat() == catSuper ||
647                      t.cat() == catSub ||
648                      t.cat() == catOther ||
649                      t.cat() == catMath ||
650                      t.cat() == catActive ||
651                      t.cat() == catBegin ||
652                      t.cat() == catEnd ||
653                      t.cat() == catAlign ||
654                      t.cat() == catParameter))
655                         h_preamble << t.cs();
656
657                 else if (!in_lyx_preamble && 
658                          (t.cat() == catSpace || t.cat() == catNewline))
659                         h_preamble << t.asInput();
660
661                 else if (t.cat() == catComment) {
662                         // regex to parse comments (currently not used)
663                         static regex const islyxfile("%% LyX .* created this file");
664                         static regex const usercommands("User specified LaTeX commands");
665
666                         string const comment = t.asInput();
667
668                         // magically switch encoding default if it looks like XeLaTeX
669                         static string const magicXeLaTeX =
670                                 "% This document must be compiled with XeLaTeX ";
671                         if (comment.size() > magicXeLaTeX.size() 
672                                   && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
673                                   && h_inputencoding == "auto") {
674                                 cerr << "XeLaTeX comment found, switching to UTF8\n";
675                                 h_inputencoding = "utf8";
676                         }
677                         smatch sub;
678                         if (regex_search(comment, sub, islyxfile)) {
679                                 is_lyx_file = true;
680                                 in_lyx_preamble = true;
681                         } else if (is_lyx_file
682                                    && regex_search(comment, sub, usercommands))
683                                 in_lyx_preamble = false;
684                         else if (!in_lyx_preamble)
685                                 h_preamble << t.asInput();
686                 }
687
688                 else if (t.cs() == "pagestyle")
689                         h_paperpagestyle = p.verbatim_item();
690
691                 else if (t.cs() == "makeatletter") {
692                         // LyX takes care of this
693                         p.setCatCode('@', catLetter);
694                 }
695
696                 else if (t.cs() == "makeatother") {
697                         // LyX takes care of this
698                         p.setCatCode('@', catOther);
699                 }
700
701                 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
702                             || t.cs() == "providecommand"
703                                 || t.cs() == "DeclareRobustCommand"
704                                 || t.cs() == "ProvideTextCommandDefault"
705                                 || t.cs() == "DeclareMathAccent") {
706                         bool star = false;
707                         if (p.next_token().character() == '*') {
708                                 p.get_token();
709                                 star = true;
710                         }
711                         string const name = p.verbatim_item();
712                         string const opt1 = p.getOpt();
713                         string const opt2 = p.getFullOpt();
714                         string const body = p.verbatim_item();
715                         // font settings
716                         if (name == "\\rmdefault")
717                                 if (is_known(body, known_roman_fonts))
718                                         h_font_roman = body;
719                         if (name == "\\sfdefault")
720                                 if (is_known(body, known_sans_fonts))
721                                         h_font_sans = body;
722                         if (name == "\\ttdefault")
723                                 if (is_known(body, known_typewriter_fonts))
724                                         h_font_typewriter = body;
725                         if (name == "\\familydefault") {
726                                 string family = body;
727                                 // remove leading "\"
728                                 h_font_default_family = family.erase(0,1);
729                         }
730                         // only non-lyxspecific stuff
731                         if (!in_lyx_preamble) {
732                                 ostringstream ss;
733                                 ss << '\\' << t.cs();
734                                 if (star)
735                                         ss << '*';
736                                 ss << '{' << name << '}' << opt1 << opt2
737                                    << '{' << body << "}";
738                                 h_preamble << ss.str();
739
740                                 // Add the command to the known commands
741                                 add_known_command(name, opt1, !opt2.empty());
742 /*
743                                 ostream & out = in_preamble ? h_preamble : os;
744                                 out << "\\" << t.cs() << "{" << name << "}"
745                                     << opts << "{" << body << "}";
746 */
747                         }
748                 }
749
750                 else if (t.cs() == "documentclass") {
751                         vector<string>::iterator it;
752                         vector<string> opts = split_options(p.getArg('[', ']'));
753                         handle_opt(opts, known_fontsizes, h_paperfontsize);
754                         delete_opt(opts, known_fontsizes);
755                         // delete "pt" at the end
756                         string::size_type i = h_paperfontsize.find("pt");
757                         if (i != string::npos)
758                                 h_paperfontsize.erase(i);
759                         // The documentclass options are always parsed before the options
760                         // of the babel call so that a language cannot overwrite the babel
761                         // options.
762                         handle_opt(opts, known_languages, h_language);
763                         delete_opt(opts, known_languages);
764                         
765                         // paper orientation
766                         if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
767                                 h_paperorientation = "landscape";
768                                 opts.erase(it);
769                         }
770                         // paper sides
771                         if ((it = find(opts.begin(), opts.end(), "oneside"))
772                                  != opts.end()) {
773                                 h_papersides = "1";
774                                 opts.erase(it);
775                         }
776                         if ((it = find(opts.begin(), opts.end(), "twoside"))
777                                  != opts.end()) {
778                                 h_papersides = "2";
779                                 opts.erase(it);
780                         }
781                         // paper columns
782                         if ((it = find(opts.begin(), opts.end(), "onecolumn"))
783                                  != opts.end()) {
784                                 h_papercolumns = "1";
785                                 opts.erase(it);
786                         }
787                         if ((it = find(opts.begin(), opts.end(), "twocolumn"))
788                                  != opts.end()) {
789                                 h_papercolumns = "2";
790                                 opts.erase(it);
791                         }
792                         // paper sizes
793                         // some size options are know to any document classes, other sizes
794                         // are handled by the \geometry command of the geometry package
795                         handle_opt(opts, known_class_paper_sizes, h_papersize);
796                         delete_opt(opts, known_class_paper_sizes);
797                         // the remaining options
798                         h_options = join(opts, ",");
799                         h_textclass = p.getArg('{', '}');
800                 }
801
802                 else if (t.cs() == "usepackage") {
803                         string const options = p.getArg('[', ']');
804                         string const name = p.getArg('{', '}');
805                         vector<string> vecnames;
806                         split(name, vecnames, ',');
807                         vector<string>::const_iterator it  = vecnames.begin();
808                         vector<string>::const_iterator end = vecnames.end();
809                         for (; it != end; ++it)
810                                 handle_package(p, trim(*it), options, 
811                                                in_lyx_preamble);
812                 }
813
814                 else if (t.cs() == "inputencoding") {
815                         string const encoding = p.getArg('{','}');
816                         h_inputencoding = encoding;
817                         p.setEncoding(encoding);
818                 }
819
820                 else if (t.cs() == "newenvironment") {
821                         string const name = p.getArg('{', '}');
822                         ostringstream ss;
823                         ss << "\\newenvironment{" << name << "}";
824                         ss << p.getOpt();
825                         ss << p.getOpt();
826                         ss << '{' << p.verbatim_item() << '}';
827                         ss << '{' << p.verbatim_item() << '}';
828                         if (!in_lyx_preamble)
829                                 h_preamble << ss.str();
830                 }
831
832                 else if (t.cs() == "def") {
833                         string name = p.get_token().cs();
834                         while (p.next_token().cat() != catBegin)
835                                 name += p.get_token().cs();
836                         if (!in_lyx_preamble)
837                                 h_preamble << "\\def\\" << name << '{'
838                                            << p.verbatim_item() << "}";
839                 }
840
841                 else if (t.cs() == "newcolumntype") {
842                         string const name = p.getArg('{', '}');
843                         trim(name);
844                         int nargs = 0;
845                         string opts = p.getOpt();
846                         if (!opts.empty()) {
847                                 istringstream is(string(opts, 1));
848                                 is >> nargs;
849                         }
850                         special_columns[name[0]] = nargs;
851                         h_preamble << "\\newcolumntype{" << name << "}";
852                         if (nargs)
853                                 h_preamble << "[" << nargs << "]";
854                         h_preamble << "{" << p.verbatim_item() << "}";
855                 }
856
857                 else if (t.cs() == "setcounter") {
858                         string const name = p.getArg('{', '}');
859                         string const content = p.getArg('{', '}');
860                         if (name == "secnumdepth")
861                                 h_secnumdepth = content;
862                         else if (name == "tocdepth")
863                                 h_tocdepth = content;
864                         else
865                                 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
866                 }
867
868                 else if (t.cs() == "setlength") {
869                         string const name = p.verbatim_item();
870                         string const content = p.verbatim_item();
871                         // the paragraphs are only not indented when \parindent is set to zero
872                         if (name == "\\parindent" && content != "") {
873                                 if (content[0] == '0')
874                                         h_paragraph_separation = "skip";
875                         } else if (name == "\\parskip") {
876                                 if (content == "\\smallskipamount")
877                                         h_defskip = "smallskip";
878                                 else if (content == "\\medskipamount")
879                                         h_defskip = "medskip";
880                                 else if (content == "\\bigskipamount")
881                                         h_defskip = "bigskip";
882                                 else
883                                         h_defskip = content;
884                         } else
885                                 h_preamble << "\\setlength{" << name << "}{" << content << "}";
886                 }
887
888                 else if (t.cs() == "onehalfspacing")
889                         h_spacing = "onehalf";
890
891                 else if (t.cs() == "doublespacing")
892                         h_spacing = "double";
893
894                 else if (t.cs() == "setstretch")
895                         h_spacing = "other " + p.verbatim_item();
896
897                 else if (t.cs() == "begin") {
898                         string const name = p.getArg('{', '}');
899                         if (name == "document")
900                                 break;
901                         h_preamble << "\\begin{" << name << "}";
902                 }
903
904                 else if (t.cs() == "geometry") {
905                         h_use_geometry = "true";
906                         vector<string> opts = split_options(p.getArg('{', '}'));
907                         vector<string>::iterator it;
908                         // paper orientation
909                         if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
910                                 h_paperorientation = "landscape";
911                                 opts.erase(it);
912                         }
913                         // paper size
914                         handle_opt(opts, known_paper_sizes, h_papersize);
915                         delete_opt(opts, known_paper_sizes);
916                         // page margins
917                         char const * const * margin = known_paper_margins;
918                         int k = -1;
919                         for (; *margin; ++margin) {
920                                 k += 1;
921                                 // search for the "=" in e.g. "lmargin=2cm" to get the value
922                                 for(size_t i = 0; i != opts.size(); i++) {
923                                         if (opts.at(i).find(*margin) != string::npos) {
924                                                 string::size_type pos = opts.at(i).find("=");
925                                                 string value = opts.at(i).substr(pos + 1);
926                                                 string name = known_coded_paper_margins[k];
927                                                 h_margins += "\\" + name + " " + value + "\n";
928                                         }
929                                 }
930                         }
931                 }
932
933                 else if (t.cs() == "jurabibsetup") {
934                         vector<string> jurabibsetup =
935                                 split_options(p.getArg('{', '}'));
936                         // add jurabibsetup to the jurabib package options
937                         add_package("jurabib", jurabibsetup);
938                         if (!jurabibsetup.empty()) {
939                                 h_preamble << "\\jurabibsetup{"
940                                            << join(jurabibsetup, ",") << '}';
941                         }
942                 }
943
944                 else if (!t.cs().empty() && !in_lyx_preamble)
945                         h_preamble << '\\' << t.cs();
946         }
947
948         // remove the whitespace
949         p.skip_spaces();
950
951         // Force textclass if the user wanted it
952         if (!forceclass.empty())
953                 h_textclass = forceclass;
954         if (noweb_mode && !prefixIs(h_textclass, "literate-"))
955                 h_textclass.insert(0, "literate-");
956         FileName layoutfilename = libFileSearch("layouts", h_textclass, "layout");
957         if (layoutfilename.empty()) {
958                 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
959                 exit(1);
960         }
961         tc.read(layoutfilename);
962         if (h_papersides.empty()) {
963                 ostringstream ss;
964                 ss << tc.sides();
965                 h_papersides = ss.str();
966         }
967         end_preamble(os, tc);
968 }
969
970 // }])
971
972
973 } // namespace lyx