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