]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/preamble.C
Fix bug 2289
[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 #include "support/lstrings.h"
22
23 #include <algorithm>
24 #include <iostream>
25 #include <sstream>
26 #include <string>
27 #include <vector>
28 #include <map>
29
30 using std::istringstream;
31 using std::ostream;
32 using std::ostringstream;
33 using std::string;
34 using std::vector;
35 using std::cerr;
36 using std::endl;
37
38 using lyx::support::libFileSearch;
39
40 // special columntypes
41 extern std::map<char, int> special_columns;
42
43 std::map<string, vector<string> > used_packages;
44
45 namespace {
46
47 const char * const known_languages[] = { "austrian", "babel", "bahasa",
48 "basque", "breton", "british", "bulgarian", "catalan", "croatian", "czech",
49 "danish", "dutch", "english", "esperanto", "estonian", "finnish",
50 "francais", "french", "frenchb", "frenchle", "frenchpro",
51 "galician", "german", "germanb", "greek", "hebcal", "hebfont",
52 "hebrew", "hebrew_newcode", "hebrew_oldcode", "hebrew_p", "hyphen",
53 "icelandic", "irish", "italian", "latin", "lgrcmr", "lgrcmro", "lgrcmss",
54 "lgrcmtt", "lgrenc", "lgrlcmss", "lgrlcmtt", "lheclas", "lhecmr",
55 "lhecmss", "lhecmtt", "lhecrml", "lheenc", "lhefr", "lheredis", "lheshold",
56 "lheshscr", "lheshstk", "lsorbian", "magyar", "naustrian", "ngermanb",
57 "ngerman", "norsk", "polish", "portuges", "rlbabel", "romanian",
58 "russianb", "samin", "scottish", "serbian", "slovak", "slovene", "spanish",
59 "swedish", "turkish", "ukraineb", "usorbian", "welsh", 0};
60
61 const char * const known_french_languages[] = {"french", "frenchb", "francais",
62                                                "frenchle", "frenchpro", 0};
63 char const * const known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
64
65 // some ugly stuff
66 ostringstream h_preamble;
67 string h_textclass               = "article";
68 string h_options                 = string();
69 string h_language                = "english";
70 string h_inputencoding           = "latin1";
71 string h_fontscheme              = "default";
72 string h_graphics                = "default";
73 string h_paperfontsize           = "default";
74 string h_spacing                 = "single";
75 string h_papersize               = "default";
76 string h_use_geometry            = "false";
77 string h_use_amsmath             = "0";
78 string h_cite_engine             = "basic";
79 string h_use_bibtopic            = "false";
80 string h_paperorientation        = "portrait";
81 string h_secnumdepth             = "3";
82 string h_tocdepth                = "3";
83 string h_paragraph_separation    = "indent";
84 string h_defskip                 = "medskip";
85 string h_quotes_language         = "english";
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 245\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            << "\\papercolumns " << h_papercolumns << "\n"
261            << "\\papersides " << h_papersides << "\n"
262            << "\\paperpagestyle " << h_paperpagestyle << "\n"
263            << "\\tracking_changes " << h_tracking_changes << "\n"
264            << "\\output_changes " << h_output_changes << "\n"
265            << "\\end_header\n\n"
266            << "\\begin_body\n";
267         // clear preamble for subdocuments
268         h_preamble.str("");
269 }
270
271 } // anonymous namespace
272
273 LyXTextClass const parse_preamble(Parser & p, ostream & os, string const & forceclass)
274 {
275         // initialize fixed types
276         special_columns['D'] = 3;
277         bool is_full_document = false;
278
279         // determine whether this is a full document or a fragment for inclusion
280         while (p.good()) {
281                 Token const & t = p.get_token();
282
283                 if (t.cat() == catEscape && t.cs() == "documentclass") {
284                         is_full_document = true;
285                         break;
286                 }
287         }
288         p.reset();
289
290         while (is_full_document && p.good()) {
291                 Token const & t = p.get_token();
292
293 #ifdef FILEDEBUG
294                 cerr << "t: " << t << "\n";
295 #endif
296
297                 //
298                 // cat codes
299                 //
300                 if (t.cat() == catLetter ||
301                           t.cat() == catSuper ||
302                           t.cat() == catSub ||
303                           t.cat() == catOther ||
304                           t.cat() == catMath ||
305                           t.cat() == catActive ||
306                           t.cat() == catBegin ||
307                           t.cat() == catEnd ||
308                           t.cat() == catAlign ||
309                           t.cat() == catParameter)
310                 h_preamble << t.character();
311
312                 else if (t.cat() == catSpace || t.cat() == catNewline)
313                         h_preamble << t.asInput();
314
315                 else if (t.cat() == catComment)
316                         h_preamble << t.asInput();
317
318                 else if (t.cs() == "pagestyle")
319                         h_paperpagestyle = p.verbatim_item();
320
321                 else if (t.cs() == "makeatletter") {
322                         p.setCatCode('@', catLetter);
323                         h_preamble << "\\makeatletter";
324                 }
325
326                 else if (t.cs() == "makeatother") {
327                         p.setCatCode('@', catOther);
328                         h_preamble << "\\makeatother";
329                 }
330
331                 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
332                             || t.cs() == "providecommand") {
333                         bool star = false;
334                         if (p.next_token().character() == '*') {
335                                 p.get_token();
336                                 star = true;
337                         }
338                         string const name = p.verbatim_item();
339                         string const opt1 = p.getOpt();
340                         string const opt2 = p.getFullOpt();
341                         string const body = p.verbatim_item();
342                         // only non-lyxspecific stuff
343                         if (   name != "\\noun"
344                             && name != "\\tabularnewline"
345                             && name != "\\LyX"
346                             && name != "\\lyxline"
347                             && name != "\\lyxaddress"
348                             && name != "\\lyxrightaddress"
349                             && name != "\\lyxdot"
350                             && name != "\\boldsymbol"
351                             && name != "\\lyxarrow") {
352                                 ostringstream ss;
353                                 ss << '\\' << t.cs();
354                                 if (star)
355                                         ss << '*';
356                                 ss << '{' << name << '}' << opt1 << opt2
357                                    << '{' << body << "}";
358                                 h_preamble << ss.str();
359
360                                 // Add the command to the known commands
361                                 add_known_command(name, opt1, !opt2.empty());
362 /*
363                                 ostream & out = in_preamble ? h_preamble : os;
364                                 out << "\\" << t.cs() << "{" << name << "}"
365                                     << opts << "{" << body << "}";
366 */
367                         }
368                 }
369
370                 else if (t.cs() == "documentclass") {
371                         vector<string> opts;
372                         split(p.getArg('[', ']'), opts, ',');
373                         handle_opt(opts, known_languages, h_language);
374                         if (is_known(h_language, known_french_languages))
375                                 h_language = "french";
376                         handle_opt(opts, known_fontsizes, h_paperfontsize);
377                         // delete "pt" at the end
378                         string::size_type i = h_paperfontsize.find("pt");
379                         if (i != string::npos)
380                                 h_paperfontsize.erase(i);
381                         h_quotes_language = h_language;
382                         h_options = join(opts, ",");
383                         h_textclass = p.getArg('{', '}');
384                 }
385
386                 else if (t.cs() == "usepackage") {
387                         string const options = p.getArg('[', ']');
388                         string const name = p.getArg('{', '}');
389                         if (options.empty() && name.find(',')) {
390                                 vector<string> vecnames;
391                                 split(name, vecnames, ',');
392                                 vector<string>::const_iterator it  = vecnames.begin();
393                                 vector<string>::const_iterator end = vecnames.end();
394                                 for (; it != end; ++it)
395                                         handle_package(trim(*it), string());
396                         } else {
397                                 handle_package(name, options);
398                         }
399                 }
400
401                 else if (t.cs() == "newenvironment") {
402                         string const name = p.getArg('{', '}');
403                         ostringstream ss;
404                         ss << "\\newenvironment{" << name << "}";
405                         ss << p.getOpt();
406                         ss << p.getOpt();
407                         ss << '{' << p.verbatim_item() << '}';
408                         ss << '{' << p.verbatim_item() << '}';
409                         if (name != "lyxcode" && name != "lyxlist" &&
410                             name != "lyxrightadress" &&
411                             name != "lyxaddress" && name != "lyxgreyedout")
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         if (noweb_mode && !lyx::support::prefixIs(h_textclass, "literate-"))
490                 h_textclass.insert(0, "literate-");
491         string layoutfilename = libFileSearch("layouts", h_textclass, "layout");
492         if (layoutfilename.empty()) {
493                 cerr << "Error: Could not find layout file for textclass \"" << h_textclass << "\"." << endl;
494                 exit(1);
495         }
496         LyXTextClass textclass;
497         textclass.read(layoutfilename);
498         if (h_papersides.empty()) {
499                 ostringstream ss;
500                 ss << textclass.sides();
501                 h_papersides = ss.str();
502         }
503         end_preamble(os, textclass);
504         return textclass;
505 }
506
507 // }])