]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/preamble.C
The package reworking.
[lyx.git] / src / tex2lyx / preamble.C
1 /**
2  * \file preamble.C
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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 // {[(
12
13 #include <config.h>
14
15 #include "tex2lyx.h"
16
17 #include "layout.h"
18 #include "lyxtextclass.h"
19 #include "lyxlex.h"
20 #include "support/filetools.h"
21
22 #include <algorithm>
23 #include <iostream>
24 #include <sstream>
25 #include <string>
26 #include <vector>
27 #include <map>
28
29 using std::istringstream;
30 using std::ostream;
31 using std::ostringstream;
32 using std::string;
33 using std::vector;
34 using std::cerr;
35 using std::endl;
36
37 using lyx::support::LibFileSearch;
38
39 // special columntypes
40 extern std::map<char, int> special_columns;
41
42 std::map<string, vector<string> > used_packages;
43
44 namespace {
45
46 const char * const known_languages[] = { "austrian", "babel", "bahasa",
47 "basque", "breton", "british", "bulgarian", "catalan", "croatian", "czech",
48 "danish", "dutch", "english", "esperanto", "estonian", "finnish", "francais",
49 "frenchb", "galician", "german", "germanb", "greek", "hebcal", "hebfont",
50 "hebrew", "hebrew_newcode", "hebrew_oldcode", "hebrew_p", "hyphen",
51 "icelandic", "irish", "italian", "latin", "lgrcmr", "lgrcmro", "lgrcmss",
52 "lgrcmtt", "lgrenc", "lgrlcmss", "lgrlcmtt", "lheclas", "lhecmr",
53 "lhecmss", "lhecmtt", "lhecrml", "lheenc", "lhefr", "lheredis", "lheshold",
54 "lheshscr", "lheshstk", "lsorbian", "magyar", "naustrian", "ngermanb",
55 "ngerman", "norsk", "polish", "portuges", "rlbabel", "romanian",
56 "russianb", "samin", "scottish", "serbian", "slovak", "slovene", "spanish",
57 "swedish", "turkish", "ukraineb", "usorbian", "welsh", 0};
58
59 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
60
61 // some ugly stuff
62 ostringstream h_preamble;
63 string h_textclass               = "article";
64 string h_options                 = string();
65 string h_language                = "english";
66 string h_inputencoding           = "latin1";
67 string h_fontscheme              = "default";
68 string h_graphics                = "default";
69 string h_paperfontsize           = "default";
70 string h_spacing                 = "single";
71 string h_papersize               = "default";
72 string h_paperpackage            = "none";
73 string h_use_geometry            = "false";
74 string h_use_amsmath             = "0";
75 string h_cite_engine             = "basic";
76 string h_use_bibtopic            = "false";
77 string h_paperorientation        = "portrait";
78 string h_secnumdepth             = "3";
79 string h_tocdepth                = "3";
80 string h_paragraph_separation    = "indent";
81 string h_defskip                 = "medskip";
82 string h_quotes_language         = "english";
83 string h_quotes_times            = "2";
84 string h_papercolumns            = "1";
85 string h_papersides              = string();
86 string h_paperpagestyle          = "default";
87 string h_tracking_changes        = "false";
88
89
90 void handle_opt(vector<string> & opts, char const * const * what, string & target)
91 {
92         if (opts.empty())
93                 return;
94
95         for ( ; *what; ++what) {
96                 vector<string>::iterator it = find(opts.begin(), opts.end(), *what);
97                 if (it != opts.end()) {
98                         //cerr << "### found option '" << *what << "'\n";
99                         target = *what;
100                         opts.erase(it);
101                         return;
102                 }
103         }
104 }
105
106
107 /*!
108  * Split a package options string (keyval format) into a vector.
109  * Example input:
110  *   authorformat=smallcaps,
111  *   commabeforerest,
112  *   titleformat=colonsep,
113  *   bibformat={tabular,ibidem,numbered}
114  */
115 vector<string> split_options(string const & input)
116 {
117         vector<string> options;
118         string option;
119         Parser p(input);
120         while (p.good()) {
121                 Token const & t = p.get_token();
122                 if (t.asInput() == ",") {
123                         options.push_back(option);
124                         option.erase();
125                 } else if (t.asInput() == "=") {
126                         option += '=';
127                         p.skip_spaces(true);
128                         if (p.next_token().asInput() == "{")
129                                 option += '{' + p.getArg('{', '}') + '}';
130                 } else if (t.cat() != catSpace)
131                         option += t.asInput();
132         }
133
134         if (!option.empty())
135                 options.push_back(option);
136
137         return options;
138 }
139
140
141 /*!
142  * Add package \p name with options \p options to used_packages.
143  * Remove options from \p options that we don't want to output.
144  */
145 void add_package(string const & name, vector<string> & options)
146 {
147         // every package inherits the global options
148         if (used_packages.find(name) == used_packages.end())
149                 used_packages[name] = split_options(h_options);
150
151         vector<string> & v = used_packages[name];
152         v.insert(v.end(), options.begin(), options.end());
153         if (name == "jurabib") {
154                 // Don't output the order argument (see the cite command
155                 // handling code in text.C).
156                 vector<string>::iterator end =
157                         remove(options.begin(), options.end(), "natbiborder");
158                 end = remove(options.begin(), end, "jurabiborder");
159                 options.erase(end, options.end());
160         }
161 }
162
163
164 void handle_package(string const & name, string const & opts)
165 {
166         vector<string> options = split_options(opts);
167         add_package(name, options);
168
169         //cerr << "handle_package: '" << name << "'\n";
170         if (name == "a4wide") {
171                 h_papersize = "a4paper";
172                 h_paperpackage = "widemarginsa4";
173         } else if (name == "ae")
174                 h_fontscheme = "ae";
175         else if (name == "aecompl")
176                 h_fontscheme = "ae";
177         else if (name == "amsmath")
178                 h_use_amsmath = "1";
179         else if (name == "amssymb")
180                 h_use_amsmath = "1";
181         else if (name == "babel")
182                 ; // ignore this
183         else if (name == "fontenc")
184                 ; // ignore this
185         else if (name == "inputenc") {
186                 h_inputencoding = opts;
187                 options.clear();
188         } else if (name == "makeidx")
189                 ; // ignore this
190         else if (name == "verbatim")
191                 ; // ignore this
192         else if (is_known(name, known_languages)) {
193                 h_language = name;
194                 h_quotes_language = name;
195         } else if (name == "natbib") {
196                 h_cite_engine = "natbib_authoryear";
197                 vector<string>::iterator it =
198                         find(options.begin(), options.end(), "authoryear");
199                 if (it != options.end())
200                         options.erase(it);
201                 else {
202                         it = find(options.begin(), options.end(), "numbers");
203                         if (it != options.end()) {
204                                 h_cite_engine = "natbib_numerical";
205                                 options.erase(it);
206                         }
207                 }
208         } else if (name == "jurabib") {
209                 h_cite_engine = "jurabib";
210         } else if (options.empty())
211                 h_preamble << "\\usepackage{" << name << "}\n";
212         else {
213                 h_preamble << "\\usepackage[" << opts << "]{" << name << "}\n";
214                 options.clear();
215         }
216
217         // We need to do something with the options...
218         if (!options.empty())
219                 cerr << "Ignoring options '" << join(options, ",")
220                      << "' of package " << name << '.' << endl;
221 }
222
223
224
225 void end_preamble(ostream & os, LyXTextClass const & /*textclass*/)
226 {
227         os << "#LyX file created by  tex2lyx 0.1.2\n"
228            << "\\lyxformat 237\n"
229            << "\\begin_document\n"
230            << "\\begin_header\n"
231            << "\\textclass " << h_textclass << "\n"
232            << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n";
233         if (!h_options.empty())
234            os << "\\options " << h_options << "\n";
235         os << "\\language " << h_language << "\n"
236            << "\\inputencoding " << h_inputencoding << "\n"
237            << "\\fontscheme " << h_fontscheme << "\n"
238            << "\\graphics " << h_graphics << "\n"
239            << "\\paperfontsize " << h_paperfontsize << "\n"
240            << "\\spacing " << h_spacing << "\n"
241            << "\\papersize " << h_papersize << "\n"
242            << "\\paperpackage " << h_paperpackage << "\n"
243            << "\\use_geometry " << h_use_geometry << "\n"
244            << "\\use_amsmath " << h_use_amsmath << "\n"
245            << "\\cite_engine " << h_cite_engine << "\n"
246            << "\\use_bibtopic " << h_use_bibtopic << "\n"
247            << "\\paperorientation " << h_paperorientation << "\n"
248            << "\\secnumdepth " << h_secnumdepth << "\n"
249            << "\\tocdepth " << h_tocdepth << "\n"
250            << "\\paragraph_separation " << h_paragraph_separation << "\n"
251            << "\\defskip " << h_defskip << "\n"
252            << "\\quotes_language " << h_quotes_language << "\n"
253            << "\\quotes_times " << h_quotes_times << "\n"
254            << "\\papercolumns " << h_papercolumns << "\n"
255            << "\\papersides " << h_papersides << "\n"
256            << "\\paperpagestyle " << h_paperpagestyle << "\n"
257            << "\\tracking_changes " << h_tracking_changes << "\n"
258            << "\\end_header\n\n"
259            << "\\begin_body\n";
260         // clear preamble for subdocuments
261         h_preamble.str("");
262 }
263
264 } // anonymous namespace
265
266 LyXTextClass const parse_preamble(Parser & p, ostream & os, string const & forceclass)
267 {
268         // initialize fixed types
269         special_columns['D'] = 3;
270         bool is_full_document = false;
271
272         // determine whether this is a full document or a fragment for inclusion
273         while (p.good()) {
274                 Token const & t = p.get_token();
275
276                 if (t.cat() == catEscape && t.cs() == "documentclass") {
277                         is_full_document = true;
278                         break;
279                 }
280         }
281         p.reset();
282
283         while (is_full_document && p.good()) {
284                 Token const & t = p.get_token();
285
286 #ifdef FILEDEBUG
287                 cerr << "t: " << t << "\n";
288 #endif
289
290                 //
291                 // cat codes
292                 //
293                 if (t.cat() == catLetter ||
294                           t.cat() == catSuper ||
295                           t.cat() == catSub ||
296                           t.cat() == catOther ||
297                           t.cat() == catMath ||
298                           t.cat() == catActive ||
299                           t.cat() == catBegin ||
300                           t.cat() == catEnd ||
301                           t.cat() == catAlign ||
302                           t.cat() == catParameter)
303                 h_preamble << t.character();
304
305                 else if (t.cat() == catSpace || t.cat() == catNewline)
306                         h_preamble << t.asInput();
307
308                 else if (t.cat() == catComment)
309                         h_preamble << t.asInput();
310
311                 else if (t.cs() == "pagestyle")
312                         h_paperpagestyle = p.verbatim_item();
313
314                 else if (t.cs() == "makeatletter") {
315                         p.setCatCode('@', catLetter);
316                         h_preamble << "\\makeatletter";
317                 }
318
319                 else if (t.cs() == "makeatother") {
320                         p.setCatCode('@', catOther);
321                         h_preamble << "\\makeatother";
322                 }
323
324                 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
325                             || t.cs() == "providecommand") {
326                         bool star = false;
327                         if (p.next_token().character() == '*') {
328                                 p.get_token();
329                                 star = true;
330                         }
331                         string const name = p.verbatim_item();
332                         string const opt1 = p.getOpt();
333                         string const opt2 = p.getFullOpt();
334                         string const body = p.verbatim_item();
335                         // only non-lyxspecific stuff
336                         if (   name != "\\noun"
337                             && name != "\\tabularnewline"
338                             && name != "\\LyX"
339                             && name != "\\lyxline"
340                             && name != "\\lyxaddress"
341                             && name != "\\lyxrightaddress"
342                             && name != "\\lyxdot"
343                             && name != "\\boldsymbol"
344                             && name != "\\lyxarrow") {
345                                 ostringstream ss;
346                                 ss << '\\' << t.cs();
347                                 if (star)
348                                         ss << '*';
349                                 ss << '{' << name << '}' << opt1 << opt2
350                                    << '{' << body << "}";
351                                 h_preamble << ss.str();
352
353                                 // Add the command to the known commands
354                                 add_known_command(name, opt1, !opt2.empty());
355 /*
356                                 ostream & out = in_preamble ? h_preamble : os;
357                                 out << "\\" << t.cs() << "{" << name << "}"
358                                     << opts << "{" << body << "}";
359 */
360                         }
361                 }
362
363                 else if (t.cs() == "documentclass") {
364                         vector<string> opts;
365                         split(p.getArg('[', ']'), opts, ',');
366                         handle_opt(opts, known_languages, h_language);
367                         handle_opt(opts, known_fontsizes, h_paperfontsize);
368                         h_quotes_language = h_language;
369                         h_options = join(opts, ",");
370                         h_textclass = p.getArg('{', '}');
371                 }
372
373                 else if (t.cs() == "usepackage") {
374                         string const options = p.getArg('[', ']');
375                         string const name = p.getArg('{', '}');
376                         if (options.empty() && name.find(',')) {
377                                 vector<string> vecnames;
378                                 split(name, vecnames, ',');
379                                 vector<string>::const_iterator it  = vecnames.begin();
380                                 vector<string>::const_iterator end = vecnames.end();
381                                 for (; it != end; ++it)
382                                         handle_package(trim(*it), string());
383                         } else {
384                                 handle_package(name, options);
385                         }
386                 }
387
388                 else if (t.cs() == "newenvironment") {
389                         string const name = p.getArg('{', '}');
390                         ostringstream ss;
391                         ss << "\\newenvironment{" << name << "}";
392                         ss << p.getOpt();
393                         ss << p.getOpt();
394                         ss << '{' << p.verbatim_item() << '}';
395                         ss << '{' << p.verbatim_item() << '}';
396                         if (name != "lyxcode" && name != "lyxlist"
397                                         && name != "lyxrightadress" && name != "lyxaddress")
398                                 h_preamble << ss.str();
399                 }
400
401                 else if (t.cs() == "def") {
402                         string name = p.get_token().cs();
403                         while (p.next_token().cat() != catBegin)
404                                 name += p.get_token().asString();
405                         h_preamble << "\\def\\" << name << '{' << p.verbatim_item() << "}";
406                 }
407
408                 else if (t.cs() == "newcolumntype") {
409                         string const name = p.getArg('{', '}');
410                         trim(name);
411                         int nargs = 0;
412                         string opts = p.getOpt();
413                         if (!opts.empty()) {
414                                 istringstream is(string(opts, 1));
415                                 //cerr << "opt: " << is.str() << "\n";
416                                 is >> nargs;
417                         }
418                         special_columns[name[0]] = nargs;
419                         h_preamble << "\\newcolumntype{" << name << "}";
420                         if (nargs)
421                                 h_preamble << "[" << nargs << "]";
422                         h_preamble << "{" << p.verbatim_item() << "}";
423                 }
424
425                 else if (t.cs() == "setcounter") {
426                         string const name = p.getArg('{', '}');
427                         string const content = p.getArg('{', '}');
428                         if (name == "secnumdepth")
429                                 h_secnumdepth = content;
430                         else if (name == "tocdepth")
431                                 h_tocdepth = content;
432                         else
433                                 h_preamble << "\\setcounter{" << name << "}{" << content << "}";
434                 }
435
436                 else if (t.cs() == "setlength") {
437                         string const name = p.verbatim_item();
438                         string const content = p.verbatim_item();
439                         // Is this correct?
440                         if (name == "parskip")
441                                 h_paragraph_separation = "skip";
442                         else if (name == "parindent")
443                                 h_paragraph_separation = "skip";
444                         else
445                                 h_preamble << "\\setlength{" << name << "}{" << content << "}";
446                 }
447
448                 else if (t.cs() == "begin") {
449                         string const name = p.getArg('{', '}');
450                         if (name == "document")
451                                 break;
452                         h_preamble << "\\begin{" << name << "}";
453                 }
454
455                 else if (t.cs() == "jurabibsetup") {
456                         vector<string> jurabibsetup =
457                                 split_options(p.getArg('{', '}'));
458                         // add jurabibsetup to the jurabib package options
459                         add_package("jurabib", jurabibsetup);
460                         if (!jurabibsetup.empty()) {
461                                 h_preamble << "\\jurabibsetup{"
462                                            << join(jurabibsetup, ",") << '}';
463                         }
464                 }
465
466                 else if (!t.cs().empty())
467                         h_preamble << '\\' << t.cs();
468         }
469         p.skip_spaces();
470
471         // Force textclass if the user wanted it
472         if (!forceclass.empty()) {
473                 h_textclass = forceclass;
474         }
475         string layoutfilename = LibFileSearch("layouts", h_textclass, "layout");
476         if (layoutfilename.empty()) {
477                 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
478                 exit(1);
479         }
480         LyXTextClass textclass;
481         textclass.Read(layoutfilename);
482         if (h_papersides.empty()) {
483                 ostringstream ss;
484                 ss << textclass.sides();
485                 h_papersides = ss.str();
486         }
487         end_preamble(os, textclass);
488         return textclass;
489 }
490
491 // }])