1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
5 * Copyright 1995 Matthias Ettrich
6 * Copyright 1995-2001 The LyX Team.
8 * This file is Copyright 1996-2001
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"
33 #include "lyx_gui_misc.h"
42 // TODO: in no particular order
43 // - get rid of the extern BufferList and the call to
44 // BufferList::updateIncludedTeXfiles, this should either
45 // be done before calling LaTeX::funcs or in a completely
47 // - the bibtex command options should be supported.
48 // - the makeindex style files should be taken care of with
49 // the dependency mechanism.
50 // - makeindex commandline options should be supported
51 // - somewhere support viewing of bibtex and makeindex log files.
52 // - we should perhaps also scan the bibtex log file
53 // - we should perhaps also scan the bibtex log file
55 extern BufferList bufferlist;
61 void TeXErrors::insertError(int line, string const & error_desc,
62 string const & error_text)
64 Error newerr(line, error_desc, error_text);
65 errors.push_back(newerr);
72 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
73 : cmd(latex), file(f), path(p)
76 depfile = file + ".dep";
77 if (prefixIs(cmd, "pdf")) // Do we use pdflatex ?
82 void LaTeX::deleteFilesOnError() const
84 // currently just a dummy function.
86 // What files do we have to delete?
88 // This will at least make latex do all the runs
91 // but the reason for the error might be in a generated file...
93 string ofname = OnlyFilename(file);
96 string bbl = ChangeExtension(ofname, ".bbl");
100 string ind = ChangeExtension(ofname, ".ind");
103 // Also remove the aux file
104 string aux = ChangeExtension(ofname, ".aux");
109 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
110 // We know that this function will only be run if the lyx buffer
111 // has been changed. We also know that a newly written .tex file
112 // is always different from the previous one because of the date
113 // in it. However it seems safe to run latex (at least) on time each
114 // time the .tex file changes.
116 int scanres = NO_ERRORS;
117 unsigned int count = 0; // number of times run
118 num_errors = 0; // just to make sure.
119 const unsigned int MAX_RUN = 6;
120 DepTable head; // empty head
121 bool rerun = false; // rerun requested
123 // The class LaTeX does not know the temp path.
124 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
126 // Never write the depfile if an error was encountered.
129 // first check if the file dependencies exist:
130 // ->If it does exist
131 // check if any of the files mentioned in it have
132 // changed (done using a checksum).
134 // run latex once and
135 // remake the dependency file
136 // -> if not changed:
137 // just return there is nothing to do for us.
138 // ->if it doesn't exist
140 // run latex once (we need to run latex once anyway) and
141 // remake the dependency file.
144 FileInfo fi(depfile);
145 bool had_depfile = fi.exist();
146 bool run_bibtex = false;
147 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
150 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
151 // Read the dep file:
153 // Update the checksums
155 if (!head.sumchange()) {
156 lyxerr[Debug::DEPEND] << "return no_change" << endl;
159 lyxerr[Debug::DEPEND]
160 << "Dependency file has changed" << endl;
162 if (head.extchanged(".bib") || head.extchanged(".bst"))
165 lyxerr[Debug::DEPEND]
166 << "Dependency file does not exist" << endl;
168 /// We scan the aux file even when had_depfile = false,
169 /// because we can run pdflatex on the file after running latex on it,
170 /// in which case we will not need to run bibtex again.
171 vector<Aux_Info> bibtex_info_old;
173 bibtex_info_old = scanAuxFiles(aux_file);
176 lyxerr[Debug::LATEX] << "Run #" << count << endl;
179 str << _("LaTeX run number") << ' ' << count;
180 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
184 //WriteStatus(lfun, string(_("LaTeX run number ")) + tostr(count));
186 scanres = scanLogFile(terr);
187 if (scanres & ERROR_RERUN) {
188 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
190 scanres = scanLogFile(terr);
193 if (scanres & ERRORS) {
194 deleteFilesOnError();
195 return scanres; // return on error
198 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
199 if (!run_bibtex && bibtex_info_old != bibtex_info)
202 // update the dependencies.
203 deplog(head); // reads the latex log
207 // At this point we must run external programs if needed.
208 // makeindex will be run if a .idx file changed or was generated.
209 // And if there were undefined citations or changes in references
210 // the .aux file is checked for signs of bibtex. Bibtex is then run
214 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
216 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
217 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
218 // WriteStatus(minib, _("Running MakeIndex."));
219 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
223 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
224 if (scanres & UNDEF_CIT || run_bibtex) {
225 // Here we must scan the .aux file and look for
226 // "\bibdata" and/or "\bibstyle". If one of those
227 // tags is found -> run bibtex and set rerun = true;
229 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
230 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running BibTeX."));
231 //WriteStatus(minib, _("Running BibTeX."));
232 updateBibtexDependencies(head, bibtex_info);
233 rerun |= runBibTeX(bibtex_info);
234 } else if (!had_depfile)
235 /// If we run pdflatex on the file after running latex on it,
236 /// then we do not need to run bibtex, but we do need to
237 /// insert the .bib and .bst files into the .dep-pdf file.
238 updateBibtexDependencies(head, bibtex_info);
241 // we know on this point that latex has been run once (or we just
242 // returned) and the question now is to decide if we need to run
243 // it any more. This is done by asking if any of the files in the
244 // dependency file has changed. (remember that the checksum for
245 // a given file is reported to have changed if it just was created)
246 // -> if changed or rerun == true:
247 // run latex once more and
248 // update the dependency structure
249 // -> if not changed:
250 // we does nothing at this point
252 if (rerun || head.sumchange()) {
255 lyxerr[Debug::DEPEND]
256 << "Dep. file has changed or rerun requested" << endl;
258 << "Run #" << count << endl;
261 str << _("LaTeX run number") << ' ' << count;
262 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
265 // WriteStatus(minib,
266 // string(_("LaTeX run number ")) + tostr(count));
268 scanres = scanLogFile(terr);
269 if (scanres & ERRORS) {
270 deleteFilesOnError();
271 return scanres; // return on error
274 // update the depedencies
275 deplog(head); // reads the latex log
278 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
282 // The inclusion of files generated by external programs like
283 // makeindex or bibtex might have done changes to pagenumbereing,
284 // etc. And because of this we must run the external programs
285 // again to make sure everything is redone correctly.
286 // Also there should be no need to run the external programs any
289 // run makeindex if the <file>.idx has changed or was generated.
290 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
292 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
293 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
294 //WriteStatus(minib, _("Running MakeIndex."));
295 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
299 // we will only run latex more if the log file asks for it.
300 // or if the sumchange() is true.
301 // -> rerun asked for:
303 // remake the dependency file
304 // goto 2 or return if max runs are reached.
305 // -> rerun not asked for:
306 // just return (fall out of bottom of func)
308 while ((head.sumchange() || rerun || (scanres & RERUN))
309 && count < MAX_RUN) {
310 // Yes rerun until message goes away, or until
311 // MAX_RUNS are reached.
314 lyxerr[Debug::LATEX] << "Run #" << count << endl;
317 str << _("LaTeX run number") << ' ' << count;
318 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
321 // WriteStatus(minib, string(_("LaTeX run number ")) + tostr(count));
323 scanres = scanLogFile(terr);
324 if (scanres & ERRORS) {
325 deleteFilesOnError();
326 return scanres; // return on error
333 // Write the dependencies to file.
335 lyxerr[Debug::LATEX] << "Done." << endl;
340 int LaTeX::operator()()
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";
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 "
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 ";
365 one.startscript(Systemcalls::System, tmp);
370 vector<Aux_Info> const
371 LaTeX::scanAuxFiles(string const & file)
373 vector<Aux_Info> result;
375 result.push_back(scanAuxFile(file));
377 for (int i = 1; i < 1000; ++i) {
378 string file2 = ChangeExtension(file, "") + "." + tostr(i)
383 result.push_back(scanAuxFile(file2));
389 Aux_Info const LaTeX::scanAuxFile(string const & file)
392 result.aux_file = file;
393 scanAuxFile(file, result);
398 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
400 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
402 ifstream ifs(file.c_str());
404 LRegex reg1("\\\\citation\\{([^}]+)\\}");
405 LRegex reg2("\\\\bibdata\\{([^}]+)\\}");
406 LRegex reg3("\\\\bibstyle\\{([^}]+)\\}");
407 LRegex reg4("\\\\@input\\{([^}]+)\\}");
409 while (getline(ifs, token)) {
410 token = strip(token, '\r');
411 if (reg1.exact_match(token)) {
412 LRegex::SubMatches const & sub = reg1.exec(token);
413 string data = LSubstring(token, sub[1].first,
415 while (!data.empty()) {
417 data = split(data, citation, ',');
418 lyxerr[Debug::LATEX] << "Citation: "
420 aux_info.citations.insert(citation);
422 } else if (reg2.exact_match(token)) {
423 LRegex::SubMatches const & sub = reg2.exec(token);
424 string data = LSubstring(token, sub[1].first,
426 // data is now all the bib files separated by ','
427 // get them one by one and pass them to the helper
428 while (!data.empty()) {
430 data = split(data, database, ',');
431 database = ChangeExtension(database, "bib");
432 lyxerr[Debug::LATEX] << "Bibtex database: `"
433 << database << "'" << endl;
434 aux_info.databases.insert(database);
436 } else if (reg3.exact_match(token)) {
437 LRegex::SubMatches const & sub = reg3.exec(token);
438 string style = LSubstring(token, sub[1].first,
440 // token is now the style file
441 // pass it to the helper
442 style = ChangeExtension(style, "bst");
443 lyxerr[Debug::LATEX] << "Bibtex style: `"
444 << style << "'" << endl;
445 aux_info.styles.insert(style);
446 } else if (reg4.exact_match(token)) {
447 LRegex::SubMatches const & sub = reg4.exec(token);
448 string file2 = LSubstring(token, sub[1].first,
450 scanAuxFile(file2, aux_info);
456 void LaTeX::updateBibtexDependencies(DepTable & dep,
457 vector<Aux_Info> const & bibtex_info)
459 // Since a run of Bibtex mandates more latex runs it is ok to
460 // remove all ".bib" and ".bst" files.
461 dep.remove_files_with_extension(".bib");
462 dep.remove_files_with_extension(".bst");
463 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
465 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
466 it != bibtex_info.end(); ++it) {
467 for (set<string>::const_iterator it2 = it->databases.begin();
468 it2 != it->databases.end(); ++it2) {
469 string file = findtexfile(*it2, "bib");
471 dep.insert(file, true);
474 for (set<string>::const_iterator it2 = it->styles.begin();
475 it2 != it->styles.end(); ++it2) {
476 string file = findtexfile(*it2, "bst");
478 dep.insert(file, true);
484 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
487 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
488 it != bibtex_info.end(); ++it) {
489 if (it->databases.empty())
493 string tmp = "bibtex ";
494 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
496 one.startscript(Systemcalls::System, tmp);
498 // Return whether bibtex was run
503 int LaTeX::scanLogFile(TeXErrors & terr)
507 int retval = NO_ERRORS;
508 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
509 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
510 ifstream ifs(tmp.c_str());
513 while (getline(ifs, token)) {
514 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
519 if (prefixIs(token, "LaTeX Warning:")) {
520 // Here shall we handle different
522 retval |= LATEX_WARNING;
523 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
524 if (contains(token, "Rerun to get cross-references")) {
527 << "We should rerun." << endl;
528 } else if (contains(token, "Citation")
529 && contains(token, "on page")
530 && contains(token, "undefined")) {
533 } else if (prefixIs(token, "Package")) {
535 retval |= PACKAGE_WARNING;
536 if (contains(token, "natbib Warning:")) {
538 if (contains(token, "Citation")
539 && contains(token, "on page")
540 && contains(token, "undefined")) {
543 } else if (contains(token, "run BibTeX")) {
545 } else if (contains(token, "Rerun LaTeX") ||
546 contains(token, "Rerun to get")) {
547 // at least longtable.sty and bibtopic.sty
550 << "We should rerun." << endl;
553 } else if (prefixIs(token, "(")) {
554 if (contains(token, "Rerun LaTeX") ||
555 contains(token, "Rerun to get")) {
558 << "We should rerun." << endl;
561 } else if (prefixIs(token, "! ")) {
562 // Ok, we have something that looks like a TeX Error
563 // but what do we really have.
565 // Just get the error description:
566 string desc(token, 2);
567 if (contains(token, "LaTeX Error:"))
568 retval |= LATEX_ERROR;
573 if (!getline(ifs, tmp))
577 } while (!prefixIs(tmp, "l."));
578 if (prefixIs(tmp, "l.")) {
579 // we have a latex error
581 if (contains(desc, "Package babel Error: You haven't defined the language"))
582 retval |= ERROR_RERUN;
583 // get the line number:
585 sscanf(tmp.c_str(), "l.%d", &line);
586 // get the rest of the message:
587 string errstr(tmp, tmp.find(' '));
590 while (!contains(errstr, "l.")
592 && !prefixIs(tmp, "! ")
593 && !contains(tmp, "(job aborted")) {
599 << "line: " << line << '\n'
600 << "Desc: " << desc << '\n'
601 << "Text: " << errstr << endl;
602 if (line == last_line)
608 if (line_count <= 5) {
609 terr.insertError(line, desc, errstr);
614 // information messages, TeX warnings and other
615 // warnings we have not caught earlier.
616 if (prefixIs(token, "Overfull ")) {
617 retval |= TEX_WARNING;
618 } else if (prefixIs(token, "Underfull ")) {
619 retval |= TEX_WARNING;
620 } else if (contains(token, "Rerun to get citations")) {
621 // Natbib seems to use this.
623 } else if (contains(token, "No pages of output")) {
624 // A dvi file was not created
626 } else if (contains(token, "That makes 100 errors")) {
627 // More than 100 errors were reprted
628 retval |= TOO_MANY_ERRORS;
632 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
637 void LaTeX::deplog(DepTable & head)
639 // This function reads the LaTeX log file end extracts all the external
640 // files used by the LaTeX run. The files are then entered into the
643 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
645 LRegex reg1("\\)* *\\(([^ )]+).*");
646 LRegex reg2("File: ([^ ]+).*");
647 LRegex reg3("No file ([^ ]+)\\..*");
648 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
649 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
651 ifstream ifs(logfile.c_str());
653 // Ok, the scanning of files here is not sufficient.
654 // Sometimes files are named by "File: xxx" only
655 // So I think we should use some regexps to find files instead.
656 // "(\([^ ]+\)" should match the "(file " variant
657 // "File: \([^ ]+\)" should match the "File: file" variant
661 token = strip(token, '\r');
662 if (token.empty()) continue;
664 if (reg1.exact_match(token)) {
665 LRegex::SubMatches const & sub = reg1.exec(token);
666 foundfile = LSubstring(token, sub[1].first,
668 } else if (reg2.exact_match(token)) {
669 LRegex::SubMatches const & sub = reg2.exec(token);
670 foundfile = LSubstring(token, sub[1].first,
672 } else if (reg3.exact_match(token)) {
673 LRegex::SubMatches const & sub = reg3.exec(token);
674 foundfile = LSubstring(token, sub[1].first,
676 } else if (reg4.exact_match(token)) {
677 LRegex::SubMatches const & sub = reg4.exec(token);
678 foundfile = LSubstring(token, sub[1].first,
684 lyxerr[Debug::DEPEND] << "Found file: "
685 << foundfile << endl;
687 // Ok now we found a file.
688 // Now we should make sure that this is a file that we can
689 // access through the normal paths.
690 // We will not try any fancy search methods to
693 // (1) foundfile is an
694 // absolute path and should
696 if (AbsolutePath(foundfile)) {
697 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
698 << foundfile << endl;
699 // On initial insert we want to do the update at once
700 // since this file can not be a file generated by
702 if (FileInfo(foundfile).exist())
703 head.insert(foundfile, true);
706 // (2) foundfile is in the tmpdir
707 // insert it into head
708 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
709 if (unwanted.exact_match(foundfile)) {
710 lyxerr[Debug::DEPEND]
712 << OnlyFilename(foundfile)
713 << " in the dep file"
715 } else if (suffixIs(foundfile, ".tex")) {
716 // This is a tex file generated by LyX
717 // and latex is not likely to change this
719 lyxerr[Debug::DEPEND]
720 << "Tmpdir TeX file: "
721 << OnlyFilename(foundfile)
723 head.insert(foundfile, true);
725 lyxerr[Debug::DEPEND]
727 << OnlyFilename(foundfile)
729 head.insert(OnlyFilename(foundfile));
732 lyxerr[Debug::DEPEND]
733 << "Not a file or we are unable to find it."
737 // Make sure that the main .tex file is in the dependancy file.
738 head.insert(OnlyFilename(file), true);