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