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)
175 name == "paragraph" ||
177 name == "chapter*" ||
179 name == "section*" ||
180 name == "subsection" ||
181 name == "subsection*" ||
182 name == "subsubsection" ||
183 name == "subsubsection*";
187 bool is_latex_command(string const & name)
192 name == "printindex";
196 void begin_inset(ostream & os, string const & name)
198 os << "\n\\begin_inset " << name;
202 void end_inset(ostream & os)
204 os << "\n\\end_inset\n";
208 void handle_ert(ostream & os, string const & s)
210 begin_inset(os, "ERT");
211 os << "\nstatus Collapsed\n\n\\layout Standard\n\n";
212 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
214 os << "\n\\backslash\n";
222 void handle_par(ostream & os)
224 if (active_environments.empty())
227 string s = active_environments.top();
228 if (s == "document") {
229 os << "Standard\n\n";
232 if (s == "lyxcode") {
233 os << "LyX-Code\n\n";
236 os << cap(s) << "\n\n";
240 void handle_package(string const & name, string const & options)
242 if (name == "a4wide") {
243 h_papersize = "a4paper";
244 h_paperpackage = "widemarginsa4";
245 } else if (name == "ae")
247 else if (name == "aecompl")
249 else if (name == "amsmath")
251 else if (name == "amssymb")
253 else if (name == "babel")
255 else if (name == "fontenc")
257 else if (name == "inputenc")
258 h_inputencoding = options;
259 else if (name == "makeidx")
261 else if (name == "verbatim")
265 h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
267 h_preamble << "\\usepackage{" << name << "}\n";
272 void handle_table(Parser & p, ostream & os)
274 // \begin{table} has been read
279 string wrap(string const & cmd, string const & str)
281 return OPEN + cmd + ' ' + str + CLOSE;
285 void end_preamble(ostream & os)
288 os << "# tex2lyx 0.0.2 created this file\n"
289 << "\\lyxformat 222\n"
290 << "\\textclass " << h_textclass << "\n"
291 << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
292 << "\\options " << h_options << "\n"
293 << "\\language " << h_language << "\n"
294 << "\\inputencoding " << h_inputencoding << "\n"
295 << "\\fontscheme " << h_fontscheme << "\n"
296 << "\\graphics " << h_graphics << "\n"
297 << "\\paperfontsize " << h_paperfontsize << "\n"
298 << "\\spacing " << h_spacing << "\n"
299 << "\\papersize " << h_papersize << "\n"
300 << "\\paperpackage " << h_paperpackage << "\n"
301 << "\\use_geometry " << h_use_geometry << "\n"
302 << "\\use_amsmath " << h_use_amsmath << "\n"
303 << "\\use_natbib " << h_use_natbib << "\n"
304 << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
305 << "\\paperorientation " << h_paperorientation << "\n"
306 << "\\secnumdepth " << h_secnumdepth << "\n"
307 << "\\tocdepth " << h_tocdepth << "\n"
308 << "\\paragraph_separation " << h_paragraph_separation << "\n"
309 << "\\defskip " << h_defskip << "\n"
310 << "\\quotes_language " << h_quotes_language << "\n"
311 << "\\quotes_times " << h_quotes_times << "\n"
312 << "\\papercolumns " << h_papercolumns << "\n"
313 << "\\papersides " << h_papersides << "\n"
314 << "\\paperpagestyle " << h_paperpagestyle << "\n"
315 << "\\tracking_changes " << h_tracking_changes << "\n";
319 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
322 Token const & t = p.getToken();
325 cerr << "t: " << t << " flags: " << flags << "\n";
329 if (flags & FLAG_ITEM) {
330 if (t.cat() == catSpace)
334 if (t.cat() == catBegin) {
335 // skip the brace and collect everything to the next matching
337 flags |= FLAG_BRACE_LAST;
341 // handle only this single token, leave the loop if done
346 if (flags & FLAG_BRACED) {
347 if (t.cat() == catSpace)
350 if (t.cat() != catBegin) {
351 p.error("opening brace expected");
355 // skip the brace and collect everything to the next matching
357 flags = FLAG_BRACE_LAST;
361 if (flags & FLAG_OPTION) {
362 if (t.cat() == catOther && t.character() == '[') {
363 parse(p, os, FLAG_BRACK_LAST, mode);
365 // no option found, put back token and we are done
374 if (t.cat() == catMath) {
375 if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
376 // we are inside some text mode thingy, so opening new math is allowed
377 if (mode == TEXT_MODE)
378 begin_inset(os, "Formula ");
379 Token const & n = p.getToken();
380 if (n.cat() == catMath) {
381 // TeX's $$...$$ syntax for displayed math
383 parse(p, os, FLAG_SIMPLE, MATH_MODE);
385 p.getToken(); // skip the second '$' token
387 // simple $...$ stuff
390 parse(p, os, FLAG_SIMPLE, MATH_MODE);
393 if (mode == TEXT_MODE)
397 else if (flags & FLAG_SIMPLE) {
398 // this is the end of the formula
403 cerr << "mode: " << mode << endl;
404 p.error("something strange in the parser\n");
409 else if (t.cat() == catLetter)
412 else if (t.cat() == catSpace)
415 else if (t.cat() == catNewline)
418 else if (t.cat() == catSuper)
421 else if (t.cat() == catSub)
424 else if (t.cat() == catParameter) {
425 Token const & n = p.getToken();
426 os << wrap("macroarg", string(1, n.character()));
429 else if (t.cat() == catActive)
430 os << wrap("active", string(1, t.character()));
432 else if (t.cat() == catBegin) {
434 parse(p, os, FLAG_BRACE_LAST, mode);
438 else if (t.cat() == catEnd) {
439 if (flags & FLAG_BRACE_LAST)
441 p.error("found '}' unexpectedly");
443 //add(cell, '}', LM_TC_TEX);
446 else if (t.cat() == catAlign)
451 //cerr << " column now " << cellcol << " max: " << grid.ncols() << "\n";
452 if (cellcol == grid.ncols()) {
453 //cerr << "adding column " << cellcol << "\n";
454 grid.addCol(cellcol - 1);
456 cell = &grid.cell(grid.index(cellrow, cellcol));
460 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
461 //cerr << "finished reading option\n";
465 else if (t.cat() == catOther)
466 os << string(1, t.character());
468 else if (t.cat() == catComment) {
471 Token const & t = p.getToken();
472 if (t.cat() == catNewline)
476 //os << wrap("comment", s);
484 else if (t.cs() == "lyxlock") {
488 else if (t.cs() == "newcommand" || t.cs() == "providecommand") {
489 string const name = p.verbatimItem();
490 string const opts = p.getArg('[', ']');
491 string const body = p.verbatimItem();
492 // only non-lyxspecific stuff
493 if (name != "noun" && name != "tabularnewline") {
494 ostream & out = in_preamble ? h_preamble : os;
496 begin_inset(os, "FormulaMacro\n");
497 out << "\\" << t.cs() << "{" << name << "}";
499 out << "[" << opts << "]";
500 out << "{" << body << "}";
506 else if (t.cs() == "(") {
507 begin_inset(os, "Formula");
509 parse(p, os, FLAG_SIMPLE2, MATH_MODE);
514 else if (t.cs() == "[") {
515 begin_inset(os, "Formula");
517 parse(p, os, FLAG_EQUATION, MATH_MODE);
522 else if (t.cs() == "protect")
523 // ignore \\protect, will hopefully be re-added during output
526 else if (t.cs() == "begin") {
527 string const name = p.getArg('{', '}');
528 active_environments.push(name);
529 if (name == "document") {
531 parse(p, os, FLAG_END, mode);
532 } else if (name == "abstract") {
534 parse(p, os, FLAG_END, mode);
535 } else if (is_math_env(name)) {
536 begin_inset(os, "Formula ");
537 os << "\\begin{" << name << "}";
538 parse(p, os, FLAG_END, MATH_MODE);
539 } else if (name == "table") {
541 parse(p, os, FLAG_END, mode);
542 } else if (name == "thebibliography") {
543 p.verbatimItem(); // swallow next arg
545 parse(p, os, FLAG_END, mode);
547 os << "\\begin{" << name << "}";
548 parse(p, os, FLAG_END, mode);
552 else if (t.cs() == "end") {
553 if (flags & FLAG_END) {
554 // eat environment name
555 string const name = p.getArg('{', '}');
556 if (name != active_environments.top())
557 p.error("\\end{" + name + "} does not match \\begin{"
558 + active_environments.top() + "}");
559 active_environments.pop();
560 if (name == "document" || name == "abstract")
562 else if (name == "table")
564 else if (name == "thebibliography")
566 else if (is_math_env(name)) {
568 os << "\\end{" << name << "}";
570 os << "\\end{" << name << "}";
573 p.error("found 'end' unexpectedly");
576 else if (t.cs() == ")") {
577 if (flags & FLAG_SIMPLE2)
579 p.error("found '\\)' unexpectedly");
582 else if (t.cs() == "]") {
583 if (flags & FLAG_EQUATION)
585 p.error("found '\\]' unexpectedly");
588 else if (t.cs() == "documentclass") {
590 split(p.getArg('[', ']'), opts, ',');
591 handle_opt(opts, known_languages, h_language);
592 handle_opt(opts, known_fontsizes, h_paperfontsize);
593 h_quotes_language = h_language;
594 h_options = join(opts, ',');
595 h_textclass = p.getArg('{', '}');
598 else if (t.cs() == "usepackage") {
599 string const options = p.getArg('[', ']');
600 string const name = p.getArg('{', '}');
601 if (options.empty() && name.find(',')) {
602 vector<string> vecnames;
603 split(name, vecnames, ',');
604 vector<string>::const_iterator it = vecnames.begin();
605 vector<string>::const_iterator end = vecnames.end();
606 for (; it != end; ++it)
607 handle_package(trim(*it), string());
609 handle_package(name, options);
613 else if (t.cs() == "newenvironment") {
614 string const name = p.getArg('{', '}');
616 string const begin = p.verbatimItem();
618 string const end = p.verbatimItem();
620 if (name != "lyxcode")
621 os << wrap("newenvironment", begin + end);
624 else if (t.cs() == "def") {
625 string name = p.getToken().cs();
626 while (p.nextToken().cat() != catBegin)
627 name += p.getToken().asString();
628 handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
631 else if (t.cs() == "setcounter") {
632 string const name = p.getArg('{', '}');
633 string const content = p.getArg('{', '}');
634 if (name == "secnumdepth")
635 h_secnumdepth = content;
636 else if (name == "tocdepth")
637 h_tocdepth = content;
639 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
642 else if (t.cs() == "setlength") {
643 string const name = p.getToken().cs();
644 string const content = p.getArg('{', '}');
645 if (name == "parskip")
646 h_paragraph_separation = "skip";
647 else if (name == "parindent")
648 h_paragraph_separation = "skip";
650 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
653 else if (t.cs() == "par")
656 else if (is_heading(t.cs())) {
657 os << "\\layout " << cap(t.cs()) << "\n\n";
658 parse(p, os, FLAG_ITEM, mode);
661 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
664 else if (t.cs() == "tableofcontents")
665 p.verbatimItem(); // swallow this
667 else if (t.cs() == "textrm") {
668 os << '\\' << t.cs() << '{';
669 parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
673 else if (t.cs() == "emph" && mode == TEXT_MODE) {
674 os << "\n\\emph on\n";
675 parse(p, os, FLAG_ITEM, mode);
676 os << "\n\\emph default\n";
679 else if (is_latex_command(t.cs()) && mode == TEXT_MODE) {
680 begin_inset(os, "LatexCommand ");
681 os << '\\' << t.cs() << '{';
682 parse(p, os, FLAG_ITEM, TEXT_MODE);
687 else if (t.cs() == "bibitem") {
688 os << "\n\\layout Bibliography\n\\bibitem ";
689 string opt = p.getArg('[',']');
691 os << '[' << opt << ']';
692 os << '{' << p.getArg('{','}') << '}' << "\n\n";
696 (in_preamble ? h_preamble : os) << t.asInput();
698 if (flags & FLAG_LEAVE) {
699 flags &= ~FLAG_LEAVE;
707 } // anonymous namespace
710 int main(int argc, char * argv[])
713 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
717 ifstream is(argv[1]);
719 parse(p, cout, 0, TEXT_MODE);
720 cout << "\n\\the_end";