]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.C
multicol; small stuff
[lyx.git] / src / tex2lyx / tex2lyx.C
1 /** The .tex to .lyx converter
2     \author André Pönitz (2003)
3  */
4
5 // {[(
6
7 #include <config.h>
8
9 #include <algorithm>
10 #include <cctype>
11 #include <fstream>
12 #include <iostream>
13 #include <stack>
14 #include <string>
15 #include <vector>
16
17 #include "Lsstream.h"
18
19 #include "texparser.h"
20
21 using std::count_if;
22 using std::cout;
23 using std::cerr;
24 using std::endl;
25 using std::fill;
26 using std::getline;
27 using std::ios;
28 using std::ifstream;
29 using std::istream;
30 using std::istringstream;
31 using std::ostream;
32 using std::ostringstream;
33 using std::stack;
34 using std::string;
35 using std::vector;
36
37
38 namespace {
39
40 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode);
41
42 char const OPEN = '<';
43 char const CLOSE = '>';
44
45 // rather brutish way to code table structure in a string:
46 //
47 //  \begin{tabular}{ccc}
48 //    1 & 2 & 3\\ 
49 //    \multicolumn{2}{c}{4} & 5\\ 
50 //    6 & 7 \\ 
51 //  \end{tabular}
52 //
53 // gets "translated" to:
54 //  
55 //  1 TAB 2 TAB 3 LINE
56 //  2 MULT c MULT 4 TAB 5 LINE
57 //  5 TAB 7 LINE
58
59 char const TAB  = '\001';
60 char const LINE = '\002';
61 char const MULT = '\003';
62
63 const char * known_languages[] = { "austrian", "babel", "bahasa", "basque",
64 "breton", "british", "bulgarian", "catalan", "croatian", "czech", "danish",
65 "dutch", "english", "esperanto", "estonian", "finnish", "francais",
66 "frenchb", "galician", "german", "germanb", "greek", "hebcal", "hebfont",
67 "hebrew", "hebrew_newcode", "hebrew_oldcode", "hebrew_p", "hyphen",
68 "icelandic", "irish", "italian", "latin", "lgrcmr", "lgrcmro", "lgrcmss",
69 "lgrcmtt", "lgrenc", "lgrlcmss", "lgrlcmtt", "lheclas", "lhecmr",
70 "lhecmss", "lhecmtt", "lhecrml", "lheenc", "lhefr", "lheredis", "lheshold",
71 "lheshscr", "lheshstk", "lsorbian", "magyar", "naustrian", "ngermanb",
72 "ngerman", "norsk", "polish", "portuges", "rlbabel", "romanian",
73 "russianb", "samin", "scottish", "serbian", "slovak", "slovene", "spanish",
74 "swedish", "turkish", "ukraineb", "usorbian", "welsh", 0};
75
76 char const * known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
77
78 char const * known_headings[] = { "caption", "title", "author",
79 "paragraph", "chapter", "section", "subsection", "subsubsection", 0 };
80
81 char const * known_math_envs[] = { "equation", "eqnarray", "eqnarray*",
82 "align", "align*", 0};
83
84 char const * known_latex_commands[] = { "ref", "cite", "label", "index",
85 "printindex", 0 };
86
87 // LaTeX names for quotes
88 char const * known_quotes[] = { "glqq", "grqq", 0};
89
90 // the same as known_quotes with .lyx names
91 char const * known_coded_quotes[] = { "gld", "grd", 0};
92
93
94
95 // some ugly stuff
96 ostringstream h_preamble;
97 string h_textclass               = "article";
98 string h_options                 = "";
99 string h_language                = "english";
100 string h_inputencoding           = "latin1";
101 string h_fontscheme              = "default";
102 string h_graphics                = "default";
103 string h_paperfontsize           = "default";
104 string h_spacing                 = "single";
105 string h_papersize               = "default";
106 string h_paperpackage            = "default";
107 string h_use_geometry            = "0";
108 string h_use_amsmath             = "0";
109 string h_use_natbib              = "0";
110 string h_use_numerical_citations = "0";
111 string h_paperorientation        = "portrait";
112 string h_secnumdepth             = "3";
113 string h_tocdepth                = "3";
114 string h_paragraph_separation    = "indent";
115 string h_defskip                 = "medskip";
116 string h_quotes_language         = "english";
117 string h_quotes_times            = "1";
118 string h_papercolumns            = "1";
119 string h_papersides              = "1";
120 string h_paperpagestyle          = "default";
121 string h_tracking_changes        = "0";
122
123 // indicates whether we are in the preamble
124 bool in_preamble = true;
125
126 // current stack of nested environments
127 stack<string> active_environments;
128
129
130 string cap(string s)
131 {
132         if (s.size())
133                 s[0] = toupper(s[0]);
134         return s;
135 }
136
137
138 string const trim(string const & a, char const * p = " ")
139 {
140         // lyx::Assert(p);
141
142         if (a.empty() || !*p)
143                 return a;
144
145         string::size_type r = a.find_last_not_of(p);
146         string::size_type l = a.find_first_not_of(p);
147
148         // Is this the minimal test? (lgb)
149         if (r == string::npos && l == string::npos)
150                 return string();
151
152         return a.substr(l, r - l + 1);
153 }
154
155
156 void split(string const & s, vector<string> & result, char delim)
157 {
158         istringstream is(s);    
159         string t;
160         while (getline(is, t, delim))
161                 result.push_back(t);
162 }
163
164
165 string join(vector<string> const & input, char delim)
166 {
167         ostringstream os;
168         for (size_t i = 0; i != input.size(); ++i) {
169                 if (i)
170                         os << delim;    
171                 os << input[i]; 
172         }
173         return os.str();
174 }
175
176
177 char const ** is_known(string const & str, char const ** what)
178 {
179         for ( ; *what; ++what)
180                 if (str == *what)
181                         return what;
182         return 0;
183 }
184
185
186 void handle_opt(vector<string> & opts, char const ** what, string & target)
187 {
188         if (opts.empty())
189                 return;
190
191         for ( ; *what; ++what) {
192                 vector<string>::iterator it = find(opts.begin(), opts.end(), *what);
193                 if (it != opts.end()) {
194                         //cerr << "### found option '" << *what << "'\n";
195                         target = *what;
196                         opts.erase(it);
197                         return;
198                 }
199         }
200 }
201
202
203 bool is_math_env(string const & name)
204 {
205         for (char const ** what = known_math_envs; *what; ++what)
206                 if (*what == name)
207                         return true;
208         return false;
209 }
210
211
212 void begin_inset(ostream & os, string const & name)
213 {
214         os << "\n\\begin_inset " << name;
215 }
216
217
218 void end_inset(ostream & os)
219 {
220         os << "\n\\end_inset\n";
221 }
222
223
224 string curr_env()
225 {
226         return active_environments.empty() ? string() : active_environments.top();
227 }
228
229
230 void handle_ert(ostream & os, string const & s)
231 {
232         begin_inset(os, "ERT");
233         os << "\nstatus Collapsed\n\n\\layout Standard\n\n";
234         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
235                 if (*it == '\\')
236                         os << "\n\\backslash\n";
237                 else
238                         os << *it;
239         }
240         end_inset(os);
241 }
242
243
244 void handle_par(ostream & os)
245 {
246         if (active_environments.empty())
247                 return;
248         os << "\n\\layout ";
249         string s = curr_env();
250         if (s == "document" || s == "table") {
251                 os << "Standard\n\n";
252                 return;
253         }
254         if (s == "lyxcode") {
255                 os << "LyX-Code\n\n";
256                 return;
257         }
258         os << cap(s) << "\n\n";
259 }
260
261
262 void handle_package(string const & name, string const & options)
263 {
264         //cerr << "handle_package: '" << name << "'\n";
265         if (name == "a4wide") {
266                 h_papersize = "a4paper";
267                 h_paperpackage = "widemarginsa4";
268         } else if (name == "ae") 
269                 h_fontscheme = "ae";
270         else if (name == "aecompl") 
271                 h_fontscheme = "ae";
272         else if (name == "amsmath") 
273                 h_use_amsmath = "1";
274         else if (name == "amssymb") 
275                 h_use_amsmath = "1";
276         else if (name == "babel") 
277                 ; // ignore this
278         else if (name == "fontenc") 
279                 ; // ignore this
280         else if (name == "inputenc") 
281                 h_inputencoding = options;
282         else if (name == "makeidx") 
283                 ; // ignore this
284         else if (name == "verbatim") 
285                 ; // ignore this
286         else if (is_known(name, known_languages)) {
287                 h_language = name;
288                 h_quotes_language = name;
289         } else {
290                 if (options.size())
291                         h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
292                 else
293                         h_preamble << "\\usepackage{" << name << "}\n";
294         }
295 }
296
297
298 vector<string> extract_col_align(string const & s)
299 {
300         vector<string> res;
301         for (size_t i = 0; i < s.size(); ++i) {
302                 switch (s[i]) {
303                         case 'c': res.push_back("center"); break;
304                         case 'l': res.push_back("left");   break;
305                         case 'r': res.push_back("right");  break;
306                         default : res.push_back("right");  break;
307                 }
308         }
309         return res;
310 }
311
312
313 void handle_tabular(Parser & p, ostream & os, mode_type mode)
314 {
315         begin_inset(os, "Tabular \n");
316         string colopts = p.verbatimItem();
317         vector<string> colalign = extract_col_align(colopts);
318         ostringstream ss;
319         parse(p, ss, FLAG_END, mode);
320         vector<string> lines;
321         split(ss.str(), lines, LINE);
322         const size_t cols = colalign.size();
323         const size_t rows = lines.size();
324         os << "<lyxtabular version=\"3\" rows=\"" << rows
325                  << "\" columns=\"" << cols << "\">\n"
326                  << "<features>\n";
327         for (size_t c = 0; c < cols; ++c)
328                 os << "<column alignment=\"" << colalign[c] << "\""
329                          << " valignment=\"top\""
330                          << " width=\"0pt\""
331                          << ">\n";
332         for (size_t r = 0; r < rows; ++r) {
333                 vector<string> cells;
334                 split(lines[r], cells, TAB);
335                 while (cells.size() < cols)
336                         cells.push_back(string());
337                 //os << "<row bottomline=\"true\">\n";
338                 os << "<row>\n";
339                 for (size_t c = 0; c < cols; ++c) {
340                         os << "<cell";
341                         string alignment = "center";
342                         vector<string> parts;
343                         split(cells[c], parts, MULT);
344                         if (parts.size() > 2) {
345                                 os << " multicolumn=\"" << parts[0] << "\"";
346                                 alignment = parts[1];
347                         }
348                         os << " alignment=\"" << alignment << "\""
349                                  << " valignment=\"top\""
350                                  << " topline=\"true\""
351                                  << " leftline=\"true\""
352                                  << " usebox=\"none\""
353                                  << ">";
354                         begin_inset(os, "Text");
355                         os << "\n\n\\layout Standard\n\n";
356                         os << parts.back();
357                         end_inset(os);
358                         os << "</cell>\n";
359                 }
360                 os << "</row>\n";
361         }
362         os << "</lyxtabular>\n";
363         end_inset(os);  
364 }
365
366
367 string wrap(string const & cmd, string const & str)
368 {
369         return OPEN + cmd + ' ' + str + CLOSE;
370 }
371
372
373 void end_preamble(ostream & os)
374 {
375         in_preamble = false;
376         os << "# tex2lyx 0.0.2 created this file\n"
377            << "\\lyxformat 222\n"
378            << "\\textclass " << h_textclass << "\n"
379            << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
380            << "\\options " << h_options << "\n"
381            << "\\language " << h_language << "\n"
382            << "\\inputencoding " << h_inputencoding << "\n"
383            << "\\fontscheme " << h_fontscheme << "\n"
384            << "\\graphics " << h_graphics << "\n"
385            << "\\paperfontsize " << h_paperfontsize << "\n"
386            << "\\spacing " << h_spacing << "\n"
387            << "\\papersize " << h_papersize << "\n"
388            << "\\paperpackage " << h_paperpackage << "\n"
389            << "\\use_geometry " << h_use_geometry << "\n"
390            << "\\use_amsmath " << h_use_amsmath << "\n"
391            << "\\use_natbib " << h_use_natbib << "\n"
392            << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
393            << "\\paperorientation " << h_paperorientation << "\n"
394            << "\\secnumdepth " << h_secnumdepth << "\n"
395            << "\\tocdepth " << h_tocdepth << "\n"
396            << "\\paragraph_separation " << h_paragraph_separation << "\n"
397            << "\\defskip " << h_defskip << "\n"
398            << "\\quotes_language " << h_quotes_language << "\n"
399            << "\\quotes_times " << h_quotes_times << "\n"
400            << "\\papercolumns " << h_papercolumns << "\n"
401            << "\\papersides " << h_papersides << "\n"
402            << "\\paperpagestyle " << h_paperpagestyle << "\n"
403            << "\\tracking_changes " << h_tracking_changes << "\n";
404 }
405
406
407 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
408 {
409         while (p.good()) {
410                 Token const & t = p.getToken();
411
412 #ifdef FILEDEBUG
413                 cerr << "t: " << t << " flags: " << flags << "\n";
414                 //cell->dump();
415 #endif
416
417                 if (flags & FLAG_ITEM) {
418                         if (t.cat() == catSpace)
419                                 continue;
420
421                         flags &= ~FLAG_ITEM;
422                         if (t.cat() == catBegin) {
423                                 // skip the brace and collect everything to the next matching
424                                 // closing brace
425                                 flags |= FLAG_BRACE_LAST;
426                                 continue;
427                         }
428
429                         // handle only this single token, leave the loop if done
430                         flags |= FLAG_LEAVE;
431                 }
432
433
434                 if (flags & FLAG_BRACED) {
435                         if (t.cat() == catSpace)
436                                 continue;
437
438                         if (t.cat() != catBegin) {
439                                 p.error("opening brace expected");
440                                 return;
441                         }
442
443                         // skip the brace and collect everything to the next matching
444                         // closing brace
445                         flags = FLAG_BRACE_LAST;
446                 }
447
448
449                 if (flags & FLAG_OPTION) {
450                         if (t.cat() == catOther && t.character() == '[') {
451                                 parse(p, os, FLAG_BRACK_LAST, mode);
452                         } else {
453                                 // no option found, put back token and we are done
454                                 p.putback();
455                         }
456                         return;
457                 }
458
459                 //
460                 // cat codes
461                 //
462                 if (t.cat() == catMath) {
463                         if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
464                                 // we are inside some text mode thingy, so opening new math is allowed
465                                 if (mode == TEXT_MODE)
466                                         begin_inset(os, "Formula ");
467                                 Token const & n = p.getToken();
468                                 if (n.cat() == catMath) {
469                                         // TeX's $$...$$ syntax for displayed math
470                                         os << "\\[";
471                                         parse(p, os, FLAG_SIMPLE, MATH_MODE);
472                                         os << "\\]";
473                                         p.getToken(); // skip the second '$' token
474                                 } else {
475                                         // simple $...$  stuff
476                                         p.putback();
477                                         os << '$';
478                                         parse(p, os, FLAG_SIMPLE, MATH_MODE);
479                                         os << '$';
480                                 }
481                                 if (mode == TEXT_MODE)
482                                         end_inset(os);
483                         }
484
485                         else if (flags & FLAG_SIMPLE) {
486                                 // this is the end of the formula
487                                 return;
488                         }
489
490                         else {
491                                 cerr << "mode: " << mode << endl;
492                                 p.error("something strange in the parser\n");
493                                 break;
494                         }
495                 }
496
497                 else if (t.cat() == catLetter)
498                         os << t.character();
499
500                 else if (t.cat() == catSpace) 
501                         os << t.character();
502
503                 else if (t.cat() == catNewline)
504                         os << ' ';
505
506                 else if (t.cat() == catSuper)
507                         os << t.character();
508
509                 else if (t.cat() == catSub)
510                         os << t.character();
511
512                 else if (t.cat() == catParameter) {
513                         Token const & n = p.getToken();
514                         os << wrap("macroarg", string(1, n.character()));
515                 }
516
517                 else if (t.cat() == catActive) {
518                         if (t.character() == '~')
519                                 os << (curr_env() == "lyxcode" ? ' ' : '~');
520                         else
521                                 os << t.asInput();
522                 }
523
524                 else if (t.cat() == catBegin) {
525                         if (mode == MATH_MODE)
526                                 os << '{';
527                         else
528                                 handle_ert(os, "{");
529                 }
530
531                 else if (t.cat() == catEnd) {
532                         if (flags & FLAG_BRACE_LAST)
533                                 return;
534                         if (mode == MATH_MODE)
535                                 os << '}';
536                         else
537                                 handle_ert(os, "}");
538                 }
539
540                 else if (t.cat() == catAlign) {
541                         if (mode == MATH_MODE)
542                                 os << t.character();
543                         else
544                                 os << TAB;
545                 }
546
547                 else if (t.cs() == "tabularnewline") {
548                         if (mode == MATH_MODE)
549                                 os << t.asInput();
550                         else
551                                 os << LINE;
552                 }
553
554                 else if (t.cs() == "\\" && mode == MATH_MODE)
555                         os << t.asInput();
556
557                 else if (t.cs() == "\\" && curr_env() == "tabular")
558                         os << LINE;
559
560                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
561                         //cerr << "finished reading option\n";
562                         return;
563                 }
564
565                 else if (t.cat() == catOther)
566                         os << string(1, t.character());
567
568                 else if (t.cat() == catComment) {
569                         string s;
570                         while (p.good()) {
571                                 Token const & t = p.getToken();
572                                 if (t.cat() == catNewline)
573                                         break;
574                                 s += t.asString();
575                         }
576                         //os << wrap("comment", s);
577                         p.skipSpaces();
578                 }
579
580                 //
581                 // control sequences
582                 //
583
584                 else if (t.cs() == "lyxlock")
585                         ; // ignored
586
587                 else if (t.cs() == "newcommand" || t.cs() == "providecommand") {
588                         string const name = p.verbatimItem();
589                         string const opts = p.getArg('[', ']');
590                         string const body = p.verbatimItem();
591                         // only non-lyxspecific stuff
592                         if (name != "\\noun " && name != "\\tabularnewline ") {
593                                 ostream & out = in_preamble ? h_preamble : os;
594                                 if (!in_preamble)
595                                         begin_inset(os, "FormulaMacro\n");
596                                 out << "\\" << t.cs() << "{" << name << "}";
597                                 if (opts.size()) 
598                                         out << "[" << opts << "]";
599                                 out << "{" << body << "}";
600                                 if (!in_preamble)
601                                         end_inset(os);
602                         }
603                 }
604
605                 else if (t.cs() == "(") {
606                         begin_inset(os, "Formula");
607                         os << " \\(";
608                         parse(p, os, FLAG_SIMPLE2, MATH_MODE);
609                         os << "\\)";
610                         end_inset(os);
611                 }
612
613                 else if (t.cs() == "[") {
614                         begin_inset(os, "Formula");
615                         os << " \\[";
616                         parse(p, os, FLAG_EQUATION, MATH_MODE);
617                         os << "\\]";
618                         end_inset(os);
619                 }
620
621                 else if (t.cs() == "protect")
622                         // ignore \\protect, will hopefully be re-added during output
623                         ;
624
625                 else if (t.cs() == "begin") {
626                         string const name = p.getArg('{', '}');
627                         active_environments.push(name);
628                         if (name == "document") {
629                                 end_preamble(os);
630                                 parse(p, os, FLAG_END, mode);
631                         } else if (name == "abstract") {
632                                 handle_par(os);
633                                 parse(p, os, FLAG_END, mode);
634                         } else if (is_math_env(name)) {
635                                 begin_inset(os, "Formula ");    
636                                 os << "\\begin{" << name << "}";
637                                 parse(p, os, FLAG_END, MATH_MODE);
638                                 os << "\\end{" << name << "}";
639                                 end_inset(os);  
640                         } else if (name == "tabular") {
641                                 handle_tabular(p, os, mode);
642                         } else if (name == "table") {
643                                 begin_inset(os, "Float table\n");       
644                                 os << "wide false\n"
645                                    << "collapsed false\n"
646                                    << "\n"
647                                    << "\\layout Standard\n";
648                                 parse(p, os, FLAG_END, mode);
649                                 end_inset(os);  
650                         } else if (name == "thebibliography") {
651                                 p.verbatimItem(); // swallow next arg
652                                 parse(p, os, FLAG_END, mode);
653                                 os << "\n\\layout Standard\n\n";
654                         } else if (mode == MATH_MODE) {
655                                 os << "\\begin{" << name << "}";
656                                 parse(p, os, FLAG_END, mode);
657                                 os << "\\end{" << name << "}";
658                         } else {
659                                 parse(p, os, FLAG_END, mode);
660                         }
661                 }
662
663                 else if (t.cs() == "end") {
664                         if (flags & FLAG_END) {
665                                 // eat environment name
666                                 string const name = p.getArg('{', '}');
667                                 if (name != curr_env())
668                                         p.error("\\end{" + name + "} does not match \\begin{"
669                                                 + curr_env() + "}");
670                                 active_environments.pop();
671                                 return;
672                         }
673                         p.error("found 'end' unexpectedly");
674                 }
675
676
677                 else if (t.cs() == "item")
678                         handle_par(os);
679
680                 else if (t.cs() == ")") {
681                         if (flags & FLAG_SIMPLE2)
682                                 return;
683                         p.error("found '\\)' unexpectedly");
684                 }
685
686                 else if (t.cs() == "]") {
687                         if (flags & FLAG_EQUATION)
688                                 return;
689                         p.error("found '\\]' unexpectedly");
690                 }
691
692                 else if (t.cs() == "documentclass") {
693                         vector<string> opts;
694                         split(p.getArg('[', ']'), opts, ',');
695                         handle_opt(opts, known_languages, h_language); 
696                         handle_opt(opts, known_fontsizes, h_paperfontsize); 
697                         h_quotes_language = h_language;
698                         h_options = join(opts, ',');
699                         h_textclass = p.getArg('{', '}');
700                 }
701
702                 else if (t.cs() == "usepackage") {
703                         string const options = p.getArg('[', ']');
704                         string const name = p.getArg('{', '}');
705                         if (options.empty() && name.find(',')) {
706                                 vector<string> vecnames;
707                                 split(name, vecnames, ',');
708                                 vector<string>::const_iterator it  = vecnames.begin();
709                                 vector<string>::const_iterator end = vecnames.end();
710                                 for (; it != end; ++it)
711                                         handle_package(trim(*it), string());
712                         } else {
713                                 handle_package(name, options);
714                         }
715                 }
716
717                 else if (t.cs() == "newenvironment") {
718                         string const name = p.getArg('{', '}');
719                         p.skipSpaces();
720                         string const begin = p.verbatimItem();
721                         p.skipSpaces();
722                         string const end = p.verbatimItem();
723                         // ignore out mess
724                         if (name != "lyxcode") 
725                                 os << wrap("newenvironment", begin + end); 
726                 }
727
728                 else if (t.cs() == "def") {
729                         string name = p.getToken().cs();
730                         while (p.nextToken().cat() != catBegin)
731                                 name += p.getToken().asString();
732                         handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
733                 }
734
735                 else if (t.cs() == "setcounter") {
736                         string const name = p.getArg('{', '}');
737                         string const content = p.getArg('{', '}');
738                         if (name == "secnumdepth") 
739                                 h_secnumdepth = content;
740                         else if (name == "tocdepth") 
741                                 h_tocdepth = content;
742                         else
743                                 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
744                 }
745
746                 else if (t.cs() == "setlength") {
747                         string const name = p.getToken().cs();
748                         string const content = p.getArg('{', '}');
749                         if (name == "parskip")
750                                 h_paragraph_separation = "skip";
751                         else if (name == "parindent")
752                                 h_paragraph_separation = "skip";
753                         else
754                                 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
755                 }
756         
757                 else if (t.cs() == "par")
758                         handle_par(os);
759
760                 else if (is_known(t.cs(), known_headings)) {
761                         string name = t.cs();
762                         if (p.nextToken().asInput() == "*") {
763                                 p.getToken();
764                                 name += "*";
765                         }
766                         os << "\\layout " << cap(name) << "\n\n";
767                         parse(p, os, FLAG_ITEM, mode);
768                 }
769
770                 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
771                         ; // swallow this
772
773                 else if (t.cs() == "tableofcontents")
774                         p.verbatimItem(); // swallow this
775
776                 else if (t.cs() == "multicolumn" && mode == TEXT_MODE) {
777                         // brutish...
778                         parse(p, os, FLAG_ITEM, mode); 
779                         os << MULT;
780                         parse(p, os, FLAG_ITEM, mode); 
781                         os << MULT;
782                         parse(p, os, FLAG_ITEM, mode); 
783                 }
784
785                 else if (t.cs() == "textrm") {
786                         os << '\\' << t.cs() << '{';
787                         parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
788                         os << '}';
789                 }
790
791                 else if ((t.cs() == "emph" || t.cs() == "noun") && mode == TEXT_MODE) {
792                         os << "\n\\" << t.cs() << " on\n";
793                         parse(p, os, FLAG_ITEM, mode);
794                         os << "\n\\" << t.cs() << " default\n";
795                 }
796
797                 else if (is_known(t.cs(), known_latex_commands) && mode == TEXT_MODE) {
798                         begin_inset(os, "LatexCommand ");
799                         os << '\\' << t.cs() << '{';
800                         parse(p, os, FLAG_ITEM, TEXT_MODE);
801                         os << '}';
802                         end_inset(os);
803                 }
804
805                 else if (t.cs() == "bibitem") {
806                         os << "\n\\layout Bibliography\n\\bibitem ";
807                         string opt = p.getArg('[',']');
808                         if (opt.size())
809                                 os << '[' << opt << ']';
810                         os << '{' << p.getArg('{','}') << '}' << "\n\n";
811                 }
812
813                 else if (char const ** where = is_known(t.cs(), known_quotes)) {
814                         begin_inset(os, "Quotes ");
815                         os << known_coded_quotes[where - known_quotes];
816                         end_inset(os);
817                 }
818
819                 else if (t.cs() == "textasciitilde")
820                         os << '~';
821
822                 else if (t.cs() == "_" && mode == TEXT_MODE)
823                         os << '_';
824
825                 else if (t.cs() == "&" && mode == TEXT_MODE)
826                         os << '&';
827
828                 else if (t.cs() == "pagestyle" && in_preamble)
829                         h_paperpagestyle == p.getArg('{','}');
830
831                 else {
832                         if (mode == MATH_MODE)
833                                 os << t.asInput();
834                         else if (in_preamble)
835                                 h_preamble << t.asInput();
836                         else {
837                                 // heuristic: read up to next non-nested space
838                                 /*
839                                 string s = t.asInput();
840                                 string z = p.verbatimItem();
841                                 while (p.good() && z != " " && z.size()) {
842                                         //cerr << "read: " << z << endl;
843                                         s += z;
844                                         z = p.verbatimItem();
845                                 }
846                                 cerr << "found ERT: " << s << endl;
847                                 handle_ert(os, s + ' ');
848                                 */
849                                 handle_ert(os, t.asInput() + ' ');
850                         }
851                 }
852
853                 if (flags & FLAG_LEAVE) {
854                         flags &= ~FLAG_LEAVE;
855                         break;
856                 }
857         }
858 }
859
860
861
862 } // anonymous namespace
863
864
865 int main(int argc, char * argv[])
866 {
867         if (argc <= 1) {
868                 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
869                 return 2;
870         }
871
872         ifstream is(argv[1]);
873         Parser p(is);
874         parse(p, cout, 0, TEXT_MODE);
875         cout << "\n\\the_end";
876
877         return 0;       
878 }       
879
880 // }])