1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
5 * Copyright 1995 Matthias Ettrich
6 * Copyright 1995-2000 The LyX Team.
8 * This file is Copyright 1996-2000
11 * ======================================================
17 #pragma implementation
21 #include "support/filetools.h"
23 #include "support/FileInfo.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"
34 #include "lyx_gui_misc.h"
40 // TODO: in no particular order
41 // - get rid of the extern BufferList and the call to
42 // BufferList::updateIncludedTeXfiles, this should either
43 // be done before calling LaTeX::funcs or in a completely
45 // - the bibtex command options should be supported.
46 // - the makeindex style files should be taken care of with
47 // the dependency mechanism.
48 // - makeindex commandline options should be supported
49 // - somewhere support viewing of bibtex and makeindex log files.
50 // - we should perhaps also scan the bibtex log file
51 // - we should perhaps also scan the bibtex log file
53 extern BufferList bufferlist;
59 void TeXErrors::insertError(int line, string const & error_desc,
60 string const & error_text)
62 Error newerr(line, error_desc, error_text);
63 errors.push_back(newerr);
70 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
71 : cmd(latex), file(f), path(p)
74 depfile = file + ".dep";
75 if (prefixIs(cmd, "pdf")) // Do we use pdflatex ?
80 void LaTeX::deleteFilesOnError() const
82 // currently just a dummy function.
84 // What files do we have to delete?
86 // This will at least make latex do all the runs
89 // but the reason for the error might be in a generated file...
91 string ofname = OnlyFilename(file);
94 string bbl = ChangeExtension(ofname, ".bbl");
98 string ind = ChangeExtension(ofname, ".ind");
101 // Also remove the aux file
102 string aux = ChangeExtension(ofname, ".aux");
107 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
108 // We know that this function will only be run if the lyx buffer
109 // has been changed. We also know that a newly written .tex file
110 // is always different from the previous one because of the date
111 // in it. However it seems safe to run latex (at least) on time each
112 // time the .tex file changes.
114 int scanres = LaTeX::NO_ERRORS;
115 unsigned int count = 0; // number of times run
116 num_errors = 0; // just to make sure.
117 const unsigned int MAX_RUN = 6;
118 DepTable head; // empty head
119 bool rerun = false; // rerun requested
121 // The class LaTeX does not know the temp path.
122 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
124 // Never write the depfile if an error was encountered.
127 // first check if the file dependencies exist:
128 // ->If it does exist
129 // check if any of the files mentioned in it have
130 // changed (done using a checksum).
132 // run latex once and
133 // remake the dependency file
134 // -> if not changed:
135 // just return there is nothing to do for us.
136 // ->if it doesn't exist
138 // run latex once (we need to run latex once anyway) and
139 // remake the dependency file.
141 FileInfo fi(depfile);
142 bool run_bibtex = false;
144 // Read the dep file:
146 // Update the checksums
149 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
150 if (head.sumchange()) {
152 lyxerr[Debug::DEPEND]
153 << "Dependency file has changed" << endl;
155 << "Run #" << count << endl;
157 string(_("LaTeX run number ")) + tostr(count));
159 scanres = scanLogFile(terr);
160 if (scanres & LaTeX::ERRORS) {
161 deleteFilesOnError();
162 return scanres; // return on error
164 run_bibtex = scanAux(head);
166 lyxerr[Debug::DEPEND]
167 << "Bibtex demands rerun" << endl;
169 lyxerr[Debug::DEPEND] << "return no_change" << endl;
170 return LaTeX::NO_CHANGE;
174 lyxerr[Debug::DEPEND]
175 << "Dependency file does not exist" << endl;
178 << "Run #" << count << endl;
179 head.insert(file, true);
181 string(_("LaTeX run number ")) + tostr(count));
183 scanres = scanLogFile(terr);
184 if (scanres & LaTeX::ERRORS) {
185 deleteFilesOnError();
186 return scanres; // return on error
191 // update the dependencies.
192 deplog(head); // reads the latex log
196 // At this point we must run external programs if needed.
197 // makeindex will be run if a .idx file changed or was generated.
198 // And if there were undefined citations or changes in references
199 // the .aux file is checked for signs of bibtex. Bibtex is then run
203 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
205 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
206 WriteStatus(minib, _("Running MakeIndex."));
207 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
211 if (scanres & LaTeX::UNDEF_CIT
212 || scanres & LaTeX::RERUN
214 // Here we must scan the .aux file and look for
215 // "\bibdata" and/or "\bibstyle". If one of those
216 // tags is found -> run bibtex and set rerun = true;
218 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
219 WriteStatus(minib, _("Running BibTeX."));
220 rerun = runBibTeX(head);
224 // we know on this point that latex has been run once (or we just
225 // returned) and the question now is to decide if we need to run
226 // it any more. This is done by asking if any of the files in the
227 // dependency file has changed. (remember that the checksum for
228 // a given file is reported to have changed if it just was created)
229 // -> if changed or rerun == true:
230 // run latex once more and
231 // update the dependency structure
232 // -> if not changed:
233 // we does nothing at this point
235 if (rerun || head.sumchange()) {
238 lyxerr[Debug::DEPEND]
239 << "Dep. file has changed or rerun requested" << endl;
241 << "Run #" << count << endl;
243 string(_("LaTeX run number ")) + tostr(count));
245 scanres = scanLogFile(terr);
246 if (scanres & LaTeX::ERRORS) {
247 deleteFilesOnError();
248 return scanres; // return on error
251 // update the depedencies
252 deplog(head); // reads the latex log
255 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
259 // The inclusion of files generated by external programs like
260 // makeindex or bibtex might have done changes to pagenumbereing,
261 // etc. And because of this we must run the external programs
262 // again to make sure everything is redone correctly.
263 // Also there should be no need to run the external programs any
266 // run makeindex if the <file>.idx has changed or was generated.
267 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
269 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
270 WriteStatus(minib, _("Running MakeIndex."));
271 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
275 // we will only run latex more if the log file asks for it.
276 // or if the sumchange() is true.
277 // -> rerun asked for:
279 // remake the dependency file
280 // goto 2 or return if max runs are reached.
281 // -> rerun not asked for:
282 // just return (fall out of bottom of func)
284 while ((head.sumchange() || rerun || (scanres & LaTeX::RERUN))
285 && count < MAX_RUN) {
286 // Yes rerun until message goes away, or until
287 // MAX_RUNS are reached.
290 lyxerr[Debug::LATEX] << "Run #" << count << endl;
291 WriteStatus(minib, string(_("LaTeX run number ")) + tostr(count));
293 scanres = scanLogFile(terr);
294 if (scanres & LaTeX::ERRORS) {
295 deleteFilesOnError();
296 return scanres; // return on error
303 // Write the dependencies to file.
305 lyxerr[Debug::LATEX] << "Done." << endl;
310 int LaTeX::operator()()
313 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
314 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
315 string tmp = cmd + ' ' + file + " > nul";
318 return one.startscript(Systemcalls::System, tmp);
322 bool LaTeX::runMakeIndex(string const & f)
324 lyxerr[Debug::LATEX] << "idx file has been made,"
325 " running makeindex on file "
328 // It should be possible to set the switches for makeindex
329 // sorting style and such. It would also be very convenient
330 // to be able to make style files from within LyX. This has
331 // to come for a later time. (0.13 perhaps?)
332 string tmp = "makeindex -c -q ";
335 one.startscript(Systemcalls::System, tmp);
339 // scanAux may return a wrong result if there are more than two bibliographies,
340 // and after LaTeX-ing the file, the user changes the order of the bibliography
341 // and run LaTeX again. However, in this case, bibtopic prints a warning message which
342 // is caught by scanLogFile.
343 bool LaTeX::scanAux(DepTable & dep)
345 // if any of the bib file has changed we don't have to
346 // check the .aux file.
347 if (dep.extchanged(".bib")
348 || dep.extchanged(".bst")) return true;
350 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
351 return !scanAuxFiles(aux, dep, false).empty();
355 LaTeX::scanAuxFiles(string const & file, DepTable & dep, bool insert)
357 vector<string> result;
358 if (scanAuxFile(file, dep, insert)) {
359 result.push_back(file);
364 for (int i = 1; i < 1000; ++i) {
365 string file2 = ChangeExtension(file, "") + "." + tostr(i)
370 if (scanAuxFile(file2, dep, insert)) {
371 result.push_back(file2);
380 // If insert = true, then scanAuxFile returns true iff the aux file contains
381 // a bibtex database (i.e. a \bibdata command), or it inputs another auxfile which
382 // contains a bibtex database.
383 // Also the dep is updated for all bibtex databases and bibtex styles in the aux
385 // Ideally, scanAuxFile should return true iff one of the bibtex database/styles has
386 // changes from previous run, or a new bibtex database/styles was added to the aux file.
387 // However, it is probably not worth the effort.
389 // If insert = false, then scanAuxFile returns true iff the aux file contains a
390 // bibtex database or a bibtex style that do not appear in dep.
392 bool LaTeX::scanAuxFile(string const & file, DepTable & dep, bool insert)
394 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
396 ifstream ifs(file.c_str());
398 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
399 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
400 LRegex reg3("\\\\@input\\{([^}]+)\\}");
402 while (getline(ifs, token)) {
403 if (reg1.exact_match(token)) {
406 LRegex::SubMatches const & sub = reg1.exec(token);
407 string data = LSubstring(token, sub[1].first,
409 // data is now all the bib files separated by ','
410 // get them one by one and pass them to the helper
411 while (!data.empty()) {
413 data = split(data, l, ',');
415 findtexfile(ChangeExtension(l, "bib"),
417 lyxerr[Debug::LATEX] << "Bibtex database: `"
418 << full_l << "'" << endl;
419 if (!full_l.empty()) {
421 // add full_l to the dep file.
422 dep.insert(full_l, true);
424 if (!dep.exist(full_l))
428 } else if (reg2.exact_match(token)) {
429 LRegex::SubMatches const & sub = reg2.exec(token);
430 string style = LSubstring(token, sub[1].first,
432 // token is now the style file
433 // pass it to the helper
435 findtexfile(ChangeExtension(style, "bst"),
437 lyxerr[Debug::LATEX] << "Bibtex style: `"
438 << full_l << "'" << endl;
439 if (!full_l.empty()) {
441 // add full_l to the dep file.
442 dep.insert(full_l, true);
444 if (!dep.exist(full_l))
447 } else if (reg3.exact_match(token)) {
448 LRegex::SubMatches const & sub = reg3.exec(token);
449 string file2 = LSubstring(token, sub[1].first,
451 result |= scanAuxFile(file2, dep, insert);
452 if (result && !insert)
460 bool LaTeX::runBibTeX(DepTable & dep)
462 // Since a run of Bibtex mandates more latex runs it is ok to
463 // remove all ".bib" and ".bst" files, it is also required to
464 // discover style and database changes.
465 dep.remove_files_with_extension(".bib");
466 dep.remove_files_with_extension(".bst");
467 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
468 vector<string> const aux_files = scanAuxFiles(aux, dep, true);
469 // Run bibtex on each of the aux files in
470 for (vector<string>::const_iterator it = aux_files.begin();
471 it != aux_files.end(); ++it) {
472 string tmp = "bibtex ";
473 tmp += OnlyFilename(ChangeExtension(*it, string()));
475 one.startscript(Systemcalls::System, tmp);
477 // Return whether bibtex was run
478 return !aux_files.empty();
482 int LaTeX::scanLogFile(TeXErrors & terr)
486 int retval = NO_ERRORS;
487 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
488 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
489 ifstream ifs(tmp.c_str());
492 while (getline(ifs, token)) {
493 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
498 if (prefixIs(token, "LaTeX Warning:")) {
499 // Here shall we handle different
501 retval |= LATEX_WARNING;
502 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
503 if (contains(token, "Rerun to get cross-references")) {
506 << "We should rerun." << endl;
507 } else if (contains(token, "Citation")
508 && contains(token, "on page")
509 && contains(token, "undefined")) {
512 } else if (prefixIs(token, "Package")) {
514 retval |= PACKAGE_WARNING;
515 if (contains(token, "natbib Warning:")) {
517 if (contains(token, "Citation")
518 && contains(token, "on page")
519 && contains(token, "undefined")) {
522 } else if (contains(token, "run BibTeX")) {
524 } else if (contains(token, "Rerun LaTeX.")) {
525 // at least longtable.sty might use this.
528 } else if (prefixIs(token, "! ")) {
529 // Ok, we have something that looks like a TeX Error
530 // but what do we really have.
532 // Just get the error description:
533 string desc(token, 2);
534 if (contains(token, "LaTeX Error:"))
535 retval |= LATEX_ERROR;
540 if (!getline(ifs, tmp))
544 } while (!prefixIs(tmp, "l."));
545 if (prefixIs(tmp, "l.")) {
546 // we have a latex error
548 // get the line number:
550 sscanf(tmp.c_str(), "l.%d", &line);
551 // get the rest of the message:
552 string errstr(tmp, tmp.find(' '));
555 while (!contains(errstr, "l.")
557 && !prefixIs(tmp, "! ")
558 && !contains(tmp, "(job aborted")) {
564 << "line: " << line << '\n'
565 << "Desc: " << desc << '\n'
566 << "Text: " << errstr << endl;
567 if (line == last_line)
573 if (line_count <= 5) {
574 terr.insertError(line, desc, errstr);
579 // information messages, TeX warnings and other
580 // warnings we have not caught earlier.
581 if (prefixIs(token, "Overfull ")) {
582 retval |= TEX_WARNING;
583 } else if (prefixIs(token, "Underfull ")) {
584 retval |= TEX_WARNING;
585 } else if (contains(token, "Rerun to get citations")) {
586 // Natbib seems to use this.
588 } else if (contains(token, "No pages of output")) {
589 // A dvi file was not created
591 } else if (contains(token, "That makes 100 errors")) {
592 // More than 100 errors were reprted
593 retval |= TOO_MANY_ERRORS;
597 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
602 void LaTeX::deplog(DepTable & head)
604 // This function reads the LaTeX log file end extracts all the external
605 // files used by the LaTeX run. The files are then entered into the
608 string logfile = OnlyFilename(ChangeExtension(file, ".log"));
610 LRegex reg1(")* *\\(([^ \\)]+).*");
611 LRegex reg2("File: ([^ ]+).*");
612 LRegex reg3("No file ([^ ]+)\\..*");
613 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
614 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
616 ifstream ifs(logfile.c_str());
618 // Ok, the scanning of files here is not sufficient.
619 // Sometimes files are named by "File: xxx" only
620 // So I think we should use some regexps to find files instead.
621 // "(\([^ ]+\)" should match the "(file " variant
622 // "File: \([^ ]+\)" should match the "File: file" variant
626 if (token.empty()) continue;
628 if (reg1.exact_match(token)) {
629 LRegex::SubMatches const & sub = reg1.exec(token);
630 foundfile = LSubstring(token, sub[1].first,
632 } else if (reg2.exact_match(token)) {
633 LRegex::SubMatches const & sub = reg2.exec(token);
634 foundfile = LSubstring(token, sub[1].first,
636 } else if (reg3.exact_match(token)) {
637 LRegex::SubMatches const & sub = reg3.exec(token);
638 foundfile = LSubstring(token, sub[1].first,
640 } else if (reg4.exact_match(token)) {
641 LRegex::SubMatches const & sub = reg4.exec(token);
642 foundfile = LSubstring(token, sub[1].first,
648 lyxerr[Debug::DEPEND] << "Found file: "
649 << foundfile << endl;
651 // Ok now we found a file.
652 // Now we should make sure that this is a file that we can
653 // access through the normal paths.
654 // We will not try any fancy search methods to
657 // (1) foundfile is an
658 // absolute path and should
660 if (AbsolutePath(foundfile)) {
661 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
662 << foundfile << endl;
663 // On initial insert we want to do the update at once
664 // since this file can not be a file generated by
666 head.insert(foundfile, true);
670 // (2) foundfile is in the tmpdir
671 // insert it into head
672 if (FileInfo(OnlyFilename(foundfile)).exist()) {
673 if (unwanted.exact_match(foundfile)) {
674 lyxerr[Debug::DEPEND]
676 << OnlyFilename(foundfile)
677 << " in the dep file"
679 } else if (suffixIs(foundfile, ".tex")) {
680 // This is a tex file generated by LyX
681 // and latex is not likely to change this
683 lyxerr[Debug::DEPEND]
684 << "Tmpdir TeX file: "
685 << OnlyFilename(foundfile)
687 head.insert(foundfile, true);
689 lyxerr[Debug::DEPEND]
691 << OnlyFilename(foundfile)
693 head.insert(OnlyFilename(foundfile));
697 lyxerr[Debug::DEPEND]
698 << "Not a file or we are unable to find it."