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 "bufferlist.h"
25 #include "support/filetools.h"
26 #include "support/FileInfo.h"
27 #include "support/lstrings.h"
28 #include "support/lyxlib.h"
29 #include "support/systemcall.h"
30 #include "support/os.h"
31 #include "support/path.h"
33 #include <boost/regex.hpp>
36 #include <cstdio> // sscanf
44 using boost::regex_match;
47 // TODO: in no particular order
48 // - get rid of the extern BufferList and the call to
49 // BufferList::updateIncludedTeXfiles, this should either
50 // be done before calling LaTeX::funcs or in a completely
52 // - the bibtex command options should be supported.
53 // - the makeindex style files should be taken care of with
54 // the dependency mechanism.
55 // - makeindex commandline options should be supported
56 // - somewhere support viewing of bibtex and makeindex log files.
57 // - we should perhaps also scan the bibtex log file
58 // - we should perhaps also scan the bibtex log file
60 extern BufferList bufferlist;
66 void TeXErrors::insertError(int line, string const & error_desc,
67 string const & error_text)
69 Error newerr(line, error_desc, error_text);
70 errors.push_back(newerr);
77 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
78 : cmd(latex), file(f), path(p)
81 depfile = file + ".dep";
82 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
84 output_file = ChangeExtension(file,".pdf");
86 output_file = ChangeExtension(file,".dvi");
91 void LaTeX::deleteFilesOnError() const
93 // currently just a dummy function.
95 // What files do we have to delete?
97 // This will at least make latex do all the runs
100 // but the reason for the error might be in a generated file...
102 string ofname = OnlyFilename(file);
105 string bbl = ChangeExtension(ofname, ".bbl");
109 string ind = ChangeExtension(ofname, ".ind");
112 // Also remove the aux file
113 string aux = ChangeExtension(ofname, ".aux");
118 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
119 // We know that this function will only be run if the lyx buffer
120 // has been changed. We also know that a newly written .tex file
121 // is always different from the previous one because of the date
122 // in it. However it seems safe to run latex (at least) on time each
123 // time the .tex file changes.
125 int scanres = NO_ERRORS;
126 unsigned int count = 0; // number of times run
127 num_errors = 0; // just to make sure.
128 const unsigned int MAX_RUN = 6;
129 DepTable head; // empty head
130 bool rerun = false; // rerun requested
132 // The class LaTeX does not know the temp path.
133 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
135 // Never write the depfile if an error was encountered.
138 // first check if the file dependencies exist:
139 // ->If it does exist
140 // check if any of the files mentioned in it have
141 // changed (done using a checksum).
143 // run latex once and
144 // remake the dependency file
145 // -> if not changed:
146 // just return there is nothing to do for us.
147 // ->if it doesn't exist
149 // run latex once (we need to run latex once anyway) and
150 // remake the dependency file.
153 FileInfo fi(depfile);
154 bool had_depfile = fi.exist();
155 bool run_bibtex = false;
156 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
159 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
160 // Read the dep file:
162 // Update the checksums
164 // Can't just check if anything has changed because it might have aborted
165 // on error last time... in which cas we need to re-run latex
166 // and collect the error messages (even if they are the same).
167 if (!FileInfo(output_file).exist()) {
168 lyxerr[Debug::DEPEND]
169 << "re-running LaTeX because output file doesn't exist." << endl;
170 } else if (!head.sumchange()) {
171 lyxerr[Debug::DEPEND] << "return no_change" << endl;
174 lyxerr[Debug::DEPEND]
175 << "Dependency file has changed" << endl;
178 if (head.extchanged(".bib") || head.extchanged(".bst"))
181 lyxerr[Debug::DEPEND]
182 << "Dependency file does not exist" << endl;
184 /// We scan the aux file even when had_depfile = false,
185 /// because we can run pdflatex on the file after running latex on it,
186 /// in which case we will not need to run bibtex again.
187 vector<Aux_Info> bibtex_info_old;
189 bibtex_info_old = scanAuxFiles(aux_file);
192 lyxerr[Debug::LATEX] << "Run #" << count << endl;
195 str << _("LaTeX run number") << ' ' << count;
196 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
200 scanres = scanLogFile(terr);
201 if (scanres & ERROR_RERUN) {
202 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
204 scanres = scanLogFile(terr);
207 if (scanres & ERRORS) {
208 deleteFilesOnError();
209 return scanres; // return on error
212 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
213 if (!run_bibtex && bibtex_info_old != bibtex_info)
216 // update the dependencies.
217 deplog(head); // reads the latex log
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
228 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
230 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
232 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
235 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
239 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
240 if (scanres & UNDEF_CIT || run_bibtex) {
241 // Here we must scan the .aux file and look for
242 // "\bibdata" and/or "\bibstyle". If one of those
243 // tags is found -> run bibtex and set rerun = true;
245 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
247 lfun->dispatch(LFUN_MESSAGE, _("Running BibTeX."));
250 updateBibtexDependencies(head, bibtex_info);
251 rerun |= runBibTeX(bibtex_info);
252 } else if (!had_depfile) {
253 /// If we run pdflatex on the file after running latex on it,
254 /// then we do not need to run bibtex, but we do need to
255 /// insert the .bib and .bst files into the .dep-pdf file.
256 updateBibtexDependencies(head, bibtex_info);
260 // we know on this point that latex has been run once (or we just
261 // returned) and the question now is to decide if we need to run
262 // it any more. This is done by asking if any of the files in the
263 // dependency file has changed. (remember that the checksum for
264 // a given file is reported to have changed if it just was created)
265 // -> if changed or rerun == true:
266 // run latex once more and
267 // update the dependency structure
268 // -> if not changed:
269 // we does nothing at this point
271 if (rerun || head.sumchange()) {
274 lyxerr[Debug::DEPEND]
275 << "Dep. file has changed or rerun requested" << endl;
277 << "Run #" << count << endl;
280 str << _("LaTeX run number") << ' ' << count;
281 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
285 scanres = scanLogFile(terr);
286 if (scanres & ERRORS) {
287 deleteFilesOnError();
288 return scanres; // return on error
291 // update the depedencies
292 deplog(head); // reads the latex log
295 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
299 // The inclusion of files generated by external programs like
300 // makeindex or bibtex might have done changes to pagenumbereing,
301 // etc. And because of this we must run the external programs
302 // again to make sure everything is redone correctly.
303 // Also there should be no need to run the external programs any
306 // run makeindex if the <file>.idx has changed or was generated.
307 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
309 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
311 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
314 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
318 // we will only run latex more if the log file asks for it.
319 // or if the sumchange() is true.
320 // -> rerun asked for:
322 // remake the dependency file
323 // goto 2 or return if max runs are reached.
324 // -> rerun not asked for:
325 // just return (fall out of bottom of func)
327 while ((head.sumchange() || rerun || (scanres & RERUN))
328 && count < MAX_RUN) {
329 // Yes rerun until message goes away, or until
330 // MAX_RUNS are reached.
333 lyxerr[Debug::LATEX] << "Run #" << count << endl;
336 str << _("LaTeX run number") << ' ' << count;
337 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
341 scanres = scanLogFile(terr);
342 if (scanres & ERRORS) {
343 deleteFilesOnError();
344 return scanres; // return on error
351 // Write the dependencies to file.
353 lyxerr[Debug::LATEX] << "Done." << endl;
358 int LaTeX::operator()()
361 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
362 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
363 string tmp = cmd + ' ' + file + " > nul";
366 return one.startscript(Systemcall::Wait, tmp);
370 bool LaTeX::runMakeIndex(string const & f)
372 lyxerr[Debug::LATEX] << "idx file has been made,"
373 " running makeindex on file "
376 // It should be possible to set the switches for makeindex
377 // sorting style and such. It would also be very convenient
378 // to be able to make style files from within LyX. This has
379 // to come for a later time. (0.13 perhaps?)
380 string tmp = "makeindex -c -q ";
383 one.startscript(Systemcall::Wait, tmp);
388 vector<Aux_Info> const
389 LaTeX::scanAuxFiles(string const & file)
391 vector<Aux_Info> result;
393 result.push_back(scanAuxFile(file));
395 for (int i = 1; i < 1000; ++i) {
396 string file2 = ChangeExtension(file, "") + "." + tostr(i)
401 result.push_back(scanAuxFile(file2));
407 Aux_Info const LaTeX::scanAuxFile(string const & file)
410 result.aux_file = file;
411 scanAuxFile(file, result);
416 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
418 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
420 ifstream ifs(file.c_str());
422 regex reg1("\\\\citation\\{([^}]+)\\}");
423 regex reg2("\\\\bibdata\\{([^}]+)\\}");
424 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
425 regex reg4("\\\\@input\\{([^}]+)\\}");
427 while (getline(ifs, token)) {
428 token = strip(token, '\r');
430 if (regex_match(token, sub, reg1)) {
431 string data = sub[1];
432 while (!data.empty()) {
434 data = split(data, citation, ',');
435 lyxerr[Debug::LATEX] << "Citation: "
437 aux_info.citations.insert(citation);
439 } else if (regex_match(token, sub, reg2)) {
440 string data = sub[1];
441 // data is now all the bib files separated by ','
442 // get them one by one and pass them to the helper
443 while (!data.empty()) {
445 data = split(data, database, ',');
446 database = ChangeExtension(database, "bib");
447 lyxerr[Debug::LATEX] << "Bibtex database: `"
448 << database << "'" << endl;
449 aux_info.databases.insert(database);
451 } else if (regex_match(token, sub, reg3)) {
452 string style = sub[1];
453 // token is now the style file
454 // pass it to the helper
455 style = ChangeExtension(style, "bst");
456 lyxerr[Debug::LATEX] << "Bibtex style: `"
457 << style << "'" << endl;
458 aux_info.styles.insert(style);
459 } else if (regex_match(token, sub, reg4)) {
460 string file2 = sub[1];
461 scanAuxFile(file2, aux_info);
467 void LaTeX::updateBibtexDependencies(DepTable & dep,
468 vector<Aux_Info> const & bibtex_info)
470 // Since a run of Bibtex mandates more latex runs it is ok to
471 // remove all ".bib" and ".bst" files.
472 dep.remove_files_with_extension(".bib");
473 dep.remove_files_with_extension(".bst");
474 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
476 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
477 it != bibtex_info.end(); ++it) {
478 for (set<string>::const_iterator it2 = it->databases.begin();
479 it2 != it->databases.end(); ++it2) {
480 string file = findtexfile(*it2, "bib");
482 dep.insert(file, true);
485 for (set<string>::const_iterator it2 = it->styles.begin();
486 it2 != it->styles.end(); ++it2) {
487 string file = findtexfile(*it2, "bst");
489 dep.insert(file, true);
495 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
498 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
499 it != bibtex_info.end(); ++it) {
500 if (it->databases.empty())
504 string tmp = "bibtex ";
505 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
507 one.startscript(Systemcall::Wait, tmp);
509 // Return whether bibtex was run
514 int LaTeX::scanLogFile(TeXErrors & terr)
518 int retval = NO_ERRORS;
519 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
520 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
521 ifstream ifs(tmp.c_str());
524 while (getline(ifs, token)) {
525 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
530 if (prefixIs(token, "LaTeX Warning:")) {
531 // Here shall we handle different
533 retval |= LATEX_WARNING;
534 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
535 if (contains(token, "Rerun to get cross-references")) {
538 << "We should rerun." << endl;
539 } else if (contains(token, "Citation")
540 && contains(token, "on page")
541 && contains(token, "undefined")) {
544 } else if (prefixIs(token, "Package")) {
546 retval |= PACKAGE_WARNING;
547 if (contains(token, "natbib Warning:")) {
549 if (contains(token, "Citation")
550 && contains(token, "on page")
551 && contains(token, "undefined")) {
554 } else if (contains(token, "run BibTeX")) {
556 } else if (contains(token, "Rerun LaTeX") ||
557 contains(token, "Rerun to get")) {
558 // at least longtable.sty and bibtopic.sty
561 << "We should rerun." << endl;
564 } else if (prefixIs(token, "(")) {
565 if (contains(token, "Rerun LaTeX") ||
566 contains(token, "Rerun to get")) {
569 << "We should rerun." << endl;
572 } else if (prefixIs(token, "! ")) {
573 // Ok, we have something that looks like a TeX Error
574 // but what do we really have.
576 // Just get the error description:
577 string desc(token, 2);
578 if (contains(token, "LaTeX Error:"))
579 retval |= LATEX_ERROR;
584 if (!getline(ifs, tmp))
588 } while (!prefixIs(tmp, "l."));
589 if (prefixIs(tmp, "l.")) {
590 // we have a latex error
592 if (contains(desc, "Package babel Error: You haven't defined the language"))
593 retval |= ERROR_RERUN;
594 // get the line number:
596 sscanf(tmp.c_str(), "l.%d", &line);
597 // get the rest of the message:
598 string errstr(tmp, tmp.find(' '));
601 while (!contains(errstr, "l.")
603 && !prefixIs(tmp, "! ")
604 && !contains(tmp, "(job aborted")) {
610 << "line: " << line << '\n'
611 << "Desc: " << desc << '\n'
612 << "Text: " << errstr << endl;
613 if (line == last_line)
619 if (line_count <= 5) {
620 terr.insertError(line, desc, errstr);
625 // information messages, TeX warnings and other
626 // warnings we have not caught earlier.
627 if (prefixIs(token, "Overfull ")) {
628 retval |= TEX_WARNING;
629 } else if (prefixIs(token, "Underfull ")) {
630 retval |= TEX_WARNING;
631 } else if (contains(token, "Rerun to get citations")) {
632 // Natbib seems to use this.
634 } else if (contains(token, "No pages of output")) {
635 // A dvi file was not created
637 } else if (contains(token, "That makes 100 errors")) {
638 // More than 100 errors were reprted
639 retval |= TOO_MANY_ERRORS;
643 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
648 void LaTeX::deplog(DepTable & head)
650 // This function reads the LaTeX log file end extracts all the external
651 // files used by the LaTeX run. The files are then entered into the
654 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
656 regex reg1("\\)* *\\(([^ )]+).*");
657 regex reg2("File: ([^ ]+).*");
658 regex reg3("No file ([^ ]+)\\..*");
659 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
660 // If an index should be created, MikTex does not write a line like
661 // \openout# = 'sample,idx'.
662 // but intstead only a line like this into the log:
663 // Writing index file sample.idx
664 regex reg5("Writing index file ([^ ]+).*");
665 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
667 ifstream ifs(logfile.c_str());
669 // Ok, the scanning of files here is not sufficient.
670 // Sometimes files are named by "File: xxx" only
671 // So I think we should use some regexps to find files instead.
672 // "(\([^ ]+\)" should match the "(file " variant
673 // "File: \([^ ]+\)" should match the "File: file" variant
677 token = strip(token, '\r');
678 if (token.empty()) continue;
681 if (regex_match(token, sub, reg1)) {
683 } else if (regex_match(token, sub, reg2)) {
685 } else if (regex_match(token, sub, reg3)) {
687 } else if (regex_match(token, sub, reg4)) {
689 } else if (regex_match(token, sub, reg5)) {
695 // convert from native os path to unix path
696 foundfile = os::internal_path(foundfile);
698 lyxerr[Debug::DEPEND] << "Found file: "
699 << foundfile << endl;
701 // Ok now we found a file.
702 // Now we should make sure that this is a file that we can
703 // access through the normal paths.
704 // We will not try any fancy search methods to
707 // (1) foundfile is an
708 // absolute path and should
710 if (AbsolutePath(foundfile)) {
711 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
712 << foundfile << endl;
713 // On initial insert we want to do the update at once
714 // since this file can not be a file generated by
716 if (FileInfo(foundfile).exist())
717 head.insert(foundfile, true);
720 // (2) foundfile is in the tmpdir
721 // insert it into head
722 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
723 if (regex_match(foundfile, unwanted)) {
724 lyxerr[Debug::DEPEND]
726 << OnlyFilename(foundfile)
727 << " in the dep file"
729 } else if (suffixIs(foundfile, ".tex")) {
730 // This is a tex file generated by LyX
731 // and latex is not likely to change this
733 lyxerr[Debug::DEPEND]
734 << "Tmpdir TeX file: "
735 << OnlyFilename(foundfile)
737 head.insert(foundfile, true);
739 lyxerr[Debug::DEPEND]
741 << OnlyFilename(foundfile)
743 head.insert(OnlyFilename(foundfile));
746 lyxerr[Debug::DEPEND]
747 << "Not a file or we are unable to find it."
751 // Make sure that the main .tex file is in the dependancy file.
752 head.insert(OnlyFilename(file), true);