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