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
22 #include "bufferlist.h"
26 #include "support/filetools.h"
27 #include "support/FileInfo.h"
28 #include "support/LRegex.h"
29 #include "support/LSubstring.h"
30 #include "support/lstrings.h"
31 #include "support/lyxlib.h"
32 #include "support/systemcall.h"
33 #include "support/os.h"
34 #include "support/path.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 ?
79 output_file = ChangeExtension(file,".pdf");
81 output_file = ChangeExtension(file,".dvi");
86 void LaTeX::deleteFilesOnError() const
88 // currently just a dummy function.
90 // What files do we have to delete?
92 // This will at least make latex do all the runs
95 // but the reason for the error might be in a generated file...
97 string ofname = OnlyFilename(file);
100 string bbl = ChangeExtension(ofname, ".bbl");
104 string ind = ChangeExtension(ofname, ".ind");
107 // Also remove the aux file
108 string aux = ChangeExtension(ofname, ".aux");
113 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
114 // We know that this function will only be run if the lyx buffer
115 // has been changed. We also know that a newly written .tex file
116 // is always different from the previous one because of the date
117 // in it. However it seems safe to run latex (at least) on time each
118 // time the .tex file changes.
120 int scanres = NO_ERRORS;
121 unsigned int count = 0; // number of times run
122 num_errors = 0; // just to make sure.
123 const unsigned int MAX_RUN = 6;
124 DepTable head; // empty head
125 bool rerun = false; // rerun requested
127 // The class LaTeX does not know the temp path.
128 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
130 // Never write the depfile if an error was encountered.
133 // first check if the file dependencies exist:
134 // ->If it does exist
135 // check if any of the files mentioned in it have
136 // changed (done using a checksum).
138 // run latex once and
139 // remake the dependency file
140 // -> if not changed:
141 // just return there is nothing to do for us.
142 // ->if it doesn't exist
144 // run latex once (we need to run latex once anyway) and
145 // remake the dependency file.
148 FileInfo fi(depfile);
149 bool had_depfile = fi.exist();
150 bool run_bibtex = false;
151 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
154 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
155 // Read the dep file:
157 // Update the checksums
159 // Can't just check if anything has changed because it might have aborted
160 // on error last time... in which cas we need to re-run latex
161 // and collect the error messages (even if they are the same).
162 if (!FileInfo(output_file).exist()) {
163 lyxerr[Debug::DEPEND]
164 << "re-running LaTeX because output file doesn't exist." << endl;
165 } else if (!head.sumchange()) {
166 lyxerr[Debug::DEPEND] << "return no_change" << endl;
169 lyxerr[Debug::DEPEND]
170 << "Dependency file has changed" << endl;
173 if (head.extchanged(".bib") || head.extchanged(".bst"))
176 lyxerr[Debug::DEPEND]
177 << "Dependency file does not exist" << endl;
179 /// We scan the aux file even when had_depfile = false,
180 /// because we can run pdflatex on the file after running latex on it,
181 /// in which case we will not need to run bibtex again.
182 vector<Aux_Info> bibtex_info_old;
184 bibtex_info_old = scanAuxFiles(aux_file);
187 lyxerr[Debug::LATEX] << "Run #" << count << endl;
190 str << _("LaTeX run number") << ' ' << count;
191 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
195 scanres = scanLogFile(terr);
196 if (scanres & ERROR_RERUN) {
197 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
199 scanres = scanLogFile(terr);
202 if (scanres & ERRORS) {
203 deleteFilesOnError();
204 return scanres; // return on error
207 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
208 if (!run_bibtex && bibtex_info_old != bibtex_info)
211 // update the dependencies.
212 deplog(head); // reads the latex log
216 // At this point we must run external programs if needed.
217 // makeindex will be run if a .idx file changed or was generated.
218 // And if there were undefined citations or changes in references
219 // the .aux file is checked for signs of bibtex. Bibtex is then run
223 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
225 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
227 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
230 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
234 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
235 if (scanres & UNDEF_CIT || run_bibtex) {
236 // Here we must scan the .aux file and look for
237 // "\bibdata" and/or "\bibstyle". If one of those
238 // tags is found -> run bibtex and set rerun = true;
240 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
242 lfun->dispatch(LFUN_MESSAGE, _("Running BibTeX."));
245 updateBibtexDependencies(head, bibtex_info);
246 rerun |= runBibTeX(bibtex_info);
247 } else if (!had_depfile) {
248 /// If we run pdflatex on the file after running latex on it,
249 /// then we do not need to run bibtex, but we do need to
250 /// insert the .bib and .bst files into the .dep-pdf file.
251 updateBibtexDependencies(head, bibtex_info);
255 // we know on this point that latex has been run once (or we just
256 // returned) and the question now is to decide if we need to run
257 // it any more. This is done by asking if any of the files in the
258 // dependency file has changed. (remember that the checksum for
259 // a given file is reported to have changed if it just was created)
260 // -> if changed or rerun == true:
261 // run latex once more and
262 // update the dependency structure
263 // -> if not changed:
264 // we does nothing at this point
266 if (rerun || head.sumchange()) {
269 lyxerr[Debug::DEPEND]
270 << "Dep. file has changed or rerun requested" << endl;
272 << "Run #" << count << endl;
275 str << _("LaTeX run number") << ' ' << count;
276 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
280 scanres = scanLogFile(terr);
281 if (scanres & ERRORS) {
282 deleteFilesOnError();
283 return scanres; // return on error
286 // update the depedencies
287 deplog(head); // reads the latex log
290 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
294 // The inclusion of files generated by external programs like
295 // makeindex or bibtex might have done changes to pagenumbereing,
296 // etc. And because of this we must run the external programs
297 // again to make sure everything is redone correctly.
298 // Also there should be no need to run the external programs any
301 // run makeindex if the <file>.idx has changed or was generated.
302 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
304 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
306 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
309 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
313 // we will only run latex more if the log file asks for it.
314 // or if the sumchange() is true.
315 // -> rerun asked for:
317 // remake the dependency file
318 // goto 2 or return if max runs are reached.
319 // -> rerun not asked for:
320 // just return (fall out of bottom of func)
322 while ((head.sumchange() || rerun || (scanres & RERUN))
323 && count < MAX_RUN) {
324 // Yes rerun until message goes away, or until
325 // MAX_RUNS are reached.
328 lyxerr[Debug::LATEX] << "Run #" << count << endl;
331 str << _("LaTeX run number") << ' ' << count;
332 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
336 scanres = scanLogFile(terr);
337 if (scanres & ERRORS) {
338 deleteFilesOnError();
339 return scanres; // return on error
346 // Write the dependencies to file.
348 lyxerr[Debug::LATEX] << "Done." << endl;
353 int LaTeX::operator()()
356 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
357 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
358 string tmp = cmd + ' ' + file + " > nul";
361 return one.startscript(Systemcall::Wait, tmp);
365 bool LaTeX::runMakeIndex(string const & f)
367 lyxerr[Debug::LATEX] << "idx file has been made,"
368 " running makeindex on file "
371 // It should be possible to set the switches for makeindex
372 // sorting style and such. It would also be very convenient
373 // to be able to make style files from within LyX. This has
374 // to come for a later time. (0.13 perhaps?)
375 string tmp = "makeindex -c -q ";
378 one.startscript(Systemcall::Wait, tmp);
383 vector<Aux_Info> const
384 LaTeX::scanAuxFiles(string const & file)
386 vector<Aux_Info> result;
388 result.push_back(scanAuxFile(file));
390 for (int i = 1; i < 1000; ++i) {
391 string file2 = ChangeExtension(file, "") + "." + tostr(i)
396 result.push_back(scanAuxFile(file2));
402 Aux_Info const LaTeX::scanAuxFile(string const & file)
405 result.aux_file = file;
406 scanAuxFile(file, result);
411 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
413 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
415 ifstream ifs(file.c_str());
417 LRegex reg1("\\\\citation\\{([^}]+)\\}");
418 LRegex reg2("\\\\bibdata\\{([^}]+)\\}");
419 LRegex reg3("\\\\bibstyle\\{([^}]+)\\}");
420 LRegex reg4("\\\\@input\\{([^}]+)\\}");
422 while (getline(ifs, token)) {
423 token = strip(token, '\r');
424 if (reg1.exact_match(token)) {
425 LRegex::SubMatches const & sub = reg1.exec(token);
426 string data = LSubstring(token, sub[1].first,
428 while (!data.empty()) {
430 data = split(data, citation, ',');
431 lyxerr[Debug::LATEX] << "Citation: "
433 aux_info.citations.insert(citation);
435 } else if (reg2.exact_match(token)) {
436 LRegex::SubMatches const & sub = reg2.exec(token);
437 string data = LSubstring(token, sub[1].first,
439 // data is now all the bib files separated by ','
440 // get them one by one and pass them to the helper
441 while (!data.empty()) {
443 data = split(data, database, ',');
444 database = ChangeExtension(database, "bib");
445 lyxerr[Debug::LATEX] << "Bibtex database: `"
446 << database << "'" << endl;
447 aux_info.databases.insert(database);
449 } else if (reg3.exact_match(token)) {
450 LRegex::SubMatches const & sub = reg3.exec(token);
451 string style = LSubstring(token, sub[1].first,
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 (reg4.exact_match(token)) {
460 LRegex::SubMatches const & sub = reg4.exec(token);
461 string file2 = LSubstring(token, sub[1].first,
463 scanAuxFile(file2, aux_info);
469 void LaTeX::updateBibtexDependencies(DepTable & dep,
470 vector<Aux_Info> const & bibtex_info)
472 // Since a run of Bibtex mandates more latex runs it is ok to
473 // remove all ".bib" and ".bst" files.
474 dep.remove_files_with_extension(".bib");
475 dep.remove_files_with_extension(".bst");
476 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
478 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
479 it != bibtex_info.end(); ++it) {
480 for (set<string>::const_iterator it2 = it->databases.begin();
481 it2 != it->databases.end(); ++it2) {
482 string file = findtexfile(*it2, "bib");
484 dep.insert(file, true);
487 for (set<string>::const_iterator it2 = it->styles.begin();
488 it2 != it->styles.end(); ++it2) {
489 string file = findtexfile(*it2, "bst");
491 dep.insert(file, true);
497 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
500 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
501 it != bibtex_info.end(); ++it) {
502 if (it->databases.empty())
506 string tmp = "bibtex ";
507 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
509 one.startscript(Systemcall::Wait, tmp);
511 // Return whether bibtex was run
516 int LaTeX::scanLogFile(TeXErrors & terr)
520 int retval = NO_ERRORS;
521 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
522 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
523 ifstream ifs(tmp.c_str());
526 while (getline(ifs, token)) {
527 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
532 if (prefixIs(token, "LaTeX Warning:")) {
533 // Here shall we handle different
535 retval |= LATEX_WARNING;
536 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
537 if (contains(token, "Rerun to get cross-references")) {
540 << "We should rerun." << endl;
541 } else if (contains(token, "Citation")
542 && contains(token, "on page")
543 && contains(token, "undefined")) {
546 } else if (prefixIs(token, "Package")) {
548 retval |= PACKAGE_WARNING;
549 if (contains(token, "natbib Warning:")) {
551 if (contains(token, "Citation")
552 && contains(token, "on page")
553 && contains(token, "undefined")) {
556 } else if (contains(token, "run BibTeX")) {
558 } else if (contains(token, "Rerun LaTeX") ||
559 contains(token, "Rerun to get")) {
560 // at least longtable.sty and bibtopic.sty
563 << "We should rerun." << endl;
566 } else if (prefixIs(token, "(")) {
567 if (contains(token, "Rerun LaTeX") ||
568 contains(token, "Rerun to get")) {
571 << "We should rerun." << endl;
574 } else if (prefixIs(token, "! ")) {
575 // Ok, we have something that looks like a TeX Error
576 // but what do we really have.
578 // Just get the error description:
579 string desc(token, 2);
580 if (contains(token, "LaTeX Error:"))
581 retval |= LATEX_ERROR;
586 if (!getline(ifs, tmp))
590 } while (!prefixIs(tmp, "l."));
591 if (prefixIs(tmp, "l.")) {
592 // we have a latex error
594 if (contains(desc, "Package babel Error: You haven't defined the language"))
595 retval |= ERROR_RERUN;
596 // get the line number:
598 sscanf(tmp.c_str(), "l.%d", &line);
599 // get the rest of the message:
600 string errstr(tmp, tmp.find(' '));
603 while (!contains(errstr, "l.")
605 && !prefixIs(tmp, "! ")
606 && !contains(tmp, "(job aborted")) {
612 << "line: " << line << '\n'
613 << "Desc: " << desc << '\n'
614 << "Text: " << errstr << endl;
615 if (line == last_line)
621 if (line_count <= 5) {
622 terr.insertError(line, desc, errstr);
627 // information messages, TeX warnings and other
628 // warnings we have not caught earlier.
629 if (prefixIs(token, "Overfull ")) {
630 retval |= TEX_WARNING;
631 } else if (prefixIs(token, "Underfull ")) {
632 retval |= TEX_WARNING;
633 } else if (contains(token, "Rerun to get citations")) {
634 // Natbib seems to use this.
636 } else if (contains(token, "No pages of output")) {
637 // A dvi file was not created
639 } else if (contains(token, "That makes 100 errors")) {
640 // More than 100 errors were reprted
641 retval |= TOO_MANY_ERRORS;
645 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
650 void LaTeX::deplog(DepTable & head)
652 // This function reads the LaTeX log file end extracts all the external
653 // files used by the LaTeX run. The files are then entered into the
656 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
658 LRegex reg1("\\)* *\\(([^ )]+).*");
659 LRegex reg2("File: ([^ ]+).*");
660 LRegex reg3("No file ([^ ]+)\\..*");
661 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
662 // If an index should be created, MikTex does not write a line like
663 // \openout# = 'sample,idx'.
664 // but intstead only a line like this into the log:
665 // Writing index file sample.idx
666 LRegex reg5("Writing index file ([^ ]+).*");
667 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
669 ifstream ifs(logfile.c_str());
671 // Ok, the scanning of files here is not sufficient.
672 // Sometimes files are named by "File: xxx" only
673 // So I think we should use some regexps to find files instead.
674 // "(\([^ ]+\)" should match the "(file " variant
675 // "File: \([^ ]+\)" should match the "File: file" variant
679 token = strip(token, '\r');
680 if (token.empty()) continue;
682 if (reg1.exact_match(token)) {
683 LRegex::SubMatches const & sub = reg1.exec(token);
684 foundfile = LSubstring(token, sub[1].first,
686 } else if (reg2.exact_match(token)) {
687 LRegex::SubMatches const & sub = reg2.exec(token);
688 foundfile = LSubstring(token, sub[1].first,
690 } else if (reg3.exact_match(token)) {
691 LRegex::SubMatches const & sub = reg3.exec(token);
692 foundfile = LSubstring(token, sub[1].first,
694 } else if (reg4.exact_match(token)) {
695 LRegex::SubMatches const & sub = reg4.exec(token);
696 foundfile = LSubstring(token, sub[1].first,
698 } else if (reg5.exact_match(token)) {
699 LRegex::SubMatches const & sub = reg5.exec(token);
700 foundfile = LSubstring(token, sub[1].first,
706 // convert from native os path to unix path
707 foundfile = os::internal_path(foundfile);
709 lyxerr[Debug::DEPEND] << "Found file: "
710 << foundfile << endl;
712 // Ok now we found a file.
713 // Now we should make sure that this is a file that we can
714 // access through the normal paths.
715 // We will not try any fancy search methods to
718 // (1) foundfile is an
719 // absolute path and should
721 if (AbsolutePath(foundfile)) {
722 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
723 << foundfile << endl;
724 // On initial insert we want to do the update at once
725 // since this file can not be a file generated by
727 if (FileInfo(foundfile).exist())
728 head.insert(foundfile, true);
731 // (2) foundfile is in the tmpdir
732 // insert it into head
733 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
734 if (unwanted.exact_match(foundfile)) {
735 lyxerr[Debug::DEPEND]
737 << OnlyFilename(foundfile)
738 << " in the dep file"
740 } else if (suffixIs(foundfile, ".tex")) {
741 // This is a tex file generated by LyX
742 // and latex is not likely to change this
744 lyxerr[Debug::DEPEND]
745 << "Tmpdir TeX file: "
746 << OnlyFilename(foundfile)
748 head.insert(foundfile, true);
750 lyxerr[Debug::DEPEND]
752 << OnlyFilename(foundfile)
754 head.insert(OnlyFilename(foundfile));
757 lyxerr[Debug::DEPEND]
758 << "Not a file or we are unable to find it."
762 // Make sure that the main .tex file is in the dependancy file.
763 head.insert(OnlyFilename(file), true);