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)
193 name == "printindex";
197 void begin_inset(ostream & os, string const & name)
199 os << "\n\\begin_inset " << name;
203 void end_inset(ostream & os)
205 os << "\n\\end_inset\n";
211 return active_environments.empty() ? string() : active_environments.top();
215 void handle_ert(ostream & os, string const & s)
217 begin_inset(os, "ERT");
218 os << "\nstatus Collapsed\n\n\\layout Standard\n\n";
219 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
221 os << "\n\\backslash\n";
229 void handle_par(ostream & os)
231 if (active_environments.empty())
234 string s = curr_env();
235 if (s == "document") {
236 os << "Standard\n\n";
239 if (s == "lyxcode") {
240 os << "LyX-Code\n\n";
243 os << cap(s) << "\n\n";
247 void handle_package(string const & name, string const & options)
249 if (name == "a4wide") {
250 h_papersize = "a4paper";
251 h_paperpackage = "widemarginsa4";
252 } else if (name == "ae")
254 else if (name == "aecompl")
256 else if (name == "amsmath")
258 else if (name == "amssymb")
260 else if (name == "babel")
262 else if (name == "fontenc")
264 else if (name == "inputenc")
265 h_inputencoding = options;
266 else if (name == "makeidx")
268 else if (name == "verbatim")
272 h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
274 h_preamble << "\\usepackage{" << name << "}\n";
279 void handle_table(Parser & p, ostream & os)
281 // \begin{table} has been read
286 string wrap(string const & cmd, string const & str)
288 return OPEN + cmd + ' ' + str + CLOSE;
292 void end_preamble(ostream & os)
295 os << "# tex2lyx 0.0.2 created this file\n"
296 << "\\lyxformat 222\n"
297 << "\\textclass " << h_textclass << "\n"
298 << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
299 << "\\options " << h_options << "\n"
300 << "\\language " << h_language << "\n"
301 << "\\inputencoding " << h_inputencoding << "\n"
302 << "\\fontscheme " << h_fontscheme << "\n"
303 << "\\graphics " << h_graphics << "\n"
304 << "\\paperfontsize " << h_paperfontsize << "\n"
305 << "\\spacing " << h_spacing << "\n"
306 << "\\papersize " << h_papersize << "\n"
307 << "\\paperpackage " << h_paperpackage << "\n"
308 << "\\use_geometry " << h_use_geometry << "\n"
309 << "\\use_amsmath " << h_use_amsmath << "\n"
310 << "\\use_natbib " << h_use_natbib << "\n"
311 << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
312 << "\\paperorientation " << h_paperorientation << "\n"
313 << "\\secnumdepth " << h_secnumdepth << "\n"
314 << "\\tocdepth " << h_tocdepth << "\n"
315 << "\\paragraph_separation " << h_paragraph_separation << "\n"
316 << "\\defskip " << h_defskip << "\n"
317 << "\\quotes_language " << h_quotes_language << "\n"
318 << "\\quotes_times " << h_quotes_times << "\n"
319 << "\\papercolumns " << h_papercolumns << "\n"
320 << "\\papersides " << h_papersides << "\n"
321 << "\\paperpagestyle " << h_paperpagestyle << "\n"
322 << "\\tracking_changes " << h_tracking_changes << "\n";
326 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
329 Token const & t = p.getToken();
332 cerr << "t: " << t << " flags: " << flags << "\n";
336 if (flags & FLAG_ITEM) {
337 if (t.cat() == catSpace)
341 if (t.cat() == catBegin) {
342 // skip the brace and collect everything to the next matching
344 flags |= FLAG_BRACE_LAST;
348 // handle only this single token, leave the loop if done
353 if (flags & FLAG_BRACED) {
354 if (t.cat() == catSpace)
357 if (t.cat() != catBegin) {
358 p.error("opening brace expected");
362 // skip the brace and collect everything to the next matching
364 flags = FLAG_BRACE_LAST;
368 if (flags & FLAG_OPTION) {
369 if (t.cat() == catOther && t.character() == '[') {
370 parse(p, os, FLAG_BRACK_LAST, mode);
372 // no option found, put back token and we are done
381 if (t.cat() == catMath) {
382 if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
383 // we are inside some text mode thingy, so opening new math is allowed
384 if (mode == TEXT_MODE)
385 begin_inset(os, "Formula ");
386 Token const & n = p.getToken();
387 if (n.cat() == catMath) {
388 // TeX's $$...$$ syntax for displayed math
390 parse(p, os, FLAG_SIMPLE, MATH_MODE);
392 p.getToken(); // skip the second '$' token
394 // simple $...$ stuff
397 parse(p, os, FLAG_SIMPLE, MATH_MODE);
400 if (mode == TEXT_MODE)
404 else if (flags & FLAG_SIMPLE) {
405 // this is the end of the formula
410 cerr << "mode: " << mode << endl;
411 p.error("something strange in the parser\n");
416 else if (t.cat() == catLetter)
419 else if (t.cat() == catSpace)
422 else if (t.cat() == catNewline)
425 else if (t.cat() == catSuper)
428 else if (t.cat() == catSub)
431 else if (t.cat() == catParameter) {
432 Token const & n = p.getToken();
433 os << wrap("macroarg", string(1, n.character()));
436 else if (t.cat() == catActive) {
437 if (t.character() == '~')
438 os << (curr_env() == "lyxcode" ? ' ' : '~');
443 else if (t.cat() == catBegin) {
445 parse(p, os, FLAG_BRACE_LAST, mode);
449 else if (t.cat() == catEnd) {
450 if (flags & FLAG_BRACE_LAST)
452 p.error("found '}' unexpectedly");
454 //add(cell, '}', LM_TC_TEX);
457 else if (t.cat() == catAlign)
462 //cerr << " column now " << cellcol << " max: " << grid.ncols() << "\n";
463 if (cellcol == grid.ncols()) {
464 //cerr << "adding column " << cellcol << "\n";
465 grid.addCol(cellcol - 1);
467 cell = &grid.cell(grid.index(cellrow, cellcol));
471 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
472 //cerr << "finished reading option\n";
476 else if (t.cat() == catOther)
477 os << string(1, t.character());
479 else if (t.cat() == catComment) {
482 Token const & t = p.getToken();
483 if (t.cat() == catNewline)
487 //os << wrap("comment", s);
495 else if (t.cs() == "lyxlock") {
499 else if (t.cs() == "newcommand" || t.cs() == "providecommand") {
500 string const name = p.verbatimItem();
501 string const opts = p.getArg('[', ']');
502 string const body = p.verbatimItem();
503 // only non-lyxspecific stuff
504 if (name != "noun" && name != "tabularnewline") {
505 ostream & out = in_preamble ? h_preamble : os;
507 begin_inset(os, "FormulaMacro\n");
508 out << "\\" << t.cs() << "{" << name << "}";
510 out << "[" << opts << "]";
511 out << "{" << body << "}";
517 else if (t.cs() == "(") {
518 begin_inset(os, "Formula");
520 parse(p, os, FLAG_SIMPLE2, MATH_MODE);
525 else if (t.cs() == "[") {
526 begin_inset(os, "Formula");
528 parse(p, os, FLAG_EQUATION, MATH_MODE);
533 else if (t.cs() == "protect")
534 // ignore \\protect, will hopefully be re-added during output
537 else if (t.cs() == "begin") {
538 string const name = p.getArg('{', '}');
539 active_environments.push(name);
540 if (name == "document") {
542 parse(p, os, FLAG_END, mode);
543 } else if (name == "abstract") {
545 parse(p, os, FLAG_END, mode);
546 } else if (is_math_env(name)) {
547 begin_inset(os, "Formula ");
548 os << "\\begin{" << name << "}";
549 parse(p, os, FLAG_END, MATH_MODE);
550 } else if (name == "table") {
552 parse(p, os, FLAG_END, mode);
553 } else if (name == "thebibliography") {
554 p.verbatimItem(); // swallow next arg
556 parse(p, os, FLAG_END, mode);
558 os << "\\begin{" << name << "}";
559 parse(p, os, FLAG_END, mode);
563 else if (t.cs() == "end") {
564 if (flags & FLAG_END) {
565 // eat environment name
566 string const name = p.getArg('{', '}');
567 if (name != curr_env())
568 p.error("\\end{" + name + "} does not match \\begin{"
570 active_environments.pop();
571 if (name == "document" || name == "abstract")
573 else if (name == "table")
575 else if (name == "thebibliography")
577 else if (is_math_env(name)) {
579 os << "\\end{" << name << "}";
581 os << "\\end{" << name << "}";
584 p.error("found 'end' unexpectedly");
587 else if (t.cs() == ")") {
588 if (flags & FLAG_SIMPLE2)
590 p.error("found '\\)' unexpectedly");
593 else if (t.cs() == "]") {
594 if (flags & FLAG_EQUATION)
596 p.error("found '\\]' unexpectedly");
599 else if (t.cs() == "documentclass") {
601 split(p.getArg('[', ']'), opts, ',');
602 handle_opt(opts, known_languages, h_language);
603 handle_opt(opts, known_fontsizes, h_paperfontsize);
604 h_quotes_language = h_language;
605 h_options = join(opts, ',');
606 h_textclass = p.getArg('{', '}');
609 else if (t.cs() == "usepackage") {
610 string const options = p.getArg('[', ']');
611 string const name = p.getArg('{', '}');
612 if (options.empty() && name.find(',')) {
613 vector<string> vecnames;
614 split(name, vecnames, ',');
615 vector<string>::const_iterator it = vecnames.begin();
616 vector<string>::const_iterator end = vecnames.end();
617 for (; it != end; ++it)
618 handle_package(trim(*it), string());
620 handle_package(name, options);
624 else if (t.cs() == "newenvironment") {
625 string const name = p.getArg('{', '}');
627 string const begin = p.verbatimItem();
629 string const end = p.verbatimItem();
631 if (name != "lyxcode")
632 os << wrap("newenvironment", begin + end);
635 else if (t.cs() == "def") {
636 string name = p.getToken().cs();
637 while (p.nextToken().cat() != catBegin)
638 name += p.getToken().asString();
639 handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
642 else if (t.cs() == "setcounter") {
643 string const name = p.getArg('{', '}');
644 string const content = p.getArg('{', '}');
645 if (name == "secnumdepth")
646 h_secnumdepth = content;
647 else if (name == "tocdepth")
648 h_tocdepth = content;
650 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
653 else if (t.cs() == "setlength") {
654 string const name = p.getToken().cs();
655 string const content = p.getArg('{', '}');
656 if (name == "parskip")
657 h_paragraph_separation = "skip";
658 else if (name == "parindent")
659 h_paragraph_separation = "skip";
661 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
664 else if (t.cs() == "par")
667 else if (is_heading(t.cs())) {
668 os << "\\layout " << cap(t.cs()) << "\n\n";
669 parse(p, os, FLAG_ITEM, mode);
672 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
675 else if (t.cs() == "tableofcontents")
676 p.verbatimItem(); // swallow this
678 else if (t.cs() == "textrm") {
679 os << '\\' << t.cs() << '{';
680 parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
684 else if (t.cs() == "emph" && mode == TEXT_MODE) {
685 os << "\n\\emph on\n";
686 parse(p, os, FLAG_ITEM, mode);
687 os << "\n\\emph default\n";
690 else if (is_latex_command(t.cs()) && mode == TEXT_MODE) {
691 begin_inset(os, "LatexCommand ");
692 os << '\\' << t.cs() << '{';
693 parse(p, os, FLAG_ITEM, TEXT_MODE);
698 else if (t.cs() == "bibitem") {
699 os << "\n\\layout Bibliography\n\\bibitem ";
700 string opt = p.getArg('[',']');
702 os << '[' << opt << ']';
703 os << '{' << p.getArg('{','}') << '}' << "\n\n";
707 (in_preamble ? h_preamble : os) << t.asInput();
709 if (flags & FLAG_LEAVE) {
710 flags &= ~FLAG_LEAVE;
718 } // anonymous namespace
721 int main(int argc, char * argv[])
724 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
728 ifstream is(argv[1]);
730 parse(p, cout, 0, TEXT_MODE);
731 cout << "\n\\the_end";