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