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