]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.C
down to 822 errors on my thesis
[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 <sstream>
14 #include <stack>
15 #include <string>
16 #include <vector>
17
18 #include "texparser.h"
19
20 using std::cout;
21 using std::cerr;
22 using std::endl;
23 using std::fill;
24 using std::getline;
25 using std::ios;
26 using std::ifstream;
27 using std::istream;
28 using std::istringstream;
29 using std::ostream;
30 using std::ostringstream;
31 using std::stack;
32 using std::string;
33 using std::vector;
34
35
36 namespace {
37
38 char const OPEN = '<';
39 char const CLOSE = '>';
40
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};
53
54 const char * known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
55
56
57 // some ugly stuff
58 ostringstream h_preamble;
59 string h_textclass               = "FIXME";
60 string h_options                 = "FIXME";
61 string h_language                = "FIXME";
62 string h_inputencoding           = "FIXME";
63 string h_fontscheme              = "FIXME";
64 string h_graphics                = "default";
65 string h_paperfontsize           = "FIXME";
66 string h_spacing                 = "single";
67 string h_papersize               = "FIXME";
68 string h_paperpackage            = "FIXME";
69 string h_use_geometry            = "0";
70 string h_use_amsmath             = "0";
71 string h_use_natbib              = "0";
72 string h_use_numerical_citations = "0";
73 string h_paperorientation        = "portrait";
74 string h_secnumdepth             = "3";
75 string h_tocdepth                = "3";
76 string h_paragraph_separation    = "indent";
77 string h_defskip                 = "medskip";
78 string h_quotes_language         = "FIXME";
79 string h_quotes_times            = "1";
80 string h_papercolumns            = "1";
81 string h_papersides              = "1";
82 string h_paperpagestyle          = "default";
83 string h_tracking_changes        = "0";
84
85 // indicates whether we are in the preamble
86 bool in_preamble = true;
87
88 // current stack of nested environments
89 stack<string> active_environments;
90
91
92
93 string const trim(string const & a, char const * p = " ")
94 {
95         // lyx::Assert(p);
96
97         if (a.empty() || !*p)
98                 return a;
99
100         string::size_type r = a.find_last_not_of(p);
101         string::size_type l = a.find_first_not_of(p);
102
103         // Is this the minimal test? (lgb)
104         if (r == string::npos && l == string::npos)
105                 return string();
106
107         return a.substr(l, r - l + 1);
108 }
109
110
111 void split(string const & s, vector<string> & result, char delim)
112 {
113         istringstream is(s);    
114         string t;
115         while (getline(is, t, delim))
116                 result.push_back(t);
117 }
118
119
120 string join(vector<string> const & input, char delim)
121 {
122         ostringstream os;
123         for (size_t i = 0; i != input.size(); ++i) {
124                 if (i)
125                         os << delim;    
126                 os << input[i]; 
127         }
128         return os.str();
129 }
130
131
132 void handle_opt(vector<string> & opts, char const ** what, string & target)
133 {
134         if (opts.empty())
135                 return;
136
137         for ( ; what; ++what) {
138                 vector<string>::iterator it = find(opts.begin(), opts.end(), *what);
139                 if (it != opts.end()) {
140                         //cerr << "### found option '" << *what << "'\n";
141                         target = *what;
142                         opts.erase(it);
143                         return;
144                 }
145         }
146 }
147
148
149 void inset_header(ostream & os, string const & name)
150 {
151         os << "\n\\begin_inset " << name;
152 }
153
154
155 void inset_footer(ostream & os)
156 {
157         os << "\n\\end_inset\n";
158 }
159
160
161 void handle_ert(ostream & os, string const & s)
162 {
163         inset_header(os, "ERT");
164         os << "\nstatus Collapsed\n\n\\layout Standard\n\n";
165         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
166                 if (*it == '\\')
167                         os << "\n\\backslash\n";
168                 else
169                         os << *it;
170         }
171         inset_footer(os);
172 }
173
174
175 void handle_par(ostream & os)
176 {
177         if (active_environments.empty())
178                 return;
179         os << "\n\\layout ";
180         string s = active_environments.top();
181         if (s == "document") {
182                 os << "Standard\n\n";
183                 return;
184         }
185         if (s.size()) 
186                 s[0] = toupper(s[0]);   
187         os << s << "\n\n";
188 }
189
190
191 void handle_package(string const & name, string const & options)
192 {
193         if (name == "a4wide") {
194                 h_papersize = "a4paper";
195                 h_paperpackage = "widemarginsa4";
196         } else if (name == "ae") 
197                 h_fontscheme = "ae";
198         else if (name == "aecompl") 
199                 h_fontscheme = "ae";
200         else if (name == "amsmath") 
201                 h_use_amsmath = "1";
202         else if (name == "amssymb") 
203                 h_use_amsmath = "1";
204         else if (name == "babel") 
205                 ; // ignore this
206         else if (name == "fontenc") 
207                 ; // ignore this
208         else if (name == "inputenc") 
209                 h_inputencoding = options;
210         else if (name == "makeidx") 
211                 ; // ignore this
212         else if (name == "verbatim") 
213                 ; // ignore this
214         else {
215                 if (options.size())
216                         h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
217                 else
218                         h_preamble << "\\usepackage{" << name << "}\n";
219         }
220 }
221
222
223 string wrap(string const & cmd, string const & str)
224 {
225         return OPEN + cmd + ' ' + str + CLOSE;
226 }
227
228
229 void end_preamble(ostream & os)
230 {
231         in_preamble = false;
232         os << "# tex2lyx 0.0.2 created this file\n"
233            << "\\lyxformat 222\n"
234            << "\\textclass " << h_textclass << "\n"
235            << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
236            << "\\options " << h_options << "\n"
237            << "\\language " << h_language << "\n"
238            << "\\inputencoding " << h_inputencoding << "\n"
239            << "\\fontscheme " << h_fontscheme << "\n"
240            << "\\graphics " << h_graphics << "\n"
241            << "\\paperfontsize " << h_paperfontsize << "\n"
242            << "\\spacing " << h_spacing << "\n"
243            << "\\papersize " << h_papersize << "\n"
244            << "\\paperpackage " << h_paperpackage << "\n"
245            << "\\use_geometry " << h_use_geometry << "\n"
246            << "\\use_amsmath " << h_use_amsmath << "\n"
247            << "\\use_natbib " << h_use_natbib << "\n"
248            << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
249            << "\\paperorientation " << h_paperorientation << "\n"
250            << "\\secnumdepth " << h_secnumdepth << "\n"
251            << "\\tocdepth " << h_tocdepth << "\n"
252            << "\\paragraph_separation " << h_paragraph_separation << "\n"
253            << "\\defskip " << h_defskip << "\n"
254            << "\\quotes_language " << h_quotes_language << "\n"
255            << "\\quotes_times " << h_quotes_times << "\n"
256            << "\\papercolumns " << h_papercolumns << "\n"
257            << "\\papersides " << h_papersides << "\n"
258            << "\\paperpagestyle " << h_paperpagestyle << "\n"
259            << "\\tracking_changes " << h_tracking_changes << "\n"
260            << h_preamble.str() << "\n";
261 }
262
263
264 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
265 {
266         while (p.good()) {
267                 Token const & t = p.getToken();
268
269 #ifdef FILEDEBUG
270                 cerr << "t: " << t << " flags: " << flags << "\n";
271                 //cell->dump();
272 #endif
273
274                 if (flags & FLAG_ITEM) {
275                         if (t.cat() == catSpace)
276                                 continue;
277
278                         flags &= ~FLAG_ITEM;
279                         if (t.cat() == catBegin) {
280                                 // skip the brace and collect everything to the next matching
281                                 // closing brace
282                                 flags |= FLAG_BRACE_LAST;
283                                 continue;
284                         }
285
286                         // handle only this single token, leave the loop if done
287                         flags |= FLAG_LEAVE;
288                 }
289
290
291                 if (flags & FLAG_BRACED) {
292                         if (t.cat() == catSpace)
293                                 continue;
294
295                         if (t.cat() != catBegin) {
296                                 p.error("opening brace expected");
297                                 return;
298                         }
299
300                         // skip the brace and collect everything to the next matching
301                         // closing brace
302                         flags = FLAG_BRACE_LAST;
303                 }
304
305
306                 if (flags & FLAG_OPTION) {
307                         if (t.cat() == catOther && t.character() == '[') {
308                                 parse(p, os, FLAG_BRACK_LAST, mode);
309                         } else {
310                                 // no option found, put back token and we are done
311                                 p.putback();
312                         }
313                         return;
314                 }
315
316                 //
317                 // cat codes
318                 //
319                 if (t.cat() == catMath) {
320                         if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
321                                 // we are inside some text mode thingy, so opening new math is allowed
322                                 if (mode == TEXT_MODE)
323                                         inset_header(os, "Formula ");
324                                 Token const & n = p.getToken();
325                                 if (n.cat() == catMath) {
326                                         // TeX's $$...$$ syntax for displayed math
327                                         os << "\\[";
328                                         parse(p, os, FLAG_SIMPLE, MATH_MODE);
329                                         os << "\\]";
330                                         p.getToken(); // skip the second '$' token
331                                 } else {
332                                         // simple $...$  stuff
333                                         p.putback();
334                                         os << '$';
335                                         parse(p, os, FLAG_SIMPLE, MATH_MODE);
336                                         os << '$';
337                                 }
338                                 if (mode == TEXT_MODE)
339                                         inset_footer(os);
340                         }
341
342                         else if (flags & FLAG_SIMPLE) {
343                                 // this is the end of the formula
344                                 return;
345                         }
346
347                         else {
348                                 cerr << "mode: " << mode << endl;
349                                 p.error("something strange in the parser\n");
350                                 break;
351                         }
352                 }
353
354                 else if (t.cat() == catLetter)
355                         os << t.character();
356
357                 else if (t.cat() == catSpace) 
358                         os << t.character();
359
360                 else if (t.cat() == catNewline)
361                         os << t.character();
362
363                 else if (t.cat() == catParameter) {
364                         Token const & n = p.getToken();
365                         os << wrap("macroarg", string(1, n.character()));
366                 }
367
368                 else if (t.cat() == catActive)
369                         os << wrap("active", string(1, t.character()));
370
371                 else if (t.cat() == catBegin) {
372                         os << '{';
373                         parse(p, os, FLAG_BRACE_LAST, mode);    
374                         os << '}';
375                 }
376
377                 else if (t.cat() == catEnd) {
378                         if (flags & FLAG_BRACE_LAST)
379                                 return;
380                         p.error("found '}' unexpectedly");
381                         //lyx::Assert(0);
382                         //add(cell, '}', LM_TC_TEX);
383                 }
384
385                 else if (t.cat() == catAlign) 
386                         os << t.character();
387
388 /*
389                         ++cellcol;
390                         //cerr << " column now " << cellcol << " max: " << grid.ncols() << "\n";
391                         if (cellcol == grid.ncols()) {
392                                 //cerr << "adding column " << cellcol << "\n";
393                                 grid.addCol(cellcol - 1);
394                         }
395                         cell = &grid.cell(grid.index(cellrow, cellcol));
396                 }
397 */
398
399                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
400                         //cerr << "finished reading option\n";
401                         return;
402                 }
403
404                 else if (t.cat() == catOther)
405                         os << string(1, t.character());
406
407                 else if (t.cat() == catComment) {
408                         string s;
409                         while (p.good()) {
410                                 Token const & t = p.getToken();
411                                 if (t.cat() == catNewline)
412                                         break;
413                                 s += t.asString();
414                         }
415                         //os << wrap("comment", s);
416                         p.skipSpaces();
417                 }
418
419                 //
420                 // control sequences
421                 //
422
423                 else if (t.cs() == "lyxlock") {
424                         // ignored;
425                 }
426
427                 else if (t.cs() == "newcommand" || t.cs() == "providecommand") {
428                         string const name = p.verbatimItem();
429                         string const opts = p.getArg('[', ']');
430                         string const body = p.verbatimItem();
431                         // only non-lyxspecific stuff
432                         if (name != "noun" && name != "tabularnewline") {
433                                 h_preamble << "\\" << t.cs() << "{" << name << "}";
434                                 if (opts.size()) 
435                                         h_preamble << "[" << opts << "]";
436                                 h_preamble << "{" << body << "}\n";
437                         }
438                 }
439
440                 else if (t.cs() == "(") {
441                         inset_header(os, "Formula");
442                         os << " \\(";
443                         parse(p, os, FLAG_SIMPLE2, MATH_MODE);
444                         os << "\\)";
445                         inset_footer(os);
446                 }
447
448                 else if (t.cs() == "[") {
449                         inset_header(os, "Formula");
450                         os << " \\[";
451                         parse(p, os, FLAG_EQUATION, MATH_MODE);
452                         os << "\\]";
453                         inset_footer(os);
454                 }
455
456                 else if (t.cs() == "protect")
457                         // ignore \\protect, will hopefully be re-added during output
458                         ;
459
460                 else if (t.cs() == "begin") {
461                         string const name = p.getArg('{', '}');
462                         active_environments.push(name);
463                         if (name == "document") 
464                                 end_preamble(os);
465                         else if (name == "abstract")
466                                 handle_par(os);
467                         else
468                                 os << "\\begin{" << name << "}";
469                         parse(p, os, FLAG_END, mode);
470                 }
471
472                 else if (t.cs() == "end") {
473                         if (flags & FLAG_END) {
474                                 // eat environment name
475                                 string const name = p.getArg('{', '}');
476                                 if (name != active_environments.top())
477                                         p.error("\\end{" + name + "} does not match \\begin{"
478                                                 + active_environments.top() + "}");
479                                 active_environments.pop();
480                                 if (name == "document" || name == "abstract")
481                                         ;
482                                 else
483                                         os << "\\end{" << name << "}";
484                                 return;
485                         }
486                         p.error("found 'end' unexpectedly");
487                 }
488
489                 else if (t.cs() == ")") {
490                         if (flags & FLAG_SIMPLE2)
491                                 return;
492                         p.error("found '\\)' unexpectedly");
493                 }
494
495                 else if (t.cs() == "]") {
496                         if (flags & FLAG_EQUATION)
497                                 return;
498                         p.error("found '\\]' unexpectedly");
499                 }
500
501                 else if (t.cs() == "documentclass") {
502                         vector<string> opts;
503                         split(p.getArg('[', ']'), opts, ',');
504                         handle_opt(opts, known_languages, h_language); 
505                         handle_opt(opts, known_fontsizes, h_paperfontsize); 
506                         h_quotes_language = h_language;
507                         h_options = join(opts, ',');
508                         h_textclass = p.getArg('{', '}');
509                 }
510
511                 else if (t.cs() == "usepackage") {
512                         string const options = p.getArg('[', ']');
513                         string const name = p.getArg('{', '}');
514                         if (options.empty() && name.find(',')) {
515                                 vector<string> vecnames;
516                                 split(name, vecnames, ',');
517                                 vector<string>::const_iterator it  = vecnames.begin();
518                                 vector<string>::const_iterator end = vecnames.end();
519                                 for (; it != end; ++it)
520                                         handle_package(trim(*it), string());
521                         } else {
522                                 handle_package(name, options);
523                         }
524                 }
525
526                 else if (t.cs() == "newenvironment") {
527                         string const name = p.getArg('{', '}');
528                         p.skipSpaces();
529                         string const begin = p.verbatimItem();
530                         p.skipSpaces();
531                         string const end = p.verbatimItem();
532                         // ignore out mess
533                         if (name != "lyxcode") 
534                                 os << wrap("newenvironment", begin + end); 
535                 }
536
537                 else if (t.cs() == "def") {
538                         string name = p.getToken().cs();
539                         while (p.nextToken().cat() != catBegin)
540                                 name += p.getToken().asString();
541                         handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
542                 }
543
544                 else if (t.cs() == "setcounter") {
545                         string const name = p.getArg('{', '}');
546                         string const content = p.getArg('{', '}');
547                         if (name == "secnumdepth") 
548                                 h_secnumdepth = content;
549                         else if (name == "tocdepth") 
550                                 h_tocdepth = content;
551                         else
552                                 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
553                 }
554
555                 else if (t.cs() == "setlength") {
556                         string const name = p.getToken().cs();
557                         string const content = p.getArg('{', '}');
558                         if (name == "parskip")
559                                 h_paragraph_separation = "skip";
560                         else if (name == "parindent")
561                                 h_paragraph_separation = "skip";
562                         else
563                                 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
564                 }
565         
566                 else if (t.cs() == "par")
567                         handle_par(os);
568
569                 else if (t.cs() == "title")
570                         os << "\\layout Title\n\n" + p.verbatimItem();
571
572                 else if (t.cs() == "author")
573                         os << "\\layout Author\n\n" + p.verbatimItem();
574
575                 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
576                         ; // swallow this
577
578                 else if (t.cs() == "textrm") {
579                         os << '\\' << t.cs() << '{';
580                         parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
581                         os << '}';
582                 }
583
584                 else if (t.cs() == "emph" && mode == TEXT_MODE) {
585                         os << "\n\\emph on\n";
586                         parse(p, os, FLAG_ITEM, mode);
587                         os << "\n\\emph default\n";
588                 }
589
590                 else 
591                         (in_preamble ? h_preamble : os) << '\\' << t.asString();
592
593                 if (flags & FLAG_LEAVE) {
594                         flags &= ~FLAG_LEAVE;
595                         break;
596                 }
597         }
598 }
599
600
601
602 } // anonymous namespace
603
604
605 int main(int argc, char * argv[])
606 {
607         if (argc <= 1) {
608                 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
609                 return 2;
610         }
611
612         ifstream is(argv[1]);
613         Parser p(is);
614         parse(p, cout, 0, TEXT_MODE);
615         cout << "\n\\the_end";
616
617         return 0;       
618 }       
619
620 // }])