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