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