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