]> git.lyx.org Git - lyx.git/blob - src/LaTeX.C
fb15bb739a0c099f079852500fb08859f1fc00b0
[lyx.git] / src / LaTeX.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor         
5  *           Copyright 1995 Matthias Ettrich
6  *           Copyright 1995-2000 The LyX Team.
7  *
8  *           This file is Copyright 1996-2000
9  *           Lars Gullik Bjønnes
10  *
11  * ====================================================== 
12  */
13
14 #include <config.h>
15
16 #ifdef __GNUG__
17 #pragma implementation
18 #endif
19 #include <fstream>
20
21 #include "support/filetools.h"
22 #include "LaTeX.h"
23 #include "support/FileInfo.h"
24 #include "debug.h"
25 #include "support/lyxlib.h"
26 #include "support/syscall.h"
27 #include "support/syscontr.h"
28 #include "support/path.h"
29 #include "support/LRegex.h"
30 #include "support/LSubstring.h"
31 #include "bufferlist.h"
32 #include "minibuffer.h"
33 #include "gettext.h"
34
35 using std::ifstream;
36 using std::endl;
37
38 // TODO: in no particular order
39 // - get rid of the extern BufferList and the call to
40 //   BufferList::updateIncludedTeXfiles, this should either
41 //   be done before calling LaTeX::funcs or in a completely
42 //   different way.
43 // - the bibtex command options should be supported.
44 // - the makeindex style files should be taken care of with
45 //   the dependency mechanism.
46 // - makeindex commandline options should be supported
47 // - somewhere support viewing of bibtex and makeindex log files.
48 // - we should perhaps also scan the bibtex log file
49 // - we should perhaps also scan the bibtex log file
50
51 extern BufferList bufferlist;
52
53 struct texfile_struct {
54         LaTeX::TEX_FILES file;
55         char const * extension;
56 };
57
58 static
59 const texfile_struct all_files[] = {
60         { LaTeX::AUX, ".aux"},
61         { LaTeX::BBL, ".bbl"},
62         { LaTeX::DVI, ".dvi"},
63         { LaTeX::GLO, ".glo"},
64         { LaTeX::IDX, ".idx"},
65         { LaTeX::IND, ".ind"},
66         { LaTeX::LOF, ".lof"},
67         { LaTeX::LOA, ".loa"},
68         { LaTeX::LOG, ".log"},
69         { LaTeX::LOT, ".lot"},
70         { LaTeX::TOC, ".toc"},
71         { LaTeX::LTX, ".ltx"},
72         { LaTeX::TEX, ".tex"}
73 };
74
75
76 /*
77  * CLASS TEXERRORS
78  */
79
80 void TeXErrors::insertError(int line, string const & error_desc,
81                             string const & error_text)
82 {
83         Error newerr(line, error_desc, error_text);
84         errors.push_back(newerr);
85 }
86
87 /*
88  * CLASS LaTeX
89  */
90
91 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
92                 : cmd(latex), file(f), path(p)
93 {
94         tex_files = NO_FILES;
95         file_count = sizeof(all_files) / sizeof(texfile_struct);
96         num_errors = 0;
97         depfile = file + ".dep";
98 }
99
100
101 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
102         // We know that this function will only be run if the lyx buffer
103         // has been changed. We also know that a newly written .tex file
104         // is always different from the previous one because of the date
105         // in it. However it seems safe to run latex (at least) on time each
106         // time the .tex file changes.
107 {
108         int scanres = LaTeX::NO_ERRORS;
109         unsigned int count = 0; // number of times run
110         num_errors = 0; // just to make sure.
111         const unsigned int MAX_RUN = 6;
112         DepTable head; // empty head
113         bool rerun = false; // rerun requested
114         
115         // The class LaTeX does not know the temp path.
116         bufferlist.updateIncludedTeXfiles(GetCWD());
117         
118         // Never write the depfile if an error was encountered.
119         
120         // 0
121         // first check if the file dependencies exist:
122         //     ->If it does exist
123         //             check if any of the files mentioned in it have
124         //             changed (done using a checksum).
125         //                 -> if changed:
126         //                        run latex once and
127         //                        remake the dependency file
128         //                 -> if not changed:
129         //                        just return there is nothing to do for us.
130         //     ->if it doesn't exist
131         //             make it and
132         //             run latex once (we need to run latex once anyway) and
133         //             remake the dependency file.
134         //
135         FileInfo fi(depfile);
136         bool run_bibtex = false;
137         if (fi.exist()) {
138                 // Read the dep file:
139                 head.read(depfile);
140                 // Update the checksums
141                 head.update();
142                 
143                 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
144                 if (head.sumchange()) {
145                         ++count;
146                         lyxerr[Debug::DEPEND]
147                                 << "Dependency file has changed" << endl;
148                         lyxerr[Debug::LATEX]
149                                 << "Run #" << count << endl; 
150                         minib->Set(string(_("LaTeX run number ")) + tostr(count));
151                         minib->Store();
152                         this->operator()();
153                         scanres = scanLogFile(terr);
154                         if (scanres & LaTeX::ERRORS) return scanres; // return on error
155                         run_bibtex = scanAux(head);
156                         if (run_bibtex)
157                                 lyxerr[Debug::DEPEND]
158                                         << "Bibtex demands rerun" << endl;
159                 } else {
160                         lyxerr[Debug::DEPEND] << "return no_change" << endl;
161                         return LaTeX::NO_CHANGE;
162                 }
163         } else {
164                 ++count;
165                 lyxerr[Debug::DEPEND]
166                         << "Dependency file does not exist" << endl;
167                 lyxerr[Debug::LATEX]
168                         << "Run #" << count << endl;
169                 head.insert(file, true);
170                 minib->Set(string(_("LaTeX run number ")) + tostr(count));
171                 minib->Store();
172                 this->operator()();
173                 scanres = scanLogFile(terr);
174                 if (scanres & LaTeX::ERRORS) return scanres; // return on error
175         }
176
177         // update the dependencies.
178         deplog(head); // reads the latex log
179         deptex(head); // checks for latex files
180         head.update();
181
182         // 0.5
183         // At this point we must run external programs if needed.
184         // makeindex will be run if a .idx file changed or was generated.
185         // And if there were undefined citations or changes in references
186         // the .aux file is checked for signs of bibtex. Bibtex is then run
187         // if needed.
188         
189         // run makeindex
190         if (head.haschanged(ChangeExtension(file, ".idx", true))) {
191                 // no checks for now
192                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
193                 minib->Set(_("Running MakeIndex."));
194                 minib->Store();
195                 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
196         }
197
198         // run bibtex
199         if (scanres & LaTeX::UNDEF_CIT
200             || scanres & LaTeX::RERUN
201             || run_bibtex) {
202                 // Here we must scan the .aux file and look for
203                 // "\bibdata" and/or "\bibstyle". If one of those
204                 // tags is found -> run bibtex and set rerun = true;
205                 // no checks for now
206                 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
207                 minib->Set(_("Running BibTeX."));
208                 minib->Store();
209                 rerun = runBibTeX(ChangeExtension(file, ".aux", true), head);
210         }
211         
212         // 1
213         // we know on this point that latex has been run once (or we just
214         // returned) and the question now is to decide if we need to run
215         // it any more. This is done by asking if any of the files in the
216         // dependency file has changed. (remember that the checksum for
217         // a given file is reported to have changed if it just was created)
218         //     -> if changed or rerun == true:
219         //             run latex once more and
220         //             update the dependency structure
221         //     -> if not changed:
222         //             we does nothing at this point
223         //
224         if (rerun || head.sumchange()) {
225                 rerun = false;
226                 ++count;
227                 lyxerr[Debug::DEPEND]
228                         << "Dep. file has changed or rerun requested" << endl;
229                 lyxerr[Debug::LATEX]
230                         << "Run #" << count << endl;
231                 minib->Set(string(_("LaTeX run number ")) + tostr(count));
232                 minib->Store();
233                 this->operator()();
234                 scanres = scanLogFile(terr);
235                 if (scanres & LaTeX::ERRORS) return scanres; // return on error
236                 // update the depedencies
237                 deplog(head); // reads the latex log
238                 head.update();
239         } else {
240                 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
241         }
242
243         // 1.5
244         // The inclusion of files generated by external programs like
245         // makeindex or bibtex might have done changes to pagenumbereing,
246         // etc. And because of this we must run the external programs
247         // again to make sure everything is redone correctly.
248         // Also there should be no need to run the external programs any
249         // more after this.
250         
251         // run makeindex if the <file>.idx has changed or was generated.
252         if (head.haschanged(ChangeExtension(file, ".idx", true))) {
253                 // no checks for now
254                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
255                 minib->Set(_("Running MakeIndex."));
256                 minib->Store();
257                 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
258         }
259         
260         // 2
261         // we will only run latex more if the log file asks for it.
262         // or if the sumchange() is true.
263         //     -> rerun asked for:
264         //             run latex and
265         //             remake the dependency file
266         //             goto 2 or return if max runs are reached.
267         //     -> rerun not asked for:
268         //             just return (fall out of bottom of func)
269         //
270         while ((head.sumchange() || rerun || (scanres & LaTeX::RERUN)) 
271                && count < MAX_RUN) {
272                 // Yes rerun until message goes away, or until
273                 // MAX_RUNS are reached.
274                 rerun = false;
275                 ++count;
276                 lyxerr[Debug::LATEX] << "Run #" << count << endl;
277                 minib->Set(string(_("LaTeX run number ")) + tostr(count));
278                 minib->Store();
279                 this->operator()();
280                 scanres = scanLogFile(terr);
281                 if (scanres & LaTeX::ERRORS) return scanres; // return on error
282                 // keep this updated
283                 head.update();
284         }
285
286         // Write the dependencies to file.
287         head.write(depfile);
288         lyxerr[Debug::LATEX] << "Done." << endl;
289         return scanres;
290 }
291
292
293 int LaTeX::operator()()
294 {
295 #ifndef __EMX__
296         string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
297 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
298         string tmp = cmd + ' ' + file + " > nul";
299 #endif
300         Systemcalls one;
301         return one.startscript(Systemcalls::System, tmp);
302 }
303
304
305 bool LaTeX::runMakeIndex(string const & f)
306 {
307         lyxerr[Debug::LATEX] << "idx file has been made,"
308                 " running makeindex on file "
309                              <<  f << endl;
310
311         // It should be possible to set the switches for makeindex
312         // sorting style and such. It would also be very convenient
313         // to be able to make style files from within LyX. This has
314         // to come for a later time. (0.13 perhaps?)
315         string tmp = "makeindex -c -q ";
316         tmp += f;
317         Systemcalls one;
318         one.startscript(Systemcalls::System, tmp);
319         return true;
320 }
321
322
323 bool LaTeX::scanAux(DepTable & dep)
324 {
325         // if any of the bib file has changed we don't have to
326         // check the .aux file.
327         if (dep.extchanged(".bib")
328             || dep.extchanged(".bst")) return true;
329         
330         string aux = ChangeExtension(file, ".aux", true);
331         ifstream ifs(aux.c_str());
332         string token;
333         LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
334         LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
335         while (getline(ifs, token)) {
336                 if (reg1.exact_match(token)) {
337                         LRegex::SubMatches sub = reg1.exec(token);
338                         string data = LSubstring(token, sub[1].first,
339                                                  sub[1].second);
340                         string::size_type b;
341                         do {
342                                 b = data.find_first_of(',', 0);
343                                 string l;
344                                 if (b == string::npos)
345                                         l = data;
346                                 else {
347                                         l = data.substr( 0, b - 0);
348                                         data.erase(0, b + 1);
349                                 }
350                                 string full_l =
351                                         findtexfile(
352                                                 ChangeExtension(l, "bib", false), "bib");
353                                 if (!full_l.empty()) {
354                                         if (!dep.exist(full_l))
355                                                 return true;
356                                 }
357                         } while (b != string::npos);
358                 } else if (reg2.exact_match(token)) {
359                         LRegex::SubMatches sub = reg2.exec(token);
360                         string style = LSubstring(token, sub[1].first,
361                                                   sub[1].second);
362                         // token is now the style file
363                         // pass it to the helper
364                         string full_l =
365                                 findtexfile(
366                                         ChangeExtension(style, "bst", false),
367                                         "bst");
368                         if (!full_l.empty()) {
369                                 if (!dep.exist(full_l))
370                                         return true;
371                         }
372                 }
373         }
374         return false;
375 }
376
377
378 bool LaTeX::runBibTeX(string const & f, DepTable & dep)
379 {
380         // Since a run of Bibtex mandates more latex runs it is ok to
381         // remove all ".bib" and ".bst" files, it is also required to
382         // discover style and database changes.
383         dep.remove_files_with_extension(".bib");
384         dep.remove_files_with_extension(".bst");
385         ifstream ifs(f.c_str());
386         string token;
387         bool using_bibtex = false;
388         LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
389         LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
390         while (getline(ifs, token)) {
391                 if (reg1.exact_match(token)) {
392                         using_bibtex = true;
393                         LRegex::SubMatches const & sub = reg1.exec(token);
394                         string data = LSubstring(token, sub[1].first,
395                                                  sub[1].second);
396                         // data is now all the bib files separated by ','
397                         // get them one by one and pass them to the helper
398                         string::size_type b;
399                         do {
400                                 b = data.find_first_of(',', 0);
401                                 string l;
402                                 if (b == string::npos)
403                                         l = data;
404                                 else {
405                                         l = data.substr(0, b - 0);
406                                         data.erase(0, b + 1);
407                                 }
408                                 string full_l = 
409                                         findtexfile(
410                                                 ChangeExtension(l, "bib", false),
411                                                 "bib");
412                                 lyxerr[Debug::LATEX] << "Bibtex database: `"
413                                                      << full_l << "'" << endl;
414                                 if (!full_l.empty()) {
415                                         // add full_l to the dep file.
416                                         dep.insert(full_l, true);
417                                 }
418                         } while (b != string::npos);
419                 } else if (reg2.exact_match(token)) {
420                         using_bibtex = true;
421                         LRegex::SubMatches const & sub = reg2.exec(token);
422                         string style = LSubstring(token, sub[1].first,
423                                                   sub[1].second);
424                         // token is now the style file
425                         // pass it to the helper
426                         string full_l = 
427                                 findtexfile(
428                                         ChangeExtension(style, "bst", false),
429                                         "bst");
430                         lyxerr[Debug::LATEX] << "Bibtex style: `"
431                                              << full_l << "'" << endl;
432                         if (!full_l.empty()) {
433                                 // add full_l to the dep file.
434                                 dep.insert(full_l, true);
435                         }
436                 }
437         }
438         if (using_bibtex) {
439                 // run bibtex and
440                 string tmp = "bibtex ";
441                 tmp += ChangeExtension(file, string(), true);
442                 Systemcalls one;
443                 one.startscript(Systemcalls::System, tmp);
444                 return true;
445         }
446         // bibtex was not run.
447         return false;
448 }
449
450
451 int LaTeX::scanLogFile(TeXErrors & terr)
452 {
453         int last_line = -1;
454         int line_count = 1;
455         int retval = NO_ERRORS;
456         string tmp = ChangeExtension(file, ".log", true);
457         lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
458         ifstream ifs(tmp.c_str());
459
460         string token;
461         while (getline(ifs, token)) {
462                 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
463                 
464                 if (token.empty())
465                         continue;
466
467                 if (prefixIs(token, "LaTeX Warning:")) {
468                         // Here shall we handle different
469                         // types of warnings
470                         retval |= LATEX_WARNING;
471                         lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
472                         if (contains(token, "Rerun to get cross-references")) {
473                                 retval |= RERUN;
474                                 lyxerr[Debug::LATEX]
475                                         << "We should rerun." << endl;
476                         } else if (contains(token, "Citation")
477                                    && contains(token, "on page")
478                                    && contains(token, "undefined")) {
479                                 retval |= UNDEF_CIT;
480                         }
481                 } else if (prefixIs(token, "Package")) {
482                         // Package warnings
483                         retval |= PACKAGE_WARNING;
484                         if (contains(token, "natbib Warning:")) {
485                                 // Natbib warnings
486                                 if (contains(token, "Citation")
487                                     && contains(token, "on page")
488                                     && contains(token, "undefined")) {
489                                         retval |= UNDEF_CIT;
490                                 }
491                         } else if (contains(token, "Rerun LaTeX.")) {
492                                 // at least longtable.sty might use this.
493                                 retval |= RERUN;
494                         }
495                 } else if (prefixIs(token, "! ")) {
496                         // Ok, we have something that looks like a TeX Error
497                         // but what do we really have.
498
499                         // Just get the error description:
500                         string desc(token, 2);
501                         if (contains(token, "LaTeX Error:"))
502                                 retval |= LATEX_ERROR;
503                         // get the next line
504                         string tmp;
505                         int count = 0;
506                         do {
507                                 if (!getline(ifs, tmp))
508                                         break;
509                                 if (++count > 10)
510                                         break;
511                         } while (!prefixIs(tmp, "l."));
512                         if (prefixIs(tmp, "l.")) {
513                                 // we have a latex error
514                                 retval |=  TEX_ERROR;
515                                 // get the line number:
516                                 int line = 0;
517                                 sscanf(tmp.c_str(), "l.%d", &line);
518                                 // get the rest of the message:
519                                 string errstr(tmp, tmp.find(' '));
520                                 errstr += '\n';
521                                 getline(ifs, tmp);
522                                 while (!contains(errstr, "l.")
523                                        && !tmp.empty()
524                                        && !prefixIs(tmp, "! ")
525                                        && !contains(tmp, "(job aborted")) {
526                                         errstr += tmp;
527                                         errstr += "\n";
528                                         getline(ifs, tmp);
529                                 }
530                                 lyxerr[Debug::LATEX]
531                                         << "line: " << line << '\n'
532                                         << "Desc: " << desc << '\n'
533                                         << "Text: " << errstr << endl;
534                                 if (line == last_line)
535                                         ++line_count;
536                                 else {
537                                         line_count = 1;
538                                         last_line = line;
539                                 }
540                                 if (line_count <= 5) {
541                                         terr.insertError(line, desc, errstr);
542                                         ++num_errors;
543                                 }
544                         }
545                 } else {
546                         // information messages, TeX warnings and other
547                         // warnings we have not caught earlier.
548                         if (prefixIs(token, "Overfull ")) {
549                                 retval |= TEX_WARNING;
550                         } else if (prefixIs(token, "Underfull ")) {
551                                 retval |= TEX_WARNING;
552                         } else if (contains(token, "Rerun to get citations")) {
553                                 // Natbib seems to use this.
554                                 retval |= RERUN;
555                         } else if (contains(token, "No pages of output")) {
556                                 // A dvi file was not created
557                                 retval |= NO_OUTPUT;
558                         } else if (contains(token, "That makes 100 errors")) {
559                                 // More than 100 errors were reprted
560                                 retval |= TOO_MANY_ERRORS;
561                         }
562                 }
563         }
564         lyxerr[Debug::LATEX] << "Log line: " << token << endl;
565         return retval;
566 }
567
568
569 void LaTeX::deplog(DepTable & head)
570 {
571         // This function reads the LaTeX log file end extracts all the external
572         // files used by the LaTeX run. The files are then entered into the
573         // dependency file.
574
575         string logfile = ChangeExtension(file, ".log", true);
576         
577         ifstream ifs(logfile.c_str());
578         while (ifs) {
579                 // Now we read chars until we find a '('
580                 char c = 0;
581                 while(ifs.get(c)) {
582                         if (c == '(') break;
583                 };
584                 if (!ifs) break;
585                 
586                 // We now have c == '(', we now read the the sequence of
587                 // chars until reaching EOL, ' ' or ')' and put that
588                 // into a string.
589                 string foundfile;
590                 while (ifs.get(c)) {
591                         if (c == '\n' || c == ' ' || c == ')')
592                                 break;
593                         foundfile += c;
594                 }
595                 lyxerr[Debug::DEPEND] << "Found file: " 
596                                      << foundfile << endl;
597                 
598                 // Ok now we found a file.
599                 // Now we should make sure that
600                 // this is a file that we can
601                 // access through the normal
602                 // paths:
603                 // (1) foundfile is an
604                 //     absolute path and should
605                 //     be inserted.
606                 if (AbsolutePath(foundfile)) {
607                         lyxerr[Debug::DEPEND] << "AbsolutePath file: " 
608                                              << foundfile << endl;
609                         // On inital insert we want to do the update at once
610                         // since this file can not be a file generated by
611                         // the latex run.
612                         head.insert(foundfile, true);
613                         continue;
614                 }
615
616                 // (2) foundfile is in the tmpdir
617                 //     insert it into head
618                 if (FileInfo(OnlyFilename(foundfile)).exist()) {
619                         if (suffixIs(foundfile, ".aux")) {
620                                 lyxerr[Debug::DEPEND] << "We don't want "
621                                                      << OnlyFilename(foundfile)
622                                                      << " in the dep file"
623                                                      << endl;
624                         } else if (suffixIs(foundfile, ".tex")) {
625                                 // This is a tex file generated by LyX
626                                 // and latex is not likely to change this
627                                 // during its runs.
628                                 lyxerr[Debug::DEPEND] << "Tmpdir TeX file: "
629                                                      << OnlyFilename(foundfile)
630                                                      << endl;
631                                 head.insert(foundfile, true);
632                         } else {
633                                 lyxerr[Debug::DEPEND] << "In tmpdir file:"
634                                                      << OnlyFilename(foundfile)
635                                                      << endl;
636                                 head.insert(OnlyFilename(foundfile));
637                         }
638                         continue;
639                 }
640                 lyxerr[Debug::DEPEND]
641                         << "Not a file or we are unable to find it."
642                         << endl;
643         }
644 }
645
646
647 void LaTeX::deptex(DepTable & head)
648 {
649         int except = AUX|LOG|DVI|BBL|IND|GLO; 
650         string tmp;
651         FileInfo fi;
652         for (int i = 0; i < file_count; ++i) {
653                 if (!(all_files[i].file & except)) {
654                         tmp = ChangeExtension(file,
655                                               all_files[i].extension,
656                                               true);
657                         lyxerr[Debug::DEPEND] << "deptex: " << tmp << endl;
658                         if (fi.newFile(tmp).exist())
659                                 head.insert(tmp);
660                 }
661         }
662 }