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"
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
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;
58 void TeXErrors::insertError(int line, string const & error_desc,
59 string const & error_text)
61 Error newerr(line, error_desc, error_text);
62 errors.push_back(newerr);
69 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
70 : cmd(latex), file(f), path(p)
73 depfile = file + ".dep";
77 void LaTeX::deleteFilesOnError() const
79 // currently just a dummy function.
81 // What files do we have to delete?
83 // This will at least make latex do all the runs
84 ::unlink(depfile.c_str());
86 // but the reason for the error might be in a generated file...
88 string ofname = OnlyFilename(file);
91 string bbl = ChangeExtension(ofname, ".bbl");
92 ::unlink(bbl.c_str());
95 string ind = ChangeExtension(ofname, ".ind");
96 ::unlink(ind.c_str());
98 // Also remove the aux file
99 string aux = ChangeExtension(ofname, ".aux");
100 ::unlink(aux.c_str());
104 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
105 // We know that this function will only be run if the lyx buffer
106 // has been changed. We also know that a newly written .tex file
107 // is always different from the previous one because of the date
108 // in it. However it seems safe to run latex (at least) on time each
109 // time the .tex file changes.
111 int scanres = LaTeX::NO_ERRORS;
112 unsigned int count = 0; // number of times run
113 num_errors = 0; // just to make sure.
114 const unsigned int MAX_RUN = 6;
115 DepTable head; // empty head
116 bool rerun = false; // rerun requested
118 // The class LaTeX does not know the temp path.
119 bufferlist.updateIncludedTeXfiles(GetCWD());
121 // Never write the depfile if an error was encountered.
124 // first check if the file dependencies exist:
125 // ->If it does exist
126 // check if any of the files mentioned in it have
127 // changed (done using a checksum).
129 // run latex once and
130 // remake the dependency file
131 // -> if not changed:
132 // just return there is nothing to do for us.
133 // ->if it doesn't exist
135 // run latex once (we need to run latex once anyway) and
136 // remake the dependency file.
138 FileInfo fi(depfile);
139 bool run_bibtex = false;
141 // Read the dep file:
143 // Update the checksums
146 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
147 if (head.sumchange()) {
149 lyxerr[Debug::DEPEND]
150 << "Dependency file has changed" << endl;
152 << "Run #" << count << endl;
153 minib->Set(string(_("LaTeX run number ")) + tostr(count));
156 scanres = scanLogFile(terr);
157 if (scanres & LaTeX::ERRORS) {
158 deleteFilesOnError();
159 return scanres; // return on error
162 run_bibtex = scanAux(head);
164 lyxerr[Debug::DEPEND]
165 << "Bibtex demands rerun" << endl;
167 lyxerr[Debug::DEPEND] << "return no_change" << endl;
168 return LaTeX::NO_CHANGE;
172 lyxerr[Debug::DEPEND]
173 << "Dependency file does not exist" << endl;
176 << "Run #" << count << endl;
177 head.insert(file, true);
178 minib->Set(string(_("LaTeX run number ")) + tostr(count));
181 scanres = scanLogFile(terr);
182 if (scanres & LaTeX::ERRORS) {
183 deleteFilesOnError();
184 return scanres; // return on error
189 // update the dependencies.
190 deplog(head); // reads the latex log
194 // At this point we must run external programs if needed.
195 // makeindex will be run if a .idx file changed or was generated.
196 // And if there were undefined citations or changes in references
197 // the .aux file is checked for signs of bibtex. Bibtex is then run
201 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
203 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
204 minib->Set(_("Running MakeIndex."));
206 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
210 if (scanres & LaTeX::UNDEF_CIT
211 || scanres & LaTeX::RERUN
213 // Here we must scan the .aux file and look for
214 // "\bibdata" and/or "\bibstyle". If one of those
215 // tags is found -> run bibtex and set rerun = true;
217 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
218 minib->Set(_("Running BibTeX."));
220 rerun = runBibTeX(OnlyFilename(ChangeExtension(file, ".aux")),
225 // we know on this point that latex has been run once (or we just
226 // returned) and the question now is to decide if we need to run
227 // it any more. This is done by asking if any of the files in the
228 // dependency file has changed. (remember that the checksum for
229 // a given file is reported to have changed if it just was created)
230 // -> if changed or rerun == true:
231 // run latex once more and
232 // update the dependency structure
233 // -> if not changed:
234 // we does nothing at this point
236 if (rerun || head.sumchange()) {
239 lyxerr[Debug::DEPEND]
240 << "Dep. file has changed or rerun requested" << endl;
242 << "Run #" << count << endl;
243 minib->Set(string(_("LaTeX run number ")) + tostr(count));
246 scanres = scanLogFile(terr);
247 if (scanres & LaTeX::ERRORS) {
248 deleteFilesOnError();
249 return scanres; // return on error
252 // update the depedencies
253 deplog(head); // reads the latex log
256 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
260 // The inclusion of files generated by external programs like
261 // makeindex or bibtex might have done changes to pagenumbereing,
262 // etc. And because of this we must run the external programs
263 // again to make sure everything is redone correctly.
264 // Also there should be no need to run the external programs any
267 // run makeindex if the <file>.idx has changed or was generated.
268 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
270 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
271 minib->Set(_("Running MakeIndex."));
273 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
277 // we will only run latex more if the log file asks for it.
278 // or if the sumchange() is true.
279 // -> rerun asked for:
281 // remake the dependency file
282 // goto 2 or return if max runs are reached.
283 // -> rerun not asked for:
284 // just return (fall out of bottom of func)
286 while ((head.sumchange() || rerun || (scanres & LaTeX::RERUN))
287 && count < MAX_RUN) {
288 // Yes rerun until message goes away, or until
289 // MAX_RUNS are reached.
292 lyxerr[Debug::LATEX] << "Run #" << count << endl;
293 minib->Set(string(_("LaTeX run number ")) + tostr(count));
296 scanres = scanLogFile(terr);
297 if (scanres & LaTeX::ERRORS) {
298 deleteFilesOnError();
299 return scanres; // return on error
306 // Write the dependencies to file.
308 lyxerr[Debug::LATEX] << "Done." << endl;
313 int LaTeX::operator()()
316 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
317 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
318 string tmp = cmd + ' ' + file + " > nul";
321 return one.startscript(Systemcalls::System, tmp);
325 bool LaTeX::runMakeIndex(string const & f)
327 lyxerr[Debug::LATEX] << "idx file has been made,"
328 " running makeindex on file "
331 // It should be possible to set the switches for makeindex
332 // sorting style and such. It would also be very convenient
333 // to be able to make style files from within LyX. This has
334 // to come for a later time. (0.13 perhaps?)
335 string tmp = "makeindex -c -q ";
338 one.startscript(Systemcalls::System, tmp);
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 ifstream ifs(aux.c_str());
353 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
354 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
355 while (getline(ifs, token)) {
356 if (reg1.exact_match(token)) {
357 LRegex::SubMatches sub = reg1.exec(token);
358 string data = LSubstring(token, sub[1].first,
362 b = data.find_first_of(',', 0);
364 if (b == string::npos)
367 l = data.substr( 0, b - 0);
368 data.erase(0, b + 1);
372 ChangeExtension(l, "bib"), "bib");
373 if (!full_l.empty()) {
374 if (!dep.exist(full_l))
377 } while (b != string::npos);
378 } else if (reg2.exact_match(token)) {
379 LRegex::SubMatches sub = reg2.exec(token);
380 string style = LSubstring(token, sub[1].first,
382 // token is now the style file
383 // pass it to the helper
386 ChangeExtension(style, "bst"),
388 if (!full_l.empty()) {
389 if (!dep.exist(full_l))
398 bool LaTeX::runBibTeX(string const & f, DepTable & dep)
400 // Since a run of Bibtex mandates more latex runs it is ok to
401 // remove all ".bib" and ".bst" files, it is also required to
402 // discover style and database changes.
403 dep.remove_files_with_extension(".bib");
404 dep.remove_files_with_extension(".bst");
405 ifstream ifs(f.c_str());
407 bool using_bibtex = false;
408 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
409 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
410 while (getline(ifs, token)) {
411 if (reg1.exact_match(token)) {
413 LRegex::SubMatches const & sub = reg1.exec(token);
414 string data = LSubstring(token, sub[1].first,
416 // data is now all the bib files separated by ','
417 // get them one by one and pass them to the helper
420 b = data.find_first_of(',', 0);
422 if (b == string::npos)
425 l = data.substr(0, b - 0);
426 data.erase(0, b + 1);
430 ChangeExtension(l, "bib"),
432 lyxerr[Debug::LATEX] << "Bibtex database: `"
433 << full_l << "'" << endl;
434 if (!full_l.empty()) {
435 // add full_l to the dep file.
436 dep.insert(full_l, true);
438 } while (b != string::npos);
439 } else if (reg2.exact_match(token)) {
441 LRegex::SubMatches const & sub = reg2.exec(token);
442 string style = LSubstring(token, sub[1].first,
444 // token is now the style file
445 // pass it to the helper
448 ChangeExtension(style, "bst"),
450 lyxerr[Debug::LATEX] << "Bibtex style: `"
451 << full_l << "'" << endl;
452 if (!full_l.empty()) {
453 // add full_l to the dep file.
454 dep.insert(full_l, true);
460 string tmp = "bibtex ";
461 tmp += OnlyFilename(ChangeExtension(file, string()));
463 one.startscript(Systemcalls::System, tmp);
466 // bibtex was not run.
471 int LaTeX::scanLogFile(TeXErrors & terr)
475 int retval = NO_ERRORS;
476 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
477 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
478 ifstream ifs(tmp.c_str());
481 while (getline(ifs, token)) {
482 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
487 if (prefixIs(token, "LaTeX Warning:")) {
488 // Here shall we handle different
490 retval |= LATEX_WARNING;
491 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
492 if (contains(token, "Rerun to get cross-references")) {
495 << "We should rerun." << endl;
496 } else if (contains(token, "Citation")
497 && contains(token, "on page")
498 && contains(token, "undefined")) {
501 } else if (prefixIs(token, "Package")) {
503 retval |= PACKAGE_WARNING;
504 if (contains(token, "natbib Warning:")) {
506 if (contains(token, "Citation")
507 && contains(token, "on page")
508 && contains(token, "undefined")) {
511 } else if (contains(token, "Rerun LaTeX.")) {
512 // at least longtable.sty might use this.
515 } else if (prefixIs(token, "! ")) {
516 // Ok, we have something that looks like a TeX Error
517 // but what do we really have.
519 // Just get the error description:
520 string desc(token, 2);
521 if (contains(token, "LaTeX Error:"))
522 retval |= LATEX_ERROR;
527 if (!getline(ifs, tmp))
531 } while (!prefixIs(tmp, "l."));
532 if (prefixIs(tmp, "l.")) {
533 // we have a latex error
535 // get the line number:
537 sscanf(tmp.c_str(), "l.%d", &line);
538 // get the rest of the message:
539 string errstr(tmp, tmp.find(' '));
542 while (!contains(errstr, "l.")
544 && !prefixIs(tmp, "! ")
545 && !contains(tmp, "(job aborted")) {
551 << "line: " << line << '\n'
552 << "Desc: " << desc << '\n'
553 << "Text: " << errstr << endl;
554 if (line == last_line)
560 if (line_count <= 5) {
561 terr.insertError(line, desc, errstr);
566 // information messages, TeX warnings and other
567 // warnings we have not caught earlier.
568 if (prefixIs(token, "Overfull ")) {
569 retval |= TEX_WARNING;
570 } else if (prefixIs(token, "Underfull ")) {
571 retval |= TEX_WARNING;
572 } else if (contains(token, "Rerun to get citations")) {
573 // Natbib seems to use this.
575 } else if (contains(token, "No pages of output")) {
576 // A dvi file was not created
578 } else if (contains(token, "That makes 100 errors")) {
579 // More than 100 errors were reprted
580 retval |= TOO_MANY_ERRORS;
584 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
589 void LaTeX::deplog(DepTable & head)
591 // This function reads the LaTeX log file end extracts all the external
592 // files used by the LaTeX run. The files are then entered into the
595 string logfile = OnlyFilename(ChangeExtension(file, ".log"));
597 LRegex reg1(")* *\\(([^ ]+).*");
598 LRegex reg2("File: ([^ ]+).*");
599 LRegex reg3("No file ([^ ]+)\\..*");
600 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
601 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
603 ifstream ifs(logfile.c_str());
605 // Ok, the scanning of files here is not sufficient.
606 // Sometimes files are named by "File: xxx" only
607 // So I think we should use some regexps to find files instead.
608 // "(\([^ ]+\)" should match the "(file " variant
609 // "File: \([^ ]+\)" should match the "File: file" variant
613 if (token.empty()) continue;
615 if (reg1.exact_match(token)) {
616 LRegex::SubMatches const & sub = reg1.exec(token);
617 foundfile = LSubstring(token, sub[1].first,
619 } else if (reg2.exact_match(token)) {
620 LRegex::SubMatches const & sub = reg2.exec(token);
621 foundfile = LSubstring(token, sub[1].first,
623 } else if (reg3.exact_match(token)) {
624 LRegex::SubMatches const & sub = reg3.exec(token);
625 foundfile = LSubstring(token, sub[1].first,
627 } else if (reg4.exact_match(token)) {
628 LRegex::SubMatches const & sub = reg4.exec(token);
629 foundfile = LSubstring(token, sub[1].first,
635 lyxerr[Debug::DEPEND] << "Found file: "
636 << foundfile << endl;
638 // Ok now we found a file.
639 // Now we should make sure that this is a file that we can
640 // access through the normal paths.
641 // We will not try any fance search methods to
644 // (1) foundfile is an
645 // absolute path and should
647 if (AbsolutePath(foundfile)) {
648 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
649 << foundfile << endl;
650 // On inital insert we want to do the update at once
651 // since this file can not be a file generated by
653 head.insert(foundfile, true);
657 // (2) foundfile is in the tmpdir
658 // insert it into head
659 if (FileInfo(OnlyFilename(foundfile)).exist()) {
660 if (unwanted.exact_match(foundfile)) {
661 lyxerr[Debug::DEPEND]
663 << OnlyFilename(foundfile)
664 << " in the dep file"
666 } else if (suffixIs(foundfile, ".tex")) {
667 // This is a tex file generated by LyX
668 // and latex is not likely to change this
670 lyxerr[Debug::DEPEND]
671 << "Tmpdir TeX file: "
672 << OnlyFilename(foundfile)
674 head.insert(foundfile, true);
676 lyxerr[Debug::DEPEND]
678 << OnlyFilename(foundfile)
680 head.insert(OnlyFilename(foundfile));
684 lyxerr[Debug::DEPEND]
685 << "Not a file or we are unable to find it."