]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/preamble.cpp
preamble.cpp: simplify code
[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                         if (opts == "ascii")
333                                 //change ascii to auto to be in the unicode range, see
334                                 //http://www.lyx.org/trac/ticket/4719
335                                 h_inputencoding = "auto";
336                         else if (!opts.empty())
337                                 h_inputencoding = opts;
338                 }
339                 if (!options.empty())
340                         p.setEncoding(options.back());
341                 options.clear();
342         }
343
344         else if (name == "makeidx")
345                 ; // ignore this
346
347         else if (name == "prettyref")
348                 ; // ignore this
349
350         else if (name == "varioref")
351                 ; // ignore this
352
353         else if (name == "verbatim")
354                 ; // ignore this
355
356         else if (name == "nomencl")
357                 ; // ignore this
358
359         else if (name == "textcomp")
360                 ; // ignore this
361
362         else if (name == "url")
363                 ; // ignore this
364
365         else if (name == "color") {
366                 // with the following command this package is only loaded when needed for
367                 // undefined colors, since we only support the predefined colors
368                 h_preamble << "\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n";
369         }
370
371         else if (name == "graphicx")
372                 ; // ignore this
373
374         else if (name == "setspace")
375                 ; // ignore this
376
377         else if (name == "geometry")
378                 ; // Ignore this, the geometry settings are made by the \geometry
379                   // command. This command is handled below.
380
381         else if (is_known(name, known_languages))
382                 h_language = name;
383
384         else if (name == "natbib") {
385                 h_cite_engine = "natbib_authoryear";
386                 vector<string>::iterator it =
387                         find(options.begin(), options.end(), "authoryear");
388                 if (it != options.end())
389                         options.erase(it);
390                 else {
391                         it = find(options.begin(), options.end(), "numbers");
392                         if (it != options.end()) {
393                                 h_cite_engine = "natbib_numerical";
394                                 options.erase(it);
395                         }
396                 }
397         }
398
399         else if (name == "jurabib")
400                 h_cite_engine = "jurabib";
401
402         else if (!in_lyx_preamble) {
403                 if (options.empty())
404                         h_preamble << "\\usepackage{" << name << "}";
405                 else {
406                         h_preamble << "\\usepackage[" << opts << "]{" 
407                                    << name << "}";
408                         options.clear();
409                 }
410         }
411
412         // We need to do something with the options...
413         if (!options.empty())
414                 cerr << "Ignoring options '" << join(options, ",")
415                      << "' of package " << name << '.' << endl;
416
417         // remove the whitespace
418         p.skip_spaces();
419 }
420
421
422
423 void end_preamble(ostream & os, TextClass const & /*textclass*/)
424 {
425         // merge synonym languages
426         if (is_known(h_language, known_brazilian_languages))
427                 h_language = "brazilian";
428         else if (is_known(h_language, known_french_languages))
429                 h_language = "french";
430         else if (is_known(h_language, known_german_languages))
431                 h_language = "german";
432         else if (is_known(h_language, known_ngerman_languages))
433                 h_language = "ngerman";
434         else if (is_known(h_language, known_portuguese_languages))
435                 h_language = "portuguese";
436         else if (is_known(h_language, known_russian_languages))
437                 h_language = "russian";
438         else if (is_known(h_language, known_ukrainian_languages))
439                 h_language = "ukrainian";
440
441         // set the quote language
442         // LyX only knows the following quotes languages:
443         // english, swedish, german, polish, french and danish
444         // english is already set as default
445         // FIXME: for a real solution we need a list what language use
446         // what quote style
447         if (h_language == "swedish" || h_language == "german"
448                 || h_language == "polish" || h_language == "french"
449                 || h_language == "danish")
450                 h_quotes_language = h_language;
451         // there is only the quotes language "german"
452         if (h_language == "ngerman")
453                 h_quotes_language = "german";
454
455         // output the LyX file settings
456         os << "#LyX file created by tex2lyx " << PACKAGE_VERSION << "\n"
457            << "\\lyxformat 264\n"
458            << "\\begin_document\n"
459            << "\\begin_header\n"
460            << "\\textclass " << h_textclass << "\n";
461         if (!h_preamble.str().empty())
462                 os << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
463         if (!h_options.empty())
464                 os << "\\options " << h_options << "\n";
465         os << "\\language " << h_language << "\n"
466            << "\\inputencoding " << h_inputencoding << "\n"
467            << "\\font_roman " << h_font_roman << "\n"
468            << "\\font_sans " << h_font_sans << "\n"
469            << "\\font_typewriter " << h_font_typewriter << "\n"
470            << "\\font_default_family " << h_font_default_family << "\n"
471            << "\\font_sc " << h_font_sc << "\n"
472            << "\\font_osf " << h_font_osf << "\n"
473            << "\\font_sf_scale " << h_font_sf_scale << "\n"
474            << "\\font_tt_scale " << h_font_tt_scale << "\n"
475            << "\\graphics " << h_graphics << "\n"
476            << "\\paperfontsize " << h_paperfontsize << "\n"
477            << "\\spacing " << h_spacing << "\n"
478            << "\\papersize " << h_papersize << "\n"
479            << "\\use_geometry " << h_use_geometry << "\n"
480            << "\\use_amsmath " << h_use_amsmath << "\n"
481            << "\\use_esint " << h_use_esint << "\n"
482            << "\\cite_engine " << h_cite_engine << "\n"
483            << "\\use_bibtopic " << h_use_bibtopic << "\n"
484            << "\\paperorientation " << h_paperorientation << "\n"
485            << h_margins
486            << "\\secnumdepth " << h_secnumdepth << "\n"
487            << "\\tocdepth " << h_tocdepth << "\n"
488            << "\\paragraph_separation " << h_paragraph_separation << "\n"
489            << "\\defskip " << h_defskip << "\n"
490            << "\\quotes_language " << h_quotes_language << "\n"
491            << "\\papercolumns " << h_papercolumns << "\n"
492            << "\\papersides " << h_papersides << "\n"
493            << "\\paperpagestyle " << h_paperpagestyle << "\n"
494            << "\\tracking_changes " << h_tracking_changes << "\n"
495            << "\\output_changes " << h_output_changes << "\n"
496            << "\\end_header\n\n"
497            << "\\begin_body\n";
498         // clear preamble for subdocuments
499         h_preamble.str("");
500 }
501
502 } // anonymous namespace
503
504 void parse_preamble(Parser & p, ostream & os, 
505         string const & forceclass, TeX2LyXDocClass & tc)
506 {
507         // initialize fixed types
508         special_columns['D'] = 3;
509         bool is_full_document = false;
510         bool is_lyx_file = false;
511         bool in_lyx_preamble = false;
512
513         // determine whether this is a full document or a fragment for inclusion
514         while (p.good()) {
515                 Token const & t = p.get_token();
516
517                 if (t.cat() == catEscape && t.cs() == "documentclass") {
518                         is_full_document = true;
519                         break;
520                 }
521         }
522         p.reset();
523
524         while (is_full_document && p.good()) {
525                 Token const & t = p.get_token();
526
527 #ifdef FILEDEBUG
528                 cerr << "t: " << t << "\n";
529 #endif
530
531                 //
532                 // cat codes
533                 //
534                 if (!in_lyx_preamble &&
535                     (t.cat() == catLetter ||
536                      t.cat() == catSuper ||
537                      t.cat() == catSub ||
538                      t.cat() == catOther ||
539                      t.cat() == catMath ||
540                      t.cat() == catActive ||
541                      t.cat() == catBegin ||
542                      t.cat() == catEnd ||
543                      t.cat() == catAlign ||
544                      t.cat() == catParameter))
545                         h_preamble << t.cs();
546
547                 else if (!in_lyx_preamble && 
548                          (t.cat() == catSpace || t.cat() == catNewline))
549                         h_preamble << t.asInput();
550
551                 else if (t.cat() == catComment) {
552                         // regex to parse comments (currently not used)
553                         static regex const islyxfile("%% LyX .* created this file");
554                         static regex const usercommands("User specified LaTeX commands");
555
556                         string const comment = t.asInput();
557
558                         // magically switch encoding default if it looks like XeLaTeX
559                         static string const magicXeLaTeX =
560                                 "% This document must be compiled with XeLaTeX ";
561                         if (comment.size() > magicXeLaTeX.size() 
562                                   && comment.substr(0, magicXeLaTeX.size()) == magicXeLaTeX
563                                   && h_inputencoding == "auto") {
564                                 cerr << "XeLaTeX comment found, switching to UTF8\n";
565                                 h_inputencoding = "utf8";
566                         }
567                         smatch sub;
568                         if (regex_search(comment, sub, islyxfile)) {
569                                 is_lyx_file = true;
570                                 in_lyx_preamble = true;
571                         } else if (is_lyx_file
572                                    && regex_search(comment, sub, usercommands))
573                                 in_lyx_preamble = false;
574                         else if (!in_lyx_preamble)
575                                 h_preamble << t.asInput();
576                 }
577
578                 else if (t.cs() == "pagestyle")
579                         h_paperpagestyle = p.verbatim_item();
580
581                 else if (t.cs() == "makeatletter") {
582                         // LyX takes care of this
583                         p.setCatCode('@', catLetter);
584                 }
585
586                 else if (t.cs() == "makeatother") {
587                         // LyX takes care of this
588                         p.setCatCode('@', catOther);
589                 }
590
591                 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
592                             || t.cs() == "providecommand"
593                                 || t.cs() == "DeclareRobustCommand"
594                                 || t.cs() == "ProvideTextCommandDefault"
595                                 || t.cs() == "DeclareMathAccent") {
596                         bool star = false;
597                         if (p.next_token().character() == '*') {
598                                 p.get_token();
599                                 star = true;
600                         }
601                         string const name = p.verbatim_item();
602                         string const opt1 = p.getOpt();
603                         string const opt2 = p.getFullOpt();
604                         string const body = p.verbatim_item();
605                         // font settings
606                         if (name == "\\rmdefault")
607                                 if (is_known(body, known_roman_fonts))
608                                         h_font_roman = body;
609                         if (name == "\\sfdefault")
610                                 if (is_known(body, known_sans_fonts))
611                                         h_font_sans = body;
612                         if (name == "\\ttdefault")
613                                 if (is_known(body, known_typewriter_fonts))
614                                         h_font_typewriter = body;
615                         if (name == "\\familydefault") {
616                                 string family = body;
617                                 // remove leading "\"
618                                 h_font_default_family = family.erase(0,1);
619                         }
620                         // only non-lyxspecific stuff
621                         if (!in_lyx_preamble) {
622                                 ostringstream ss;
623                                 ss << '\\' << t.cs();
624                                 if (star)
625                                         ss << '*';
626                                 ss << '{' << name << '}' << opt1 << opt2
627                                    << '{' << body << "}";
628                                 h_preamble << ss.str();
629
630                                 // Add the command to the known commands
631                                 add_known_command(name, opt1, !opt2.empty());
632 /*
633                                 ostream & out = in_preamble ? h_preamble : os;
634                                 out << "\\" << t.cs() << "{" << name << "}"
635                                     << opts << "{" << body << "}";
636 */
637                         }
638                 }
639
640                 else if (t.cs() == "documentclass") {
641                         vector<string>::iterator it;
642                         vector<string> opts = split_options(p.getArg('[', ']'));
643                         handle_opt(opts, known_fontsizes, h_paperfontsize);
644                         delete_opt(opts, known_fontsizes);
645                         // delete "pt" at the end
646                         string::size_type i = h_paperfontsize.find("pt");
647                         if (i != string::npos)
648                                 h_paperfontsize.erase(i);
649                         // The documentclass options are always parsed before the options
650                         // of the babel call so that a language cannot overwrite the babel
651                         // options.
652                         handle_opt(opts, known_languages, h_language);
653                         delete_opt(opts, known_languages);
654                         
655                         // paper orientation
656                         if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
657                                 h_paperorientation = "landscape";
658                                 opts.erase(it);
659                         }
660                         // paper sides
661                         if ((it = find(opts.begin(), opts.end(), "oneside"))
662                                  != opts.end()) {
663                                 h_papersides = "1";
664                                 opts.erase(it);
665                         }
666                         if ((it = find(opts.begin(), opts.end(), "twoside"))
667                                  != opts.end()) {
668                                 h_papersides = "2";
669                                 opts.erase(it);
670                         }
671                         // paper columns
672                         if ((it = find(opts.begin(), opts.end(), "onecolumn"))
673                                  != opts.end()) {
674                                 h_papercolumns = "1";
675                                 opts.erase(it);
676                         }
677                         if ((it = find(opts.begin(), opts.end(), "twocolumn"))
678                                  != opts.end()) {
679                                 h_papercolumns = "2";
680                                 opts.erase(it);
681                         }
682                         // paper sizes
683                         // some size options are know to any document classes, other sizes
684                         // are handled by the \geometry command of the geometry package
685                         handle_opt(opts, known_class_paper_sizes, h_papersize);
686                         delete_opt(opts, known_class_paper_sizes);
687                         // the remaining options
688                         h_options = join(opts, ",");
689                         h_textclass = p.getArg('{', '}');
690                 }
691
692                 else if (t.cs() == "usepackage") {
693                         string const options = p.getArg('[', ']');
694                         string const name = p.getArg('{', '}');
695                         vector<string> vecnames;
696                         split(name, vecnames, ',');
697                         vector<string>::const_iterator it  = vecnames.begin();
698                         vector<string>::const_iterator end = vecnames.end();
699                         for (; it != end; ++it)
700                                 handle_package(p, trim(*it), options, 
701                                                in_lyx_preamble);
702                 }
703
704                 else if (t.cs() == "inputencoding") {
705                         string const encoding = p.getArg('{','}');
706                         h_inputencoding = encoding;
707                         p.setEncoding(encoding);
708                 }
709
710                 else if (t.cs() == "newenvironment") {
711                         string const name = p.getArg('{', '}');
712                         ostringstream ss;
713                         ss << "\\newenvironment{" << name << "}";
714                         ss << p.getOpt();
715                         ss << p.getOpt();
716                         ss << '{' << p.verbatim_item() << '}';
717                         ss << '{' << p.verbatim_item() << '}';
718                         if (!in_lyx_preamble)
719                                 h_preamble << ss.str();
720                 }
721
722                 else if (t.cs() == "def") {
723                         string name = p.get_token().cs();
724                         while (p.next_token().cat() != catBegin)
725                                 name += p.get_token().cs();
726                         if (!in_lyx_preamble)
727                                 h_preamble << "\\def\\" << name << '{'
728                                            << p.verbatim_item() << "}";
729                 }
730
731                 else if (t.cs() == "newcolumntype") {
732                         string const name = p.getArg('{', '}');
733                         trim(name);
734                         int nargs = 0;
735                         string opts = p.getOpt();
736                         if (!opts.empty()) {
737                                 istringstream is(string(opts, 1));
738                                 is >> nargs;
739                         }
740                         special_columns[name[0]] = nargs;
741                         h_preamble << "\\newcolumntype{" << name << "}";
742                         if (nargs)
743                                 h_preamble << "[" << nargs << "]";
744                         h_preamble << "{" << p.verbatim_item() << "}";
745                 }
746
747                 else if (t.cs() == "setcounter") {
748                         string const name = p.getArg('{', '}');
749                         string const content = p.getArg('{', '}');
750                         if (name == "secnumdepth")
751                                 h_secnumdepth = content;
752                         else if (name == "tocdepth")
753                                 h_tocdepth = content;
754                         else
755                                 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
756                 }
757
758                 else if (t.cs() == "setlength") {
759                         string const name = p.verbatim_item();
760                         string const content = p.verbatim_item();
761                         // the paragraphs are only not indented when \parindent is set to zero
762                         if (name == "\\parindent" && content != "") {
763                                 if (content[0] == '0')
764                                         h_paragraph_separation = "skip";
765                         } else if (name == "\\parskip") {
766                                 if (content == "\\smallskipamount")
767                                         h_defskip = "smallskip";
768                                 else if (content == "\\medskipamount")
769                                         h_defskip = "medskip";
770                                 else if (content == "\\bigskipamount")
771                                         h_defskip = "bigskip";
772                                 else
773                                         h_defskip = content;
774                         } else
775                                 h_preamble << "\\setlength{" << name << "}{" << content << "}";
776                 }
777
778                 else if (t.cs() == "onehalfspacing")
779                         h_spacing = "onehalf";
780
781                 else if (t.cs() == "doublespacing")
782                         h_spacing = "double";
783
784                 else if (t.cs() == "setstretch")
785                         h_spacing = "other " + p.verbatim_item();
786
787                 else if (t.cs() == "begin") {
788                         string const name = p.getArg('{', '}');
789                         if (name == "document")
790                                 break;
791                         h_preamble << "\\begin{" << name << "}";
792                 }
793
794                 else if (t.cs() == "geometry") {
795                         h_use_geometry = "true";
796                         vector<string> opts = split_options(p.getArg('{', '}'));
797                         vector<string>::iterator it;
798                         // paper orientation
799                         if ((it = find(opts.begin(), opts.end(), "landscape")) != opts.end()) {
800                                 h_paperorientation = "landscape";
801                                 opts.erase(it);
802                         }
803                         // paper size
804                         handle_opt(opts, known_paper_sizes, h_papersize);
805                         delete_opt(opts, known_paper_sizes);
806                         // page margins
807                         char const * const * margin = known_paper_margins;
808                         int k = -1;
809                         for (; *margin; ++margin) {
810                                 k += 1;
811                                 // search for the "=" in e.g. "lmargin=2cm" to get the value
812                                 for(size_t i = 0; i != opts.size(); i++) {
813                                         if (opts.at(i).find(*margin) != string::npos) {
814                                                 string::size_type pos = opts.at(i).find("=");
815                                                 string value = opts.at(i).substr(pos + 1);
816                                                 string name = known_coded_paper_margins[k];
817                                                 h_margins += "\\" + name + " " + value + "\n";
818                                         }
819                                 }
820                         }
821                 }
822
823                 else if (t.cs() == "jurabibsetup") {
824                         vector<string> jurabibsetup =
825                                 split_options(p.getArg('{', '}'));
826                         // add jurabibsetup to the jurabib package options
827                         add_package("jurabib", jurabibsetup);
828                         if (!jurabibsetup.empty()) {
829                                 h_preamble << "\\jurabibsetup{"
830                                            << join(jurabibsetup, ",") << '}';
831                         }
832                 }
833
834                 else if (!t.cs().empty() && !in_lyx_preamble)
835                         h_preamble << '\\' << t.cs();
836
837                 // remove the whitespace
838                 p.skip_spaces();
839         }
840
841         // remove the whitespace
842         p.skip_spaces();
843
844         // Force textclass if the user wanted it
845         if (!forceclass.empty())
846                 h_textclass = forceclass;
847         if (noweb_mode && !prefixIs(h_textclass, "literate-"))
848                 h_textclass.insert(0, "literate-");
849         FileName layoutfilename = libFileSearch("layouts", h_textclass, "layout");
850         if (layoutfilename.empty()) {
851                 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
852                 exit(1);
853         }
854         tc.read(layoutfilename);
855         if (h_papersides.empty()) {
856                 ostringstream ss;
857                 ss << tc.sides();
858                 h_papersides = ss.str();
859         }
860         end_preamble(os, tc);
861 }
862
863 // }])
864
865
866 } // namespace lyx