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