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