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