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