1 /** The .tex to .lyx converter
2 \author André Pönitz (2003)
18 #include "texparser.h"
28 using std::istringstream;
30 using std::ostringstream;
38 char const OPEN = '<';
39 char const CLOSE = '>';
41 const char * known_languages[] = { "austrian", "babel", "bahasa",
42 "basque", "breton", "bulgarian", "catalan", "croatian", "czech", "danish",
43 "dutch", "english", "esperanto", "estonian", "finnish", "francais",
44 "frenchb", "galician", "germanb", "greek", "hebcal", "hebfont", "hebrew",
45 "hebrew_newcode", "hebrew_oldcode", "hebrew_p", "hyphen", "icelandic",
46 "irish", "italian", "latin", "lgrcmr", "lgrcmro", "lgrcmss", "lgrcmtt",
47 "lgrenc", "lgrlcmss", "lgrlcmtt", "lheclas", "lhecmr", "lhecmss",
48 "lhecmtt", "lhecrml", "lheenc", "lhefr", "lheredis", "lheshold",
49 "lheshscr", "lheshstk", "lsorbian", "magyar", "naustrian", "ngermanb",
50 "ngerman", "norsk", "polish", "portuges", "rlbabel", "romanian",
51 "russianb", "samin", "scottish", "serbian", "slovak", "slovene", "spanish",
52 "swedish", "turkish", "ukraineb", "usorbian", "welsh", 0};
54 const char * known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
57 const char * known_math_envs[] = {"equation", "eqnarray", "eqnarray*",
62 ostringstream h_preamble;
63 string h_textclass = "FIXME";
64 string h_options = "FIXME";
65 string h_language = "FIXME";
66 string h_inputencoding = "FIXME";
67 string h_fontscheme = "FIXME";
68 string h_graphics = "default";
69 string h_paperfontsize = "FIXME";
70 string h_spacing = "single";
71 string h_papersize = "FIXME";
72 string h_paperpackage = "FIXME";
73 string h_use_geometry = "0";
74 string h_use_amsmath = "0";
75 string h_use_natbib = "0";
76 string h_use_numerical_citations = "0";
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 = "FIXME";
83 string h_quotes_times = "1";
84 string h_papercolumns = "1";
85 string h_papersides = "1";
86 string h_paperpagestyle = "default";
87 string h_tracking_changes = "0";
89 // indicates whether we are in the preamble
90 bool in_preamble = true;
92 // current stack of nested environments
93 stack<string> active_environments;
104 string const trim(string const & a, char const * p = " ")
108 if (a.empty() || !*p)
111 string::size_type r = a.find_last_not_of(p);
112 string::size_type l = a.find_first_not_of(p);
114 // Is this the minimal test? (lgb)
115 if (r == string::npos && l == string::npos)
118 return a.substr(l, r - l + 1);
122 void split(string const & s, vector<string> & result, char delim)
126 while (getline(is, t, delim))
131 string join(vector<string> const & input, char delim)
134 for (size_t i = 0; i != input.size(); ++i) {
143 void handle_opt(vector<string> & opts, char const ** what, string & target)
148 for ( ; what; ++what) {
149 vector<string>::iterator it = find(opts.begin(), opts.end(), *what);
150 if (it != opts.end()) {
151 //cerr << "### found option '" << *what << "'\n";
160 bool is_math_env(string const & name)
162 for (char const ** what = known_math_envs; *what; ++what)
169 bool is_heading(string const & name)
174 name == "paragraph" ||
176 name == "chapter*" ||
178 name == "section*" ||
179 name == "subsection" ||
180 name == "subsection*" ||
181 name == "subsubsection" ||
182 name == "subsubsection*";
186 void begin_inset(ostream & os, string const & name)
188 os << "\n\\begin_inset " << name;
192 void end_inset(ostream & os)
194 os << "\n\\end_inset\n";
198 void handle_ert(ostream & os, string const & s)
200 begin_inset(os, "ERT");
201 os << "\nstatus Collapsed\n\n\\layout Standard\n\n";
202 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
204 os << "\n\\backslash\n";
212 void handle_par(ostream & os)
214 if (active_environments.empty())
217 string s = active_environments.top();
218 if (s == "document") {
219 os << "Standard\n\n";
222 if (s == "lyxcode") {
223 os << "LyX-Code\n\n";
226 os << cap(s) << "\n\n";
230 void handle_package(string const & name, string const & options)
232 if (name == "a4wide") {
233 h_papersize = "a4paper";
234 h_paperpackage = "widemarginsa4";
235 } else if (name == "ae")
237 else if (name == "aecompl")
239 else if (name == "amsmath")
241 else if (name == "amssymb")
243 else if (name == "babel")
245 else if (name == "fontenc")
247 else if (name == "inputenc")
248 h_inputencoding = options;
249 else if (name == "makeidx")
251 else if (name == "verbatim")
255 h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
257 h_preamble << "\\usepackage{" << name << "}\n";
262 string wrap(string const & cmd, string const & str)
264 return OPEN + cmd + ' ' + str + CLOSE;
268 void end_preamble(ostream & os)
271 os << "# tex2lyx 0.0.2 created this file\n"
272 << "\\lyxformat 222\n"
273 << "\\textclass " << h_textclass << "\n"
274 << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
275 << "\\options " << h_options << "\n"
276 << "\\language " << h_language << "\n"
277 << "\\inputencoding " << h_inputencoding << "\n"
278 << "\\fontscheme " << h_fontscheme << "\n"
279 << "\\graphics " << h_graphics << "\n"
280 << "\\paperfontsize " << h_paperfontsize << "\n"
281 << "\\spacing " << h_spacing << "\n"
282 << "\\papersize " << h_papersize << "\n"
283 << "\\paperpackage " << h_paperpackage << "\n"
284 << "\\use_geometry " << h_use_geometry << "\n"
285 << "\\use_amsmath " << h_use_amsmath << "\n"
286 << "\\use_natbib " << h_use_natbib << "\n"
287 << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
288 << "\\paperorientation " << h_paperorientation << "\n"
289 << "\\secnumdepth " << h_secnumdepth << "\n"
290 << "\\tocdepth " << h_tocdepth << "\n"
291 << "\\paragraph_separation " << h_paragraph_separation << "\n"
292 << "\\defskip " << h_defskip << "\n"
293 << "\\quotes_language " << h_quotes_language << "\n"
294 << "\\quotes_times " << h_quotes_times << "\n"
295 << "\\papercolumns " << h_papercolumns << "\n"
296 << "\\papersides " << h_papersides << "\n"
297 << "\\paperpagestyle " << h_paperpagestyle << "\n"
298 << "\\tracking_changes " << h_tracking_changes << "\n"
299 << h_preamble.str() << "\n";
303 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
306 Token const & t = p.getToken();
309 cerr << "t: " << t << " flags: " << flags << "\n";
313 if (flags & FLAG_ITEM) {
314 if (t.cat() == catSpace)
318 if (t.cat() == catBegin) {
319 // skip the brace and collect everything to the next matching
321 flags |= FLAG_BRACE_LAST;
325 // handle only this single token, leave the loop if done
330 if (flags & FLAG_BRACED) {
331 if (t.cat() == catSpace)
334 if (t.cat() != catBegin) {
335 p.error("opening brace expected");
339 // skip the brace and collect everything to the next matching
341 flags = FLAG_BRACE_LAST;
345 if (flags & FLAG_OPTION) {
346 if (t.cat() == catOther && t.character() == '[') {
347 parse(p, os, FLAG_BRACK_LAST, mode);
349 // no option found, put back token and we are done
358 if (t.cat() == catMath) {
359 if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
360 // we are inside some text mode thingy, so opening new math is allowed
361 if (mode == TEXT_MODE)
362 begin_inset(os, "Formula ");
363 Token const & n = p.getToken();
364 if (n.cat() == catMath) {
365 // TeX's $$...$$ syntax for displayed math
367 parse(p, os, FLAG_SIMPLE, MATH_MODE);
369 p.getToken(); // skip the second '$' token
371 // simple $...$ stuff
374 parse(p, os, FLAG_SIMPLE, MATH_MODE);
377 if (mode == TEXT_MODE)
381 else if (flags & FLAG_SIMPLE) {
382 // this is the end of the formula
387 cerr << "mode: " << mode << endl;
388 p.error("something strange in the parser\n");
393 else if (t.cat() == catLetter)
396 else if (t.cat() == catSpace)
399 else if (t.cat() == catNewline)
402 else if (t.cat() == catSuper)
405 else if (t.cat() == catSub)
408 else if (t.cat() == catParameter) {
409 Token const & n = p.getToken();
410 os << wrap("macroarg", string(1, n.character()));
413 else if (t.cat() == catActive)
414 os << wrap("active", string(1, t.character()));
416 else if (t.cat() == catBegin) {
418 parse(p, os, FLAG_BRACE_LAST, mode);
422 else if (t.cat() == catEnd) {
423 if (flags & FLAG_BRACE_LAST)
425 p.error("found '}' unexpectedly");
427 //add(cell, '}', LM_TC_TEX);
430 else if (t.cat() == catAlign)
435 //cerr << " column now " << cellcol << " max: " << grid.ncols() << "\n";
436 if (cellcol == grid.ncols()) {
437 //cerr << "adding column " << cellcol << "\n";
438 grid.addCol(cellcol - 1);
440 cell = &grid.cell(grid.index(cellrow, cellcol));
444 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
445 //cerr << "finished reading option\n";
449 else if (t.cat() == catOther)
450 os << string(1, t.character());
452 else if (t.cat() == catComment) {
455 Token const & t = p.getToken();
456 if (t.cat() == catNewline)
460 //os << wrap("comment", s);
468 else if (t.cs() == "lyxlock") {
472 else if (t.cs() == "newcommand" || t.cs() == "providecommand") {
473 string const name = p.verbatimItem();
474 string const opts = p.getArg('[', ']');
475 string const body = p.verbatimItem();
476 // only non-lyxspecific stuff
477 if (name != "noun" && name != "tabularnewline") {
478 h_preamble << "\\" << t.cs() << "{" << name << "}";
480 h_preamble << "[" << opts << "]";
481 h_preamble << "{" << body << "}\n";
485 else if (t.cs() == "(") {
486 begin_inset(os, "Formula");
488 parse(p, os, FLAG_SIMPLE2, MATH_MODE);
493 else if (t.cs() == "[") {
494 begin_inset(os, "Formula");
496 parse(p, os, FLAG_EQUATION, MATH_MODE);
501 else if (t.cs() == "protect")
502 // ignore \\protect, will hopefully be re-added during output
505 else if (t.cs() == "begin") {
506 string const name = p.getArg('{', '}');
507 active_environments.push(name);
508 if (name == "document")
510 else if (name == "abstract")
512 else if (is_math_env(name))
513 begin_inset(os, "Formula ");
515 os << "\\begin{" << name << "}";
516 parse(p, os, FLAG_END, mode);
519 else if (t.cs() == "end") {
520 if (flags & FLAG_END) {
521 // eat environment name
522 string const name = p.getArg('{', '}');
523 if (name != active_environments.top())
524 p.error("\\end{" + name + "} does not match \\begin{"
525 + active_environments.top() + "}");
526 active_environments.pop();
527 if (name == "document" || name == "abstract")
529 else if (is_math_env(name))
532 os << "\\end{" << name << "}";
535 p.error("found 'end' unexpectedly");
538 else if (t.cs() == ")") {
539 if (flags & FLAG_SIMPLE2)
541 p.error("found '\\)' unexpectedly");
544 else if (t.cs() == "]") {
545 if (flags & FLAG_EQUATION)
547 p.error("found '\\]' unexpectedly");
550 else if (t.cs() == "documentclass") {
552 split(p.getArg('[', ']'), opts, ',');
553 handle_opt(opts, known_languages, h_language);
554 handle_opt(opts, known_fontsizes, h_paperfontsize);
555 h_quotes_language = h_language;
556 h_options = join(opts, ',');
557 h_textclass = p.getArg('{', '}');
560 else if (t.cs() == "usepackage") {
561 string const options = p.getArg('[', ']');
562 string const name = p.getArg('{', '}');
563 if (options.empty() && name.find(',')) {
564 vector<string> vecnames;
565 split(name, vecnames, ',');
566 vector<string>::const_iterator it = vecnames.begin();
567 vector<string>::const_iterator end = vecnames.end();
568 for (; it != end; ++it)
569 handle_package(trim(*it), string());
571 handle_package(name, options);
575 else if (t.cs() == "newenvironment") {
576 string const name = p.getArg('{', '}');
578 string const begin = p.verbatimItem();
580 string const end = p.verbatimItem();
582 if (name != "lyxcode")
583 os << wrap("newenvironment", begin + end);
586 else if (t.cs() == "def") {
587 string name = p.getToken().cs();
588 while (p.nextToken().cat() != catBegin)
589 name += p.getToken().asString();
590 handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
593 else if (t.cs() == "setcounter") {
594 string const name = p.getArg('{', '}');
595 string const content = p.getArg('{', '}');
596 if (name == "secnumdepth")
597 h_secnumdepth = content;
598 else if (name == "tocdepth")
599 h_tocdepth = content;
601 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
604 else if (t.cs() == "setlength") {
605 string const name = p.getToken().cs();
606 string const content = p.getArg('{', '}');
607 if (name == "parskip")
608 h_paragraph_separation = "skip";
609 else if (name == "parindent")
610 h_paragraph_separation = "skip";
612 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
615 else if (t.cs() == "par")
618 else if (is_heading(t.cs())) {
619 os << "\\layout " << cap(t.cs()) << "\n\n";
620 parse(p, os, FLAG_ITEM, mode);
623 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
626 else if (t.cs() == "tableofcontents")
627 p.verbatimItem(); // swallow this
629 else if (t.cs() == "textrm") {
630 os << '\\' << t.cs() << '{';
631 parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
635 else if (t.cs() == "emph" && mode == TEXT_MODE) {
636 os << "\n\\emph on\n";
637 parse(p, os, FLAG_ITEM, mode);
638 os << "\n\\emph default\n";
641 else if (t.cs() == "index") {
642 begin_inset(os, "LatexCommand ");
643 parse(p, os, FLAG_ITEM, TEXT_MODE);
648 (in_preamble ? h_preamble : os) << '\\' << t.asInput();
650 if (flags & FLAG_LEAVE) {
651 flags &= ~FLAG_LEAVE;
659 } // anonymous namespace
662 int main(int argc, char * argv[])
665 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
669 ifstream is(argv[1]);
671 parse(p, cout, 0, TEXT_MODE);
672 cout << "\n\\the_end";