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