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