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 "funcrequest.h"
26 #include "support/filetools.h"
27 #include "support/FileInfo.h"
28 #include "support/lstrings.h"
29 #include "support/lyxlib.h"
30 #include "support/systemcall.h"
31 #include "support/os.h"
32 #include "support/path.h"
34 #include <boost/regex.hpp>
35 #include "BoostFormat.h"
38 #include <cstdio> // sscanf
40 #ifndef CXX_GLOBAL_CSTD
50 using boost::regex_match;
52 #ifndef USE_INCLUDED_STRING
58 // TODO: in no particular order
59 // - get rid of the extern BufferList and the call to
60 // BufferList::updateIncludedTeXfiles, this should either
61 // be done before calling LaTeX::funcs or in a completely
63 // - the bibtex command options should be supported.
64 // - the makeindex style files should be taken care of with
65 // the dependency mechanism.
66 // - makeindex commandline options should be supported
67 // - somewhere support viewing of bibtex and makeindex log files.
68 // - we should perhaps also scan the bibtex log file
69 // - we should perhaps also scan the bibtex log file
71 extern BufferList bufferlist;
77 void TeXErrors::insertError(int line, string const & error_desc,
78 string const & error_text)
80 Error newerr(line, error_desc, error_text);
81 errors.push_back(newerr);
88 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
89 : cmd(latex), file(f), path(p)
92 depfile = file + ".dep";
93 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
95 output_file = ChangeExtension(file,".pdf");
97 output_file = ChangeExtension(file,".dvi");
102 void LaTeX::deleteFilesOnError() const
104 // currently just a dummy function.
106 // What files do we have to delete?
108 // This will at least make latex do all the runs
109 lyx::unlink(depfile);
111 // but the reason for the error might be in a generated file...
113 string const ofname = OnlyFilename(file);
116 string const bbl = ChangeExtension(ofname, ".bbl");
120 string const ind = ChangeExtension(ofname, ".ind");
123 // Also remove the aux file
124 string const aux = ChangeExtension(ofname, ".aux");
129 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
130 // We know that this function will only be run if the lyx buffer
131 // has been changed. We also know that a newly written .tex file
132 // is always different from the previous one because of the date
133 // in it. However it seems safe to run latex (at least) on time each
134 // time the .tex file changes.
136 int scanres = NO_ERRORS;
137 unsigned int count = 0; // number of times run
138 num_errors = 0; // just to make sure.
139 unsigned int const MAX_RUN = 6;
140 DepTable head; // empty head
141 bool rerun = false; // rerun requested
143 // The class LaTeX does not know the temp path.
144 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
146 // Never write the depfile if an error was encountered.
149 // first check if the file dependencies exist:
150 // ->If it does exist
151 // check if any of the files mentioned in it have
152 // changed (done using a checksum).
154 // run latex once and
155 // remake the dependency file
156 // -> if not changed:
157 // just return there is nothing to do for us.
158 // ->if it doesn't exist
160 // run latex once (we need to run latex once anyway) and
161 // remake the dependency file.
164 FileInfo fi(depfile);
165 bool had_depfile = fi.exist();
166 bool run_bibtex = false;
167 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
170 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
171 // Read the dep file:
173 // Update the checksums
175 // Can't just check if anything has changed because it might have aborted
176 // on error last time... in which cas we need to re-run latex
177 // and collect the error messages (even if they are the same).
178 if (!FileInfo(output_file).exist()) {
179 lyxerr[Debug::DEPEND]
180 << "re-running LaTeX because output file doesn't exist." << endl;
181 } else if (!head.sumchange()) {
182 lyxerr[Debug::DEPEND] << "return no_change" << endl;
185 lyxerr[Debug::DEPEND]
186 << "Dependency file has changed" << endl;
189 if (head.extchanged(".bib") || head.extchanged(".bst"))
192 lyxerr[Debug::DEPEND]
193 << "Dependency file does not exist" << endl;
195 /// We scan the aux file even when had_depfile = false,
196 /// because we can run pdflatex on the file after running latex on it,
197 /// in which case we will not need to run bibtex again.
198 vector<Aux_Info> bibtex_info_old;
200 bibtex_info_old = scanAuxFiles(aux_file);
203 lyxerr[Debug::LATEX] << "Run #" << count << endl;
207 str << boost::format(_("LaTeX run number %1$d")) % count;
209 str << _("LaTeX run number ") << count;
211 lfun->dispatch(FuncRequest(LFUN_MESSAGE, STRCONV(str.str())));
215 scanres = scanLogFile(terr);
216 if (scanres & ERROR_RERUN) {
217 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
219 scanres = scanLogFile(terr);
222 if (scanres & ERRORS) {
223 deleteFilesOnError();
224 return scanres; // return on error
227 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
228 if (!run_bibtex && bibtex_info_old != bibtex_info)
231 // update the dependencies.
232 deplog(head); // reads the latex log
236 // At this point we must run external programs if needed.
237 // makeindex will be run if a .idx file changed or was generated.
238 // And if there were undefined citations or changes in references
239 // the .aux file is checked for signs of bibtex. Bibtex is then run
243 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
245 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
247 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
250 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
254 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
255 if (scanres & UNDEF_CIT || run_bibtex) {
256 // Here we must scan the .aux file and look for
257 // "\bibdata" and/or "\bibstyle". If one of those
258 // tags is found -> run bibtex and set rerun = true;
260 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
262 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
265 updateBibtexDependencies(head, bibtex_info);
266 rerun |= runBibTeX(bibtex_info);
267 } else if (!had_depfile) {
268 /// If we run pdflatex on the file after running latex on it,
269 /// then we do not need to run bibtex, but we do need to
270 /// insert the .bib and .bst files into the .dep-pdf file.
271 updateBibtexDependencies(head, bibtex_info);
275 // we know on this point that latex has been run once (or we just
276 // returned) and the question now is to decide if we need to run
277 // it any more. This is done by asking if any of the files in the
278 // dependency file has changed. (remember that the checksum for
279 // a given file is reported to have changed if it just was created)
280 // -> if changed or rerun == true:
281 // run latex once more and
282 // update the dependency structure
283 // -> if not changed:
284 // we does nothing at this point
286 if (rerun || head.sumchange()) {
289 lyxerr[Debug::DEPEND]
290 << "Dep. file has changed or rerun requested" << endl;
292 << "Run #" << count << endl;
296 str << boost::format(_("LaTeX run number %1$d")) % count;
298 str << _("LaTeX run number ") << count;
300 // check lyxstring string stream and gcc 3.1 before fixing
301 lfun->dispatch(FuncRequest(LFUN_MESSAGE, STRCONV(str.str())));
305 scanres = scanLogFile(terr);
306 if (scanres & ERRORS) {
307 deleteFilesOnError();
308 return scanres; // return on error
311 // update the depedencies
312 deplog(head); // reads the latex log
315 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
319 // The inclusion of files generated by external programs like
320 // makeindex or bibtex might have done changes to pagenumbereing,
321 // etc. And because of this we must run the external programs
322 // again to make sure everything is redone correctly.
323 // Also there should be no need to run the external programs any
326 // run makeindex if the <file>.idx has changed or was generated.
327 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
329 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
331 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
334 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
338 // we will only run latex more if the log file asks for it.
339 // or if the sumchange() is true.
340 // -> rerun asked for:
342 // remake the dependency file
343 // goto 2 or return if max runs are reached.
344 // -> rerun not asked for:
345 // just return (fall out of bottom of func)
347 while ((head.sumchange() || rerun || (scanres & RERUN))
348 && count < MAX_RUN) {
349 // Yes rerun until message goes away, or until
350 // MAX_RUNS are reached.
353 lyxerr[Debug::LATEX] << "Run #" << count << endl;
357 str << boost::format(_("LaTeX run number %1$d")) % count;
359 str << _("LaTeX run number ") << count;
361 lfun->dispatch(FuncRequest(LFUN_MESSAGE, STRCONV(str.str())));
365 scanres = scanLogFile(terr);
366 if (scanres & ERRORS) {
367 deleteFilesOnError();
368 return scanres; // return on error
375 // Write the dependencies to file.
377 lyxerr[Debug::LATEX] << "Done." << endl;
382 int LaTeX::operator()()
385 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
386 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
387 string tmp = cmd + ' ' + file + " > nul";
390 return one.startscript(Systemcall::Wait, tmp);
394 bool LaTeX::runMakeIndex(string const & f)
396 lyxerr[Debug::LATEX] << "idx file has been made,"
397 " running makeindex on file "
400 // It should be possible to set the switches for makeindex
401 // sorting style and such. It would also be very convenient
402 // to be able to make style files from within LyX. This has
403 // to come for a later time.
404 string tmp = "makeindex -c -q ";
407 one.startscript(Systemcall::Wait, tmp);
412 vector<Aux_Info> const
413 LaTeX::scanAuxFiles(string const & file)
415 vector<Aux_Info> result;
417 result.push_back(scanAuxFile(file));
419 for (int i = 1; i < 1000; ++i) {
420 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
425 result.push_back(scanAuxFile(file2));
431 Aux_Info const LaTeX::scanAuxFile(string const & file)
434 result.aux_file = file;
435 scanAuxFile(file, result);
440 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
442 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
444 ifstream ifs(file.c_str());
446 regex reg1("\\\\citation\\{([^}]+)\\}");
447 regex reg2("\\\\bibdata\\{([^}]+)\\}");
448 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
449 regex reg4("\\\\@input\\{([^}]+)\\}");
451 while (getline(ifs, token)) {
452 token = rtrim(token, "\r");
453 #ifndef USE_INCLUDED_STRING
458 if (regex_match(STRCONV(token), sub, reg1)) {
459 string data = STRCONV(sub.str(1));
460 while (!data.empty()) {
462 data = split(data, citation, ',');
463 lyxerr[Debug::LATEX] << "Citation: "
465 aux_info.citations.insert(citation);
467 } else if (regex_match(STRCONV(token), sub, reg2)) {
468 string data = sub.STRCONV(str(1));
469 // data is now all the bib files separated by ','
470 // get them one by one and pass them to the helper
471 while (!data.empty()) {
473 data = split(data, database, ',');
474 database = ChangeExtension(database, "bib");
475 lyxerr[Debug::LATEX] << "BibTeX database: `"
476 << database << '\'' << endl;
477 aux_info.databases.insert(database);
479 } else if (regex_match(STRCONV(token), sub, reg3)) {
480 string style = STRCONV(sub.str(1));
481 // token is now the style file
482 // pass it to the helper
483 style = ChangeExtension(style, "bst");
484 lyxerr[Debug::LATEX] << "BibTeX style: `"
485 << style << '\'' << endl;
486 aux_info.styles.insert(style);
487 } else if (regex_match(STRCONV(token), sub, reg4)) {
488 string const file2 = STRCONV(sub.str(1));
489 scanAuxFile(file2, aux_info);
495 void LaTeX::updateBibtexDependencies(DepTable & dep,
496 vector<Aux_Info> const & bibtex_info)
498 // Since a run of Bibtex mandates more latex runs it is ok to
499 // remove all ".bib" and ".bst" files.
500 dep.remove_files_with_extension(".bib");
501 dep.remove_files_with_extension(".bst");
502 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
504 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
505 it != bibtex_info.end(); ++it) {
506 for (set<string>::const_iterator it2 = it->databases.begin();
507 it2 != it->databases.end(); ++it2) {
508 string file = findtexfile(*it2, "bib");
510 dep.insert(file, true);
513 for (set<string>::const_iterator it2 = it->styles.begin();
514 it2 != it->styles.end(); ++it2) {
515 string file = findtexfile(*it2, "bst");
517 dep.insert(file, true);
523 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
526 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
527 it != bibtex_info.end(); ++it) {
528 if (it->databases.empty())
532 string tmp = "bibtex ";
533 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
535 one.startscript(Systemcall::Wait, tmp);
537 // Return whether bibtex was run
542 int LaTeX::scanLogFile(TeXErrors & terr)
546 int retval = NO_ERRORS;
547 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
548 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
549 ifstream ifs(tmp.c_str());
552 while (getline(ifs, token)) {
553 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
558 if (prefixIs(token, "LaTeX Warning:")) {
559 // Here shall we handle different
561 retval |= LATEX_WARNING;
562 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
563 if (contains(token, "Rerun to get cross-references")) {
566 << "We should rerun." << endl;
567 } else if (contains(token, "Citation")
568 && contains(token, "on page")
569 && contains(token, "undefined")) {
572 } else if (prefixIs(token, "Package")) {
574 retval |= PACKAGE_WARNING;
575 if (contains(token, "natbib Warning:")) {
577 if (contains(token, "Citation")
578 && contains(token, "on page")
579 && contains(token, "undefined")) {
582 } else if (contains(token, "run BibTeX")) {
584 } else if (contains(token, "Rerun LaTeX") ||
585 contains(token, "Rerun to get")) {
586 // at least longtable.sty and bibtopic.sty
589 << "We should rerun." << endl;
592 } else if (token[0] == '(') {
593 if (contains(token, "Rerun LaTeX") ||
594 contains(token, "Rerun to get")) {
597 << "We should rerun." << endl;
600 } else if (prefixIs(token, "! ")) {
601 // Ok, we have something that looks like a TeX Error
602 // but what do we really have.
604 // Just get the error description:
605 string desc(token, 2);
606 if (contains(token, "LaTeX Error:"))
607 retval |= LATEX_ERROR;
612 if (!getline(ifs, tmp))
616 } while (!prefixIs(tmp, "l."));
617 if (prefixIs(tmp, "l.")) {
618 // we have a latex error
620 if (contains(desc, "Package babel Error: You haven't defined the language"))
621 retval |= ERROR_RERUN;
622 // get the line number:
624 sscanf(tmp.c_str(), "l.%d", &line);
625 // get the rest of the message:
626 string errstr(tmp, tmp.find(' '));
629 while (!contains(errstr, "l.")
631 && !prefixIs(tmp, "! ")
632 && !contains(tmp, "(job aborted")) {
638 << "line: " << line << '\n'
639 << "Desc: " << desc << '\n'
640 << "Text: " << errstr << endl;
641 if (line == last_line)
647 if (line_count <= 5) {
648 terr.insertError(line, desc, errstr);
653 // information messages, TeX warnings and other
654 // warnings we have not caught earlier.
655 if (prefixIs(token, "Overfull ")) {
656 retval |= TEX_WARNING;
657 } else if (prefixIs(token, "Underfull ")) {
658 retval |= TEX_WARNING;
659 } else if (contains(token, "Rerun to get citations")) {
660 // Natbib seems to use this.
662 } else if (contains(token, "No pages of output")) {
663 // A dvi file was not created
665 } else if (contains(token, "That makes 100 errors")) {
666 // More than 100 errors were reprted
667 retval |= TOO_MANY_ERRORS;
671 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
676 void LaTeX::deplog(DepTable & head)
678 // This function reads the LaTeX log file end extracts all the external
679 // files used by the LaTeX run. The files are then entered into the
682 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
684 regex reg1("\\)* *\\(([^ )]+).*");
685 regex reg2("File: ([^ ]+).*");
686 regex reg3("No file ([^ ]+)\\..*");
687 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
688 // If an index should be created, MikTex does not write a line like
689 // \openout# = 'sample,idx'.
690 // but intstead only a line like this into the log:
691 // Writing index file sample.idx
692 regex reg5("Writing index file ([^ ]+).*");
693 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
695 ifstream ifs(logfile.c_str());
697 // Ok, the scanning of files here is not sufficient.
698 // Sometimes files are named by "File: xxx" only
699 // So I think we should use some regexps to find files instead.
700 // "(\([^ ]+\)" should match the "(file " variant
701 // "File: \([^ ]+\)" should match the "File: file" variant
705 token = rtrim(token, "\r");
706 if (token.empty()) continue;
708 #ifndef USE_INCLUDED_STRING
713 if (regex_match(STRCONV(token), sub, reg1)) {
714 foundfile = STRCONV(sub.str(1));
715 } else if (regex_match(STRCONV(token), sub, reg2)) {
716 foundfile = STRCONV(sub.str(1));
717 } else if (regex_match(STRCONV(token), sub, reg3)) {
718 foundfile = STRCONV(sub.str(1));
719 } else if (regex_match(STRCONV(token), sub, reg4)) {
720 foundfile = STRCONV(sub.str(1));
721 } else if (regex_match(STRCONV(token), sub, reg5)) {
722 foundfile = STRCONV(sub.str(1));
727 // convert from native os path to unix path
728 foundfile = os::internal_path(foundfile);
730 lyxerr[Debug::DEPEND] << "Found file: "
731 << foundfile << endl;
733 // Ok now we found a file.
734 // Now we should make sure that this is a file that we can
735 // access through the normal paths.
736 // We will not try any fancy search methods to
739 // (1) foundfile is an
740 // absolute path and should
742 if (AbsolutePath(foundfile)) {
743 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
744 << foundfile << endl;
745 // On initial insert we want to do the update at once
746 // since this file can not be a file generated by
748 if (FileInfo(foundfile).exist())
749 head.insert(foundfile, true);
752 // (2) foundfile is in the tmpdir
753 // insert it into head
754 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
755 if (regex_match(STRCONV(foundfile), unwanted)) {
756 lyxerr[Debug::DEPEND]
758 << OnlyFilename(foundfile)
759 << " in the dep file"
761 } else if (suffixIs(foundfile, ".tex")) {
762 // This is a tex file generated by LyX
763 // and latex is not likely to change this
765 lyxerr[Debug::DEPEND]
766 << "Tmpdir TeX file: "
767 << OnlyFilename(foundfile)
769 head.insert(foundfile, true);
771 lyxerr[Debug::DEPEND]
773 << OnlyFilename(foundfile)
775 head.insert(OnlyFilename(foundfile));
778 lyxerr[Debug::DEPEND]
779 << "Not a file or we are unable to find it."
783 // Make sure that the main .tex file is in the dependancy file.
784 head.insert(OnlyFilename(file), true);