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