]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.C
compilation fix
[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 #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 const char * known_math_envs[] = {"equation", "eqnarray", "eqnarray*",
58 "align", 0};
59
60
61 // some ugly stuff
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";
88
89 // indicates whether we are in the preamble
90 bool in_preamble = true;
91
92 // current stack of nested environments
93 stack<string> active_environments;
94
95
96 string cap(string s)
97 {
98         if (s.size())
99                 s[0] = toupper(s[0]);
100         return s;
101 }
102
103
104 string const trim(string const & a, char const * p = " ")
105 {
106         // lyx::Assert(p);
107
108         if (a.empty() || !*p)
109                 return a;
110
111         string::size_type r = a.find_last_not_of(p);
112         string::size_type l = a.find_first_not_of(p);
113
114         // Is this the minimal test? (lgb)
115         if (r == string::npos && l == string::npos)
116                 return string();
117
118         return a.substr(l, r - l + 1);
119 }
120
121
122 void split(string const & s, vector<string> & result, char delim)
123 {
124         istringstream is(s);    
125         string t;
126         while (getline(is, t, delim))
127                 result.push_back(t);
128 }
129
130
131 string join(vector<string> const & input, char delim)
132 {
133         ostringstream os;
134         for (size_t i = 0; i != input.size(); ++i) {
135                 if (i)
136                         os << delim;    
137                 os << input[i]; 
138         }
139         return os.str();
140 }
141
142
143 void handle_opt(vector<string> & opts, char const ** what, string & target)
144 {
145         if (opts.empty())
146                 return;
147
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";
152                         target = *what;
153                         opts.erase(it);
154                         return;
155                 }
156         }
157 }
158
159
160 bool is_math_env(string const & name)
161 {
162         for (char const ** what = known_math_envs; *what; ++what)
163                 if (*what == name)
164                         return true;
165         return false;
166 }
167
168
169 bool is_heading(string const & name)
170 {
171         return
172                 name == "title" ||
173                 name == "author" ||
174                 name == "paragraph" ||
175                 name == "chapter" ||
176                 name == "chapter*" ||
177                 name == "section" ||
178                 name == "section*" ||
179                 name == "subsection" ||
180                 name == "subsection*" ||
181                 name == "subsubsection" ||
182                 name == "subsubsection*";
183 }
184
185
186 void begin_inset(ostream & os, string const & name)
187 {
188         os << "\n\\begin_inset " << name;
189 }
190
191
192 void end_inset(ostream & os)
193 {
194         os << "\n\\end_inset\n";
195 }
196
197
198 void handle_ert(ostream & os, string const & s)
199 {
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) {
203                 if (*it == '\\')
204                         os << "\n\\backslash\n";
205                 else
206                         os << *it;
207         }
208         end_inset(os);
209 }
210
211
212 void handle_par(ostream & os)
213 {
214         if (active_environments.empty())
215                 return;
216         os << "\n\\layout ";
217         string s = active_environments.top();
218         if (s == "document") {
219                 os << "Standard\n\n";
220                 return;
221         }
222         if (s == "lyxcode") {
223                 os << "LyX-Code\n\n";
224                 return;
225         }
226         os << cap(s) << "\n\n";
227 }
228
229
230 void handle_package(string const & name, string const & options)
231 {
232         if (name == "a4wide") {
233                 h_papersize = "a4paper";
234                 h_paperpackage = "widemarginsa4";
235         } else if (name == "ae") 
236                 h_fontscheme = "ae";
237         else if (name == "aecompl") 
238                 h_fontscheme = "ae";
239         else if (name == "amsmath") 
240                 h_use_amsmath = "1";
241         else if (name == "amssymb") 
242                 h_use_amsmath = "1";
243         else if (name == "babel") 
244                 ; // ignore this
245         else if (name == "fontenc") 
246                 ; // ignore this
247         else if (name == "inputenc") 
248                 h_inputencoding = options;
249         else if (name == "makeidx") 
250                 ; // ignore this
251         else if (name == "verbatim") 
252                 ; // ignore this
253         else {
254                 if (options.size())
255                         h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
256                 else
257                         h_preamble << "\\usepackage{" << name << "}\n";
258         }
259 }
260
261
262 string wrap(string const & cmd, string const & str)
263 {
264         return OPEN + cmd + ' ' + str + CLOSE;
265 }
266
267
268 void end_preamble(ostream & os)
269 {
270         in_preamble = false;
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";
300 }
301
302
303 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
304 {
305         while (p.good()) {
306                 Token const & t = p.getToken();
307
308 #ifdef FILEDEBUG
309                 cerr << "t: " << t << " flags: " << flags << "\n";
310                 //cell->dump();
311 #endif
312
313                 if (flags & FLAG_ITEM) {
314                         if (t.cat() == catSpace)
315                                 continue;
316
317                         flags &= ~FLAG_ITEM;
318                         if (t.cat() == catBegin) {
319                                 // skip the brace and collect everything to the next matching
320                                 // closing brace
321                                 flags |= FLAG_BRACE_LAST;
322                                 continue;
323                         }
324
325                         // handle only this single token, leave the loop if done
326                         flags |= FLAG_LEAVE;
327                 }
328
329
330                 if (flags & FLAG_BRACED) {
331                         if (t.cat() == catSpace)
332                                 continue;
333
334                         if (t.cat() != catBegin) {
335                                 p.error("opening brace expected");
336                                 return;
337                         }
338
339                         // skip the brace and collect everything to the next matching
340                         // closing brace
341                         flags = FLAG_BRACE_LAST;
342                 }
343
344
345                 if (flags & FLAG_OPTION) {
346                         if (t.cat() == catOther && t.character() == '[') {
347                                 parse(p, os, FLAG_BRACK_LAST, mode);
348                         } else {
349                                 // no option found, put back token and we are done
350                                 p.putback();
351                         }
352                         return;
353                 }
354
355                 //
356                 // cat codes
357                 //
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
366                                         os << "\\[";
367                                         parse(p, os, FLAG_SIMPLE, MATH_MODE);
368                                         os << "\\]";
369                                         p.getToken(); // skip the second '$' token
370                                 } else {
371                                         // simple $...$  stuff
372                                         p.putback();
373                                         os << '$';
374                                         parse(p, os, FLAG_SIMPLE, MATH_MODE);
375                                         os << '$';
376                                 }
377                                 if (mode == TEXT_MODE)
378                                         end_inset(os);
379                         }
380
381                         else if (flags & FLAG_SIMPLE) {
382                                 // this is the end of the formula
383                                 return;
384                         }
385
386                         else {
387                                 cerr << "mode: " << mode << endl;
388                                 p.error("something strange in the parser\n");
389                                 break;
390                         }
391                 }
392
393                 else if (t.cat() == catLetter)
394                         os << t.character();
395
396                 else if (t.cat() == catSpace) 
397                         os << t.character();
398
399                 else if (t.cat() == catNewline)
400                         os << ' ';
401
402                 else if (t.cat() == catSuper)
403                         os << t.character();
404
405                 else if (t.cat() == catSub)
406                         os << t.character();
407
408                 else if (t.cat() == catParameter) {
409                         Token const & n = p.getToken();
410                         os << wrap("macroarg", string(1, n.character()));
411                 }
412
413                 else if (t.cat() == catActive)
414                         os << wrap("active", string(1, t.character()));
415
416                 else if (t.cat() == catBegin) {
417                         os << '{';
418                         parse(p, os, FLAG_BRACE_LAST, mode);    
419                         os << '}';
420                 }
421
422                 else if (t.cat() == catEnd) {
423                         if (flags & FLAG_BRACE_LAST)
424                                 return;
425                         p.error("found '}' unexpectedly");
426                         //lyx::Assert(0);
427                         //add(cell, '}', LM_TC_TEX);
428                 }
429
430                 else if (t.cat() == catAlign) 
431                         os << t.character();
432
433 /*
434                         ++cellcol;
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);
439                         }
440                         cell = &grid.cell(grid.index(cellrow, cellcol));
441                 }
442 */
443
444                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
445                         //cerr << "finished reading option\n";
446                         return;
447                 }
448
449                 else if (t.cat() == catOther)
450                         os << string(1, t.character());
451
452                 else if (t.cat() == catComment) {
453                         string s;
454                         while (p.good()) {
455                                 Token const & t = p.getToken();
456                                 if (t.cat() == catNewline)
457                                         break;
458                                 s += t.asString();
459                         }
460                         //os << wrap("comment", s);
461                         p.skipSpaces();
462                 }
463
464                 //
465                 // control sequences
466                 //
467
468                 else if (t.cs() == "lyxlock") {
469                         // ignored;
470                 }
471
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 << "}";
479                                 if (opts.size()) 
480                                         h_preamble << "[" << opts << "]";
481                                 h_preamble << "{" << body << "}\n";
482                         }
483                 }
484
485                 else if (t.cs() == "(") {
486                         begin_inset(os, "Formula");
487                         os << " \\(";
488                         parse(p, os, FLAG_SIMPLE2, MATH_MODE);
489                         os << "\\)";
490                         end_inset(os);
491                 }
492
493                 else if (t.cs() == "[") {
494                         begin_inset(os, "Formula");
495                         os << " \\[";
496                         parse(p, os, FLAG_EQUATION, MATH_MODE);
497                         os << "\\]";
498                         end_inset(os);
499                 }
500
501                 else if (t.cs() == "protect")
502                         // ignore \\protect, will hopefully be re-added during output
503                         ;
504
505                 else if (t.cs() == "begin") {
506                         string const name = p.getArg('{', '}');
507                         active_environments.push(name);
508                         if (name == "document") 
509                                 end_preamble(os);
510                         else if (name == "abstract")
511                                 handle_par(os);
512                         else if (is_math_env(name))
513                                 begin_inset(os, "Formula ");    
514                         else
515                                 os << "\\begin{" << name << "}";
516                         parse(p, os, FLAG_END, mode);
517                 }
518
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")
528                                         ;
529                                 else if (is_math_env(name))
530                                         end_inset(os);  
531                                 else
532                                         os << "\\end{" << name << "}";
533                                 return;
534                         }
535                         p.error("found 'end' unexpectedly");
536                 }
537
538                 else if (t.cs() == ")") {
539                         if (flags & FLAG_SIMPLE2)
540                                 return;
541                         p.error("found '\\)' unexpectedly");
542                 }
543
544                 else if (t.cs() == "]") {
545                         if (flags & FLAG_EQUATION)
546                                 return;
547                         p.error("found '\\]' unexpectedly");
548                 }
549
550                 else if (t.cs() == "documentclass") {
551                         vector<string> opts;
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('{', '}');
558                 }
559
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());
570                         } else {
571                                 handle_package(name, options);
572                         }
573                 }
574
575                 else if (t.cs() == "newenvironment") {
576                         string const name = p.getArg('{', '}');
577                         p.skipSpaces();
578                         string const begin = p.verbatimItem();
579                         p.skipSpaces();
580                         string const end = p.verbatimItem();
581                         // ignore out mess
582                         if (name != "lyxcode") 
583                                 os << wrap("newenvironment", begin + end); 
584                 }
585
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() + '}');
591                 }
592
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;
600                         else
601                                 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
602                 }
603
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";
611                         else
612                                 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
613                 }
614         
615                 else if (t.cs() == "par")
616                         handle_par(os);
617
618                 else if (is_heading(t.cs())) {
619                         os << "\\layout " << cap(t.cs()) << "\n\n";
620                         parse(p, os, FLAG_ITEM, mode);
621                 }
622
623                 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
624                         ; // swallow this
625
626                 else if (t.cs() == "tableofcontents")
627                         p.verbatimItem(); // swallow this
628
629                 else if (t.cs() == "textrm") {
630                         os << '\\' << t.cs() << '{';
631                         parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
632                         os << '}';
633                 }
634
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";
639                 }
640
641                 else if (t.cs() == "index") {
642                         begin_inset(os, "LatexCommand ");
643                         parse(p, os, FLAG_ITEM, TEXT_MODE);
644                         end_inset(os);
645                 }
646
647                 else
648                         (in_preamble ? h_preamble : os) << '\\' << t.asInput();
649
650                 if (flags & FLAG_LEAVE) {
651                         flags &= ~FLAG_LEAVE;
652                         break;
653                 }
654         }
655 }
656
657
658
659 } // anonymous namespace
660
661
662 int main(int argc, char * argv[])
663 {
664         if (argc <= 1) {
665                 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
666                 return 2;
667         }
668
669         ifstream is(argv[1]);
670         Parser p(is);
671         parse(p, cout, 0, TEXT_MODE);
672         cout << "\n\\the_end";
673
674         return 0;       
675 }       
676
677 // }])