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