]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.C
*** empty log message ***
[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 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 == "caption" ||
173                 name == "title" ||
174                 name == "author" ||
175                 name == "paragraph" ||
176                 name == "chapter" ||
177                 name == "chapter*" ||
178                 name == "section" ||
179                 name == "section*" ||
180                 name == "subsection" ||
181                 name == "subsection*" ||
182                 name == "subsubsection" ||
183                 name == "subsubsection*";
184 }
185
186
187 bool is_latex_command(string const & name)
188 {
189         return
190                 name == "cite" ||
191                 name == "label" ||
192                 name == "index" ||
193                 name == "printindex";
194 }
195
196
197 void begin_inset(ostream & os, string const & name)
198 {
199         os << "\n\\begin_inset " << name;
200 }
201
202
203 void end_inset(ostream & os)
204 {
205         os << "\n\\end_inset\n";
206 }
207
208
209 string curr_env()
210 {
211         return active_environments.empty() ? string() : active_environments.top();
212 }
213
214
215 void handle_ert(ostream & os, string const & s)
216 {
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) {
220                 if (*it == '\\')
221                         os << "\n\\backslash\n";
222                 else
223                         os << *it;
224         }
225         end_inset(os);
226 }
227
228
229 void handle_par(ostream & os)
230 {
231         if (active_environments.empty())
232                 return;
233         os << "\n\\layout ";
234         string s = curr_env();
235         if (s == "document") {
236                 os << "Standard\n\n";
237                 return;
238         }
239         if (s == "lyxcode") {
240                 os << "LyX-Code\n\n";
241                 return;
242         }
243         os << cap(s) << "\n\n";
244 }
245
246
247 void handle_package(string const & name, string const & options)
248 {
249         if (name == "a4wide") {
250                 h_papersize = "a4paper";
251                 h_paperpackage = "widemarginsa4";
252         } else if (name == "ae") 
253                 h_fontscheme = "ae";
254         else if (name == "aecompl") 
255                 h_fontscheme = "ae";
256         else if (name == "amsmath") 
257                 h_use_amsmath = "1";
258         else if (name == "amssymb") 
259                 h_use_amsmath = "1";
260         else if (name == "babel") 
261                 ; // ignore this
262         else if (name == "fontenc") 
263                 ; // ignore this
264         else if (name == "inputenc") 
265                 h_inputencoding = options;
266         else if (name == "makeidx") 
267                 ; // ignore this
268         else if (name == "verbatim") 
269                 ; // ignore this
270         else {
271                 if (options.size())
272                         h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
273                 else
274                         h_preamble << "\\usepackage{" << name << "}\n";
275         }
276 }
277
278
279 void handle_table(Parser & p, ostream & os)
280 {
281         // \begin{table} has been read
282         //parse(end
283 }
284
285
286 string wrap(string const & cmd, string const & str)
287 {
288         return OPEN + cmd + ' ' + str + CLOSE;
289 }
290
291
292 void end_preamble(ostream & os)
293 {
294         in_preamble = false;
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";
323 }
324
325
326 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
327 {
328         while (p.good()) {
329                 Token const & t = p.getToken();
330
331 #ifdef FILEDEBUG
332                 cerr << "t: " << t << " flags: " << flags << "\n";
333                 //cell->dump();
334 #endif
335
336                 if (flags & FLAG_ITEM) {
337                         if (t.cat() == catSpace)
338                                 continue;
339
340                         flags &= ~FLAG_ITEM;
341                         if (t.cat() == catBegin) {
342                                 // skip the brace and collect everything to the next matching
343                                 // closing brace
344                                 flags |= FLAG_BRACE_LAST;
345                                 continue;
346                         }
347
348                         // handle only this single token, leave the loop if done
349                         flags |= FLAG_LEAVE;
350                 }
351
352
353                 if (flags & FLAG_BRACED) {
354                         if (t.cat() == catSpace)
355                                 continue;
356
357                         if (t.cat() != catBegin) {
358                                 p.error("opening brace expected");
359                                 return;
360                         }
361
362                         // skip the brace and collect everything to the next matching
363                         // closing brace
364                         flags = FLAG_BRACE_LAST;
365                 }
366
367
368                 if (flags & FLAG_OPTION) {
369                         if (t.cat() == catOther && t.character() == '[') {
370                                 parse(p, os, FLAG_BRACK_LAST, mode);
371                         } else {
372                                 // no option found, put back token and we are done
373                                 p.putback();
374                         }
375                         return;
376                 }
377
378                 //
379                 // cat codes
380                 //
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
389                                         os << "\\[";
390                                         parse(p, os, FLAG_SIMPLE, MATH_MODE);
391                                         os << "\\]";
392                                         p.getToken(); // skip the second '$' token
393                                 } else {
394                                         // simple $...$  stuff
395                                         p.putback();
396                                         os << '$';
397                                         parse(p, os, FLAG_SIMPLE, MATH_MODE);
398                                         os << '$';
399                                 }
400                                 if (mode == TEXT_MODE)
401                                         end_inset(os);
402                         }
403
404                         else if (flags & FLAG_SIMPLE) {
405                                 // this is the end of the formula
406                                 return;
407                         }
408
409                         else {
410                                 cerr << "mode: " << mode << endl;
411                                 p.error("something strange in the parser\n");
412                                 break;
413                         }
414                 }
415
416                 else if (t.cat() == catLetter)
417                         os << t.character();
418
419                 else if (t.cat() == catSpace) 
420                         os << t.character();
421
422                 else if (t.cat() == catNewline)
423                         os << ' ';
424
425                 else if (t.cat() == catSuper)
426                         os << t.character();
427
428                 else if (t.cat() == catSub)
429                         os << t.character();
430
431                 else if (t.cat() == catParameter) {
432                         Token const & n = p.getToken();
433                         os << wrap("macroarg", string(1, n.character()));
434                 }
435
436                 else if (t.cat() == catActive) {
437                         if (t.character() == '~')
438                                 os << (curr_env() == "lyxcode" ? ' ' : '~');
439                         else
440                                 os << t.asInput();
441                 }
442
443                 else if (t.cat() == catBegin) {
444                         os << '{';
445                         parse(p, os, FLAG_BRACE_LAST, mode);    
446                         os << '}';
447                 }
448
449                 else if (t.cat() == catEnd) {
450                         if (flags & FLAG_BRACE_LAST)
451                                 return;
452                         p.error("found '}' unexpectedly");
453                         //lyx::Assert(0);
454                         //add(cell, '}', LM_TC_TEX);
455                 }
456
457                 else if (t.cat() == catAlign) 
458                         os << t.character();
459
460 /*
461                         ++cellcol;
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);
466                         }
467                         cell = &grid.cell(grid.index(cellrow, cellcol));
468                 }
469 */
470
471                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
472                         //cerr << "finished reading option\n";
473                         return;
474                 }
475
476                 else if (t.cat() == catOther)
477                         os << string(1, t.character());
478
479                 else if (t.cat() == catComment) {
480                         string s;
481                         while (p.good()) {
482                                 Token const & t = p.getToken();
483                                 if (t.cat() == catNewline)
484                                         break;
485                                 s += t.asString();
486                         }
487                         //os << wrap("comment", s);
488                         p.skipSpaces();
489                 }
490
491                 //
492                 // control sequences
493                 //
494
495                 else if (t.cs() == "lyxlock") {
496                         // ignored;
497                 }
498
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;
506                                 if (!in_preamble)
507                                         begin_inset(os, "FormulaMacro\n");
508                                 out << "\\" << t.cs() << "{" << name << "}";
509                                 if (opts.size()) 
510                                         out << "[" << opts << "]";
511                                 out << "{" << body << "}";
512                                 if (!in_preamble)
513                                         end_inset(os);
514                         }
515                 }
516
517                 else if (t.cs() == "(") {
518                         begin_inset(os, "Formula");
519                         os << " \\(";
520                         parse(p, os, FLAG_SIMPLE2, MATH_MODE);
521                         os << "\\)";
522                         end_inset(os);
523                 }
524
525                 else if (t.cs() == "[") {
526                         begin_inset(os, "Formula");
527                         os << " \\[";
528                         parse(p, os, FLAG_EQUATION, MATH_MODE);
529                         os << "\\]";
530                         end_inset(os);
531                 }
532
533                 else if (t.cs() == "protect")
534                         // ignore \\protect, will hopefully be re-added during output
535                         ;
536
537                 else if (t.cs() == "begin") {
538                         string const name = p.getArg('{', '}');
539                         active_environments.push(name);
540                         if (name == "document") {
541                                 end_preamble(os);
542                                 parse(p, os, FLAG_END, mode);
543                         } else if (name == "abstract") {
544                                 handle_par(os);
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") {
551                                 handle_table(p, os);
552                                 parse(p, os, FLAG_END, mode);
553                         } else if (name == "thebibliography") {
554                                 p.verbatimItem(); // swallow next arg
555                                 handle_table(p, os);
556                                 parse(p, os, FLAG_END, mode);
557                         } else {
558                                 os << "\\begin{" << name << "}";
559                                 parse(p, os, FLAG_END, mode);
560                         }
561                 }
562
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{"
569                                                 + curr_env() + "}");
570                                 active_environments.pop();
571                                 if (name == "document" || name == "abstract")
572                                         ;
573                                 else if (name == "table")
574                                         ;
575                                 else if (name == "thebibliography")
576                                         ;
577                                 else if (is_math_env(name)) {
578                                         end_inset(os);  
579                                         os << "\\end{" << name << "}";
580                                 } else
581                                         os << "\\end{" << name << "}";
582                                 return;
583                         }
584                         p.error("found 'end' unexpectedly");
585                 }
586
587                 else if (t.cs() == ")") {
588                         if (flags & FLAG_SIMPLE2)
589                                 return;
590                         p.error("found '\\)' unexpectedly");
591                 }
592
593                 else if (t.cs() == "]") {
594                         if (flags & FLAG_EQUATION)
595                                 return;
596                         p.error("found '\\]' unexpectedly");
597                 }
598
599                 else if (t.cs() == "documentclass") {
600                         vector<string> opts;
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('{', '}');
607                 }
608
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());
619                         } else {
620                                 handle_package(name, options);
621                         }
622                 }
623
624                 else if (t.cs() == "newenvironment") {
625                         string const name = p.getArg('{', '}');
626                         p.skipSpaces();
627                         string const begin = p.verbatimItem();
628                         p.skipSpaces();
629                         string const end = p.verbatimItem();
630                         // ignore out mess
631                         if (name != "lyxcode") 
632                                 os << wrap("newenvironment", begin + end); 
633                 }
634
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() + '}');
640                 }
641
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;
649                         else
650                                 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
651                 }
652
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";
660                         else
661                                 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
662                 }
663         
664                 else if (t.cs() == "par")
665                         handle_par(os);
666
667                 else if (is_heading(t.cs())) {
668                         os << "\\layout " << cap(t.cs()) << "\n\n";
669                         parse(p, os, FLAG_ITEM, mode);
670                 }
671
672                 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
673                         ; // swallow this
674
675                 else if (t.cs() == "tableofcontents")
676                         p.verbatimItem(); // swallow this
677
678                 else if (t.cs() == "textrm") {
679                         os << '\\' << t.cs() << '{';
680                         parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
681                         os << '}';
682                 }
683
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";
688                 }
689
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);
694                         os << '}';
695                         end_inset(os);
696                 }
697
698                 else if (t.cs() == "bibitem") {
699                         os << "\n\\layout Bibliography\n\\bibitem ";
700                         string opt = p.getArg('[',']');
701                         if (opt.size())
702                                 os << '[' << opt << ']';
703                         os << '{' << p.getArg('{','}') << '}' << "\n\n";
704                 }
705
706                 else
707                         (in_preamble ? h_preamble : os) << t.asInput();
708
709                 if (flags & FLAG_LEAVE) {
710                         flags &= ~FLAG_LEAVE;
711                         break;
712                 }
713         }
714 }
715
716
717
718 } // anonymous namespace
719
720
721 int main(int argc, char * argv[])
722 {
723         if (argc <= 1) {
724                 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
725                 return 2;
726         }
727
728         ifstream is(argv[1]);
729         Parser p(is);
730         parse(p, cout, 0, TEXT_MODE);
731         cout << "\n\\the_end";
732
733         return 0;       
734 }       
735
736 // }])