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
38 #ifndef CXX_GLOBAL_CSTD
48 using boost::regex_match;
51 // TODO: in no particular order
52 // - get rid of the extern BufferList and the call to
53 // BufferList::updateIncludedTeXfiles, this should either
54 // be done before calling LaTeX::funcs or in a completely
56 // - the bibtex command options should be supported.
57 // - the makeindex style files should be taken care of with
58 // the dependency mechanism.
59 // - makeindex commandline options should be supported
60 // - somewhere support viewing of bibtex and makeindex log files.
61 // - we should perhaps also scan the bibtex log file
62 // - we should perhaps also scan the bibtex log file
64 extern BufferList bufferlist;
70 void TeXErrors::insertError(int line, string const & error_desc,
71 string const & error_text)
73 Error newerr(line, error_desc, error_text);
74 errors.push_back(newerr);
81 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
82 : cmd(latex), file(f), path(p)
85 depfile = file + ".dep";
86 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
88 output_file = ChangeExtension(file,".pdf");
90 output_file = ChangeExtension(file,".dvi");
95 void LaTeX::deleteFilesOnError() const
97 // currently just a dummy function.
99 // What files do we have to delete?
101 // This will at least make latex do all the runs
102 lyx::unlink(depfile);
104 // but the reason for the error might be in a generated file...
106 string ofname = OnlyFilename(file);
109 string bbl = ChangeExtension(ofname, ".bbl");
113 string ind = ChangeExtension(ofname, ".ind");
116 // Also remove the aux file
117 string aux = ChangeExtension(ofname, ".aux");
122 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
123 // We know that this function will only be run if the lyx buffer
124 // has been changed. We also know that a newly written .tex file
125 // is always different from the previous one because of the date
126 // in it. However it seems safe to run latex (at least) on time each
127 // time the .tex file changes.
129 int scanres = NO_ERRORS;
130 unsigned int count = 0; // number of times run
131 num_errors = 0; // just to make sure.
132 const unsigned int MAX_RUN = 6;
133 DepTable head; // empty head
134 bool rerun = false; // rerun requested
136 // The class LaTeX does not know the temp path.
137 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
139 // Never write the depfile if an error was encountered.
142 // first check if the file dependencies exist:
143 // ->If it does exist
144 // check if any of the files mentioned in it have
145 // changed (done using a checksum).
147 // run latex once and
148 // remake the dependency file
149 // -> if not changed:
150 // just return there is nothing to do for us.
151 // ->if it doesn't exist
153 // run latex once (we need to run latex once anyway) and
154 // remake the dependency file.
157 FileInfo fi(depfile);
158 bool had_depfile = fi.exist();
159 bool run_bibtex = false;
160 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
163 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
164 // Read the dep file:
166 // Update the checksums
168 // Can't just check if anything has changed because it might have aborted
169 // on error last time... in which cas we need to re-run latex
170 // and collect the error messages (even if they are the same).
171 if (!FileInfo(output_file).exist()) {
172 lyxerr[Debug::DEPEND]
173 << "re-running LaTeX because output file doesn't exist." << endl;
174 } else if (!head.sumchange()) {
175 lyxerr[Debug::DEPEND] << "return no_change" << endl;
178 lyxerr[Debug::DEPEND]
179 << "Dependency file has changed" << endl;
182 if (head.extchanged(".bib") || head.extchanged(".bst"))
185 lyxerr[Debug::DEPEND]
186 << "Dependency file does not exist" << endl;
188 /// We scan the aux file even when had_depfile = false,
189 /// because we can run pdflatex on the file after running latex on it,
190 /// in which case we will not need to run bibtex again.
191 vector<Aux_Info> bibtex_info_old;
193 bibtex_info_old = scanAuxFiles(aux_file);
196 lyxerr[Debug::LATEX] << "Run #" << count << endl;
199 str << _("LaTeX run number") << ' ' << count;
200 // check lyxstring string stream and gcc 3.1 before fixing
201 lfun->dispatch(LFUN_MESSAGE, string(str.str().c_str()));
205 scanres = scanLogFile(terr);
206 if (scanres & ERROR_RERUN) {
207 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
209 scanres = scanLogFile(terr);
212 if (scanres & ERRORS) {
213 deleteFilesOnError();
214 return scanres; // return on error
217 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
218 if (!run_bibtex && bibtex_info_old != bibtex_info)
221 // update the dependencies.
222 deplog(head); // reads the latex log
226 // At this point we must run external programs if needed.
227 // makeindex will be run if a .idx file changed or was generated.
228 // And if there were undefined citations or changes in references
229 // the .aux file is checked for signs of bibtex. Bibtex is then run
233 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
235 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
237 lfun->dispatch(LFUN_MESSAGE, string(_("Running MakeIndex.")));
240 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
244 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
245 if (scanres & UNDEF_CIT || run_bibtex) {
246 // Here we must scan the .aux file and look for
247 // "\bibdata" and/or "\bibstyle". If one of those
248 // tags is found -> run bibtex and set rerun = true;
250 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
252 lfun->dispatch(LFUN_MESSAGE, string(_("Running BibTeX.")));
255 updateBibtexDependencies(head, bibtex_info);
256 rerun |= runBibTeX(bibtex_info);
257 } else if (!had_depfile) {
258 /// If we run pdflatex on the file after running latex on it,
259 /// then we do not need to run bibtex, but we do need to
260 /// insert the .bib and .bst files into the .dep-pdf file.
261 updateBibtexDependencies(head, bibtex_info);
265 // we know on this point that latex has been run once (or we just
266 // returned) and the question now is to decide if we need to run
267 // it any more. This is done by asking if any of the files in the
268 // dependency file has changed. (remember that the checksum for
269 // a given file is reported to have changed if it just was created)
270 // -> if changed or rerun == true:
271 // run latex once more and
272 // update the dependency structure
273 // -> if not changed:
274 // we does nothing at this point
276 if (rerun || head.sumchange()) {
279 lyxerr[Debug::DEPEND]
280 << "Dep. file has changed or rerun requested" << endl;
282 << "Run #" << count << endl;
285 str << _("LaTeX run number") << ' ' << count;
286 // check lyxstring string stream and gcc 3.1 before fixing
287 lfun->dispatch(LFUN_MESSAGE, string(str.str().c_str()));
291 scanres = scanLogFile(terr);
292 if (scanres & ERRORS) {
293 deleteFilesOnError();
294 return scanres; // return on error
297 // update the depedencies
298 deplog(head); // reads the latex log
301 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
305 // The inclusion of files generated by external programs like
306 // makeindex or bibtex might have done changes to pagenumbereing,
307 // etc. And because of this we must run the external programs
308 // again to make sure everything is redone correctly.
309 // Also there should be no need to run the external programs any
312 // run makeindex if the <file>.idx has changed or was generated.
313 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
315 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
317 lfun->dispatch(LFUN_MESSAGE, string(_("Running MakeIndex.")));
320 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
324 // we will only run latex more if the log file asks for it.
325 // or if the sumchange() is true.
326 // -> rerun asked for:
328 // remake the dependency file
329 // goto 2 or return if max runs are reached.
330 // -> rerun not asked for:
331 // just return (fall out of bottom of func)
333 while ((head.sumchange() || rerun || (scanres & RERUN))
334 && count < MAX_RUN) {
335 // Yes rerun until message goes away, or until
336 // MAX_RUNS are reached.
339 lyxerr[Debug::LATEX] << "Run #" << count << endl;
342 str << _("LaTeX run number") << ' ' << count;
343 // check lyxstring string stream and gcc 3.1 before fixing
344 lfun->dispatch(LFUN_MESSAGE, string(str.str().c_str()));
348 scanres = scanLogFile(terr);
349 if (scanres & ERRORS) {
350 deleteFilesOnError();
351 return scanres; // return on error
358 // Write the dependencies to file.
360 lyxerr[Debug::LATEX] << "Done." << endl;
365 int LaTeX::operator()()
368 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
369 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
370 string tmp = cmd + ' ' + file + " > nul";
373 return one.startscript(Systemcall::Wait, tmp);
377 bool LaTeX::runMakeIndex(string const & f)
379 lyxerr[Debug::LATEX] << "idx file has been made,"
380 " running makeindex on file "
383 // It should be possible to set the switches for makeindex
384 // sorting style and such. It would also be very convenient
385 // to be able to make style files from within LyX. This has
386 // to come for a later time.
387 string tmp = "makeindex -c -q ";
390 one.startscript(Systemcall::Wait, tmp);
395 vector<Aux_Info> const
396 LaTeX::scanAuxFiles(string const & file)
398 vector<Aux_Info> result;
400 result.push_back(scanAuxFile(file));
402 for (int i = 1; i < 1000; ++i) {
403 string file2 = ChangeExtension(file, "") + "." + tostr(i)
408 result.push_back(scanAuxFile(file2));
414 Aux_Info const LaTeX::scanAuxFile(string const & file)
417 result.aux_file = file;
418 scanAuxFile(file, result);
423 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
425 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
427 ifstream ifs(file.c_str());
429 regex reg1("\\\\citation\\{([^}]+)\\}");
430 regex reg2("\\\\bibdata\\{([^}]+)\\}");
431 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
432 regex reg4("\\\\@input\\{([^}]+)\\}");
434 while (getline(ifs, token)) {
435 token = strip(token, '\r');
437 if (regex_match(token, sub, reg1)) {
438 string data = sub[1];
439 while (!data.empty()) {
441 data = split(data, citation, ',');
442 lyxerr[Debug::LATEX] << "Citation: "
444 aux_info.citations.insert(citation);
446 } else if (regex_match(token, sub, reg2)) {
447 string data = sub[1];
448 // data is now all the bib files separated by ','
449 // get them one by one and pass them to the helper
450 while (!data.empty()) {
452 data = split(data, database, ',');
453 database = ChangeExtension(database, "bib");
454 lyxerr[Debug::LATEX] << "Bibtex database: `"
455 << database << "'" << endl;
456 aux_info.databases.insert(database);
458 } else if (regex_match(token, sub, reg3)) {
459 string style = sub[1];
460 // token is now the style file
461 // pass it to the helper
462 style = ChangeExtension(style, "bst");
463 lyxerr[Debug::LATEX] << "Bibtex style: `"
464 << style << "'" << endl;
465 aux_info.styles.insert(style);
466 } else if (regex_match(token, sub, reg4)) {
467 string file2 = sub[1];
468 scanAuxFile(file2, aux_info);
474 void LaTeX::updateBibtexDependencies(DepTable & dep,
475 vector<Aux_Info> const & bibtex_info)
477 // Since a run of Bibtex mandates more latex runs it is ok to
478 // remove all ".bib" and ".bst" files.
479 dep.remove_files_with_extension(".bib");
480 dep.remove_files_with_extension(".bst");
481 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
483 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
484 it != bibtex_info.end(); ++it) {
485 for (set<string>::const_iterator it2 = it->databases.begin();
486 it2 != it->databases.end(); ++it2) {
487 string file = findtexfile(*it2, "bib");
489 dep.insert(file, true);
492 for (set<string>::const_iterator it2 = it->styles.begin();
493 it2 != it->styles.end(); ++it2) {
494 string file = findtexfile(*it2, "bst");
496 dep.insert(file, true);
502 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
505 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
506 it != bibtex_info.end(); ++it) {
507 if (it->databases.empty())
511 string tmp = "bibtex ";
512 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
514 one.startscript(Systemcall::Wait, tmp);
516 // Return whether bibtex was run
521 int LaTeX::scanLogFile(TeXErrors & terr)
525 int retval = NO_ERRORS;
526 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
527 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
528 ifstream ifs(tmp.c_str());
531 while (getline(ifs, token)) {
532 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
537 if (prefixIs(token, "LaTeX Warning:")) {
538 // Here shall we handle different
540 retval |= LATEX_WARNING;
541 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
542 if (contains(token, "Rerun to get cross-references")) {
545 << "We should rerun." << endl;
546 } else if (contains(token, "Citation")
547 && contains(token, "on page")
548 && contains(token, "undefined")) {
551 } else if (prefixIs(token, "Package")) {
553 retval |= PACKAGE_WARNING;
554 if (contains(token, "natbib Warning:")) {
556 if (contains(token, "Citation")
557 && contains(token, "on page")
558 && contains(token, "undefined")) {
561 } else if (contains(token, "run BibTeX")) {
563 } else if (contains(token, "Rerun LaTeX") ||
564 contains(token, "Rerun to get")) {
565 // at least longtable.sty and bibtopic.sty
568 << "We should rerun." << endl;
571 } else if (prefixIs(token, "(")) {
572 if (contains(token, "Rerun LaTeX") ||
573 contains(token, "Rerun to get")) {
576 << "We should rerun." << endl;
579 } else if (prefixIs(token, "! ")) {
580 // Ok, we have something that looks like a TeX Error
581 // but what do we really have.
583 // Just get the error description:
584 string desc(token, 2);
585 if (contains(token, "LaTeX Error:"))
586 retval |= LATEX_ERROR;
591 if (!getline(ifs, tmp))
595 } while (!prefixIs(tmp, "l."));
596 if (prefixIs(tmp, "l.")) {
597 // we have a latex error
599 if (contains(desc, "Package babel Error: You haven't defined the language"))
600 retval |= ERROR_RERUN;
601 // get the line number:
603 sscanf(tmp.c_str(), "l.%d", &line);
604 // get the rest of the message:
605 string errstr(tmp, tmp.find(' '));
608 while (!contains(errstr, "l.")
610 && !prefixIs(tmp, "! ")
611 && !contains(tmp, "(job aborted")) {
617 << "line: " << line << '\n'
618 << "Desc: " << desc << '\n'
619 << "Text: " << errstr << endl;
620 if (line == last_line)
626 if (line_count <= 5) {
627 terr.insertError(line, desc, errstr);
632 // information messages, TeX warnings and other
633 // warnings we have not caught earlier.
634 if (prefixIs(token, "Overfull ")) {
635 retval |= TEX_WARNING;
636 } else if (prefixIs(token, "Underfull ")) {
637 retval |= TEX_WARNING;
638 } else if (contains(token, "Rerun to get citations")) {
639 // Natbib seems to use this.
641 } else if (contains(token, "No pages of output")) {
642 // A dvi file was not created
644 } else if (contains(token, "That makes 100 errors")) {
645 // More than 100 errors were reprted
646 retval |= TOO_MANY_ERRORS;
650 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
655 void LaTeX::deplog(DepTable & head)
657 // This function reads the LaTeX log file end extracts all the external
658 // files used by the LaTeX run. The files are then entered into the
661 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
663 regex reg1("\\)* *\\(([^ )]+).*");
664 regex reg2("File: ([^ ]+).*");
665 regex reg3("No file ([^ ]+)\\..*");
666 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
667 // If an index should be created, MikTex does not write a line like
668 // \openout# = 'sample,idx'.
669 // but intstead only a line like this into the log:
670 // Writing index file sample.idx
671 regex reg5("Writing index file ([^ ]+).*");
672 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
674 ifstream ifs(logfile.c_str());
676 // Ok, the scanning of files here is not sufficient.
677 // Sometimes files are named by "File: xxx" only
678 // So I think we should use some regexps to find files instead.
679 // "(\([^ ]+\)" should match the "(file " variant
680 // "File: \([^ ]+\)" should match the "File: file" variant
684 token = strip(token, '\r');
685 if (token.empty()) continue;
688 if (regex_match(token, sub, reg1)) {
690 } else if (regex_match(token, sub, reg2)) {
692 } else if (regex_match(token, sub, reg3)) {
694 } else if (regex_match(token, sub, reg4)) {
696 } else if (regex_match(token, sub, reg5)) {
702 // convert from native os path to unix path
703 foundfile = os::internal_path(foundfile);
705 lyxerr[Debug::DEPEND] << "Found file: "
706 << foundfile << endl;
708 // Ok now we found a file.
709 // Now we should make sure that this is a file that we can
710 // access through the normal paths.
711 // We will not try any fancy search methods to
714 // (1) foundfile is an
715 // absolute path and should
717 if (AbsolutePath(foundfile)) {
718 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
719 << foundfile << endl;
720 // On initial insert we want to do the update at once
721 // since this file can not be a file generated by
723 if (FileInfo(foundfile).exist())
724 head.insert(foundfile, true);
727 // (2) foundfile is in the tmpdir
728 // insert it into head
729 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
730 if (regex_match(foundfile, unwanted)) {
731 lyxerr[Debug::DEPEND]
733 << OnlyFilename(foundfile)
734 << " in the dep file"
736 } else if (suffixIs(foundfile, ".tex")) {
737 // This is a tex file generated by LyX
738 // and latex is not likely to change this
740 lyxerr[Debug::DEPEND]
741 << "Tmpdir TeX file: "
742 << OnlyFilename(foundfile)
744 head.insert(foundfile, true);
746 lyxerr[Debug::DEPEND]
748 << OnlyFilename(foundfile)
750 head.insert(OnlyFilename(foundfile));
753 lyxerr[Debug::DEPEND]
754 << "Not a file or we are unable to find it."
758 // Make sure that the main .tex file is in the dependancy file.
759 head.insert(OnlyFilename(file), true);