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 #include "bufferlist.h"
21 #include "funcrequest.h"
22 #include "support/filetools.h"
23 #include "support/FileInfo.h"
24 #include "support/tostr.h"
25 #include "support/lstrings.h"
26 #include "support/lyxlib.h"
27 #include "support/systemcall.h"
28 #include "support/os.h"
29 #include "support/path.h"
31 #include <boost/regex.hpp>
34 #include <cstdio> // sscanf
36 #ifndef CXX_GLOBAL_CSTD
46 using boost::regex_match;
48 #ifndef USE_INCLUDED_STRING
54 // TODO: in no particular order
55 // - get rid of the extern BufferList and the call to
56 // BufferList::updateIncludedTeXfiles, this should either
57 // be done before calling LaTeX::funcs or in a completely
59 // - the bibtex command options should be supported.
60 // - the makeindex style files should be taken care of with
61 // the dependency mechanism.
62 // - makeindex commandline options should be supported
63 // - somewhere support viewing of bibtex and makeindex log files.
64 // - we should perhaps also scan the bibtex log file
65 // - we should perhaps also scan the bibtex log file
67 extern BufferList bufferlist;
71 void showRunMessage(LyXFunc * lf, unsigned int count)
73 string str = bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
74 lf->dispatch(FuncRequest(LFUN_MESSAGE, str));
83 void TeXErrors::insertError(int line, string const & error_desc,
84 string const & error_text)
86 Error newerr(line, error_desc, error_text);
87 errors.push_back(newerr);
91 bool operator==(Aux_Info const & a, Aux_Info const & o)
93 return a.aux_file == o.aux_file &&
94 a.citations == o.citations &&
95 a.databases == o.databases &&
100 bool operator!=(Aux_Info const & a, Aux_Info const & o)
110 LaTeX::LaTeX(string const & latex, LatexRunParams const & rp,
111 string const & f, string const & p)
112 : cmd(latex), file(f), path(p), runparams(rp)
115 depfile = file + ".dep";
116 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
118 output_file = ChangeExtension(file,".pdf");
120 output_file = ChangeExtension(file,".dvi");
125 void LaTeX::deleteFilesOnError() const
127 // currently just a dummy function.
129 // What files do we have to delete?
131 // This will at least make latex do all the runs
132 lyx::unlink(depfile);
134 // but the reason for the error might be in a generated file...
136 string const ofname = OnlyFilename(file);
139 string const bbl = ChangeExtension(ofname, ".bbl");
143 string const ind = ChangeExtension(ofname, ".ind");
146 // Also remove the aux file
147 string const aux = ChangeExtension(ofname, ".aux");
152 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
153 // We know that this function will only be run if the lyx buffer
154 // has been changed. We also know that a newly written .tex file
155 // is always different from the previous one because of the date
156 // in it. However it seems safe to run latex (at least) on time each
157 // time the .tex file changes.
159 int scanres = NO_ERRORS;
160 unsigned int count = 0; // number of times run
161 num_errors = 0; // just to make sure.
162 unsigned int const MAX_RUN = 6;
163 DepTable head; // empty head
164 bool rerun = false; // rerun requested
166 // The class LaTeX does not know the temp path.
167 bufferlist.updateIncludedTeXfiles(lyx::getcwd(), runparams);
169 // Never write the depfile if an error was encountered.
172 // first check if the file dependencies exist:
173 // ->If it does exist
174 // check if any of the files mentioned in it have
175 // changed (done using a checksum).
177 // run latex once and
178 // remake the dependency file
179 // -> if not changed:
180 // just return there is nothing to do for us.
181 // ->if it doesn't exist
183 // run latex once (we need to run latex once anyway) and
184 // remake the dependency file.
187 FileInfo fi(depfile);
188 bool had_depfile = fi.exist();
189 bool run_bibtex = false;
190 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
193 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
194 // Read the dep file:
195 had_depfile = head.read(depfile);
199 // Update the checksums
201 // Can't just check if anything has changed because it might have aborted
202 // on error last time... in which cas we need to re-run latex
203 // and collect the error messages (even if they are the same).
204 if (!FileInfo(output_file).exist()) {
205 lyxerr[Debug::DEPEND]
206 << "re-running LaTeX because output file doesn't exist." << endl;
207 } else if (!head.sumchange()) {
208 lyxerr[Debug::DEPEND] << "return no_change" << endl;
211 lyxerr[Debug::DEPEND]
212 << "Dependency file has changed" << endl;
215 if (head.extchanged(".bib") || head.extchanged(".bst"))
218 lyxerr[Debug::DEPEND]
219 << "Dependency file does not exist, or has wrong format" << endl;
221 /// We scan the aux file even when had_depfile = false,
222 /// because we can run pdflatex on the file after running latex on it,
223 /// in which case we will not need to run bibtex again.
224 vector<Aux_Info> bibtex_info_old;
226 bibtex_info_old = scanAuxFiles(aux_file);
229 lyxerr[Debug::LATEX] << "Run #" << count << endl;
231 showRunMessage(lfun, count);
235 scanres = scanLogFile(terr);
236 if (scanres & ERROR_RERUN) {
237 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
239 scanres = scanLogFile(terr);
242 if (scanres & ERRORS) {
243 deleteFilesOnError();
244 return scanres; // return on error
247 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
248 if (!run_bibtex && bibtex_info_old != bibtex_info)
251 // update the dependencies.
252 deplog(head); // reads the latex log
256 // At this point we must run external programs if needed.
257 // makeindex will be run if a .idx file changed or was generated.
258 // And if there were undefined citations or changes in references
259 // the .aux file is checked for signs of bibtex. Bibtex is then run
263 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
265 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
267 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
270 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
274 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
275 if (scanres & UNDEF_CIT || run_bibtex) {
276 // Here we must scan the .aux file and look for
277 // "\bibdata" and/or "\bibstyle". If one of those
278 // tags is found -> run bibtex and set rerun = true;
280 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
282 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
285 updateBibtexDependencies(head, bibtex_info);
286 rerun |= runBibTeX(bibtex_info);
287 } else if (!had_depfile) {
288 /// If we run pdflatex on the file after running latex on it,
289 /// then we do not need to run bibtex, but we do need to
290 /// insert the .bib and .bst files into the .dep-pdf file.
291 updateBibtexDependencies(head, bibtex_info);
295 // we know on this point that latex has been run once (or we just
296 // returned) and the question now is to decide if we need to run
297 // it any more. This is done by asking if any of the files in the
298 // dependency file has changed. (remember that the checksum for
299 // a given file is reported to have changed if it just was created)
300 // -> if changed or rerun == true:
301 // run latex once more and
302 // update the dependency structure
303 // -> if not changed:
304 // we does nothing at this point
306 if (rerun || head.sumchange()) {
309 lyxerr[Debug::DEPEND]
310 << "Dep. file has changed or rerun requested" << endl;
312 << "Run #" << count << endl;
314 showRunMessage(lfun, count);
318 scanres = scanLogFile(terr);
319 if (scanres & ERRORS) {
320 deleteFilesOnError();
321 return scanres; // return on error
324 // update the depedencies
325 deplog(head); // reads the latex log
328 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
332 // The inclusion of files generated by external programs like
333 // makeindex or bibtex might have done changes to pagenumbereing,
334 // etc. And because of this we must run the external programs
335 // again to make sure everything is redone correctly.
336 // Also there should be no need to run the external programs any
339 // run makeindex if the <file>.idx has changed or was generated.
340 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
342 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
344 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
347 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
351 // we will only run latex more if the log file asks for it.
352 // or if the sumchange() is true.
353 // -> rerun asked for:
355 // remake the dependency file
356 // goto 2 or return if max runs are reached.
357 // -> rerun not asked for:
358 // just return (fall out of bottom of func)
360 while ((head.sumchange() || rerun || (scanres & RERUN))
361 && count < MAX_RUN) {
362 // Yes rerun until message goes away, or until
363 // MAX_RUNS are reached.
366 lyxerr[Debug::LATEX] << "Run #" << count << endl;
368 showRunMessage(lfun, count);
372 scanres = scanLogFile(terr);
373 if (scanres & ERRORS) {
374 deleteFilesOnError();
375 return scanres; // return on error
382 // Write the dependencies to file.
384 lyxerr[Debug::LATEX] << "Done." << endl;
389 int LaTeX::startscript()
392 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
393 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
394 string tmp = cmd + ' ' + file + " > nul";
397 return one.startscript(Systemcall::Wait, tmp);
401 bool LaTeX::runMakeIndex(string const & f)
403 lyxerr[Debug::LATEX] << "idx file has been made,"
404 " running makeindex on file "
407 // It should be possible to set the switches for makeindex
408 // sorting style and such. It would also be very convenient
409 // to be able to make style files from within LyX. This has
410 // to come for a later time.
411 string tmp = "makeindex -c -q ";
414 one.startscript(Systemcall::Wait, tmp);
419 vector<Aux_Info> const
420 LaTeX::scanAuxFiles(string const & file)
422 vector<Aux_Info> result;
424 result.push_back(scanAuxFile(file));
426 for (int i = 1; i < 1000; ++i) {
427 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
432 result.push_back(scanAuxFile(file2));
438 Aux_Info const LaTeX::scanAuxFile(string const & file)
441 result.aux_file = file;
442 scanAuxFile(file, result);
447 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
449 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
451 ifstream ifs(file.c_str());
453 regex reg1("\\\\citation\\{([^}]+)\\}");
454 regex reg2("\\\\bibdata\\{([^}]+)\\}");
455 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
456 regex reg4("\\\\@input\\{([^}]+)\\}");
458 while (getline(ifs, token)) {
459 token = rtrim(token, "\r");
460 #ifndef USE_INCLUDED_STRING
465 if (regex_match(STRCONV(token), sub, reg1)) {
466 string data = STRCONV(sub.str(1));
467 while (!data.empty()) {
469 data = split(data, citation, ',');
470 lyxerr[Debug::LATEX] << "Citation: "
472 aux_info.citations.insert(citation);
474 } else if (regex_match(STRCONV(token), sub, reg2)) {
475 string data = sub.STRCONV(str(1));
476 // data is now all the bib files separated by ','
477 // get them one by one and pass them to the helper
478 while (!data.empty()) {
480 data = split(data, database, ',');
481 database = ChangeExtension(database, "bib");
482 lyxerr[Debug::LATEX] << "BibTeX database: `"
483 << database << '\'' << endl;
484 aux_info.databases.insert(database);
486 } else if (regex_match(STRCONV(token), sub, reg3)) {
487 string style = STRCONV(sub.str(1));
488 // token is now the style file
489 // pass it to the helper
490 style = ChangeExtension(style, "bst");
491 lyxerr[Debug::LATEX] << "BibTeX style: `"
492 << style << '\'' << endl;
493 aux_info.styles.insert(style);
494 } else if (regex_match(STRCONV(token), sub, reg4)) {
495 string const file2 = STRCONV(sub.str(1));
496 scanAuxFile(file2, aux_info);
502 void LaTeX::updateBibtexDependencies(DepTable & dep,
503 vector<Aux_Info> const & bibtex_info)
505 // Since a run of Bibtex mandates more latex runs it is ok to
506 // remove all ".bib" and ".bst" files.
507 dep.remove_files_with_extension(".bib");
508 dep.remove_files_with_extension(".bst");
509 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
511 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
512 it != bibtex_info.end(); ++it) {
513 for (set<string>::const_iterator it2 = it->databases.begin();
514 it2 != it->databases.end(); ++it2) {
515 string file = findtexfile(*it2, "bib");
517 dep.insert(file, true);
520 for (set<string>::const_iterator it2 = it->styles.begin();
521 it2 != it->styles.end(); ++it2) {
522 string file = findtexfile(*it2, "bst");
524 dep.insert(file, true);
530 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
533 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
534 it != bibtex_info.end(); ++it) {
535 if (it->databases.empty())
539 string tmp = "bibtex ";
540 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
542 one.startscript(Systemcall::Wait, tmp);
544 // Return whether bibtex was run
549 int LaTeX::scanLogFile(TeXErrors & terr)
553 int retval = NO_ERRORS;
554 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
555 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
556 ifstream ifs(tmp.c_str());
559 while (getline(ifs, token)) {
560 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
565 if (prefixIs(token, "LaTeX Warning:")) {
566 // Here shall we handle different
568 retval |= LATEX_WARNING;
569 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
570 if (contains(token, "Rerun to get cross-references")) {
573 << "We should rerun." << endl;
574 } else if (contains(token, "Citation")
575 && contains(token, "on page")
576 && contains(token, "undefined")) {
579 } else if (prefixIs(token, "Package")) {
581 retval |= PACKAGE_WARNING;
582 if (contains(token, "natbib Warning:")) {
584 if (contains(token, "Citation")
585 && contains(token, "on page")
586 && contains(token, "undefined")) {
589 } else if (contains(token, "run BibTeX")) {
591 } else if (contains(token, "Rerun LaTeX") ||
592 contains(token, "Rerun to get")) {
593 // at least longtable.sty and bibtopic.sty
596 << "We should rerun." << endl;
599 } else if (token[0] == '(') {
600 if (contains(token, "Rerun LaTeX") ||
601 contains(token, "Rerun to get")) {
604 << "We should rerun." << endl;
607 } else if (prefixIs(token, "! ")) {
608 // Ok, we have something that looks like a TeX Error
609 // but what do we really have.
611 // Just get the error description:
612 string desc(token, 2);
613 if (contains(token, "LaTeX Error:"))
614 retval |= LATEX_ERROR;
619 if (!getline(ifs, tmp))
623 } while (!prefixIs(tmp, "l."));
624 if (prefixIs(tmp, "l.")) {
625 // we have a latex error
627 if (contains(desc, "Package babel Error: You haven't defined the language"))
628 retval |= ERROR_RERUN;
629 // get the line number:
631 sscanf(tmp.c_str(), "l.%d", &line);
632 // get the rest of the message:
633 string errstr(tmp, tmp.find(' '));
636 while (!contains(errstr, "l.")
638 && !prefixIs(tmp, "! ")
639 && !contains(tmp, "(job aborted")) {
645 << "line: " << line << '\n'
646 << "Desc: " << desc << '\n'
647 << "Text: " << errstr << endl;
648 if (line == last_line)
654 if (line_count <= 5) {
655 terr.insertError(line, desc, errstr);
660 // information messages, TeX warnings and other
661 // warnings we have not caught earlier.
662 if (prefixIs(token, "Overfull ")) {
663 retval |= TEX_WARNING;
664 } else if (prefixIs(token, "Underfull ")) {
665 retval |= TEX_WARNING;
666 } else if (contains(token, "Rerun to get citations")) {
667 // Natbib seems to use this.
669 } else if (contains(token, "No pages of output")) {
670 // A dvi file was not created
672 } else if (contains(token, "That makes 100 errors")) {
673 // More than 100 errors were reprted
674 retval |= TOO_MANY_ERRORS;
678 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
683 void LaTeX::deplog(DepTable & head)
685 // This function reads the LaTeX log file end extracts all the external
686 // files used by the LaTeX run. The files are then entered into the
689 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
691 regex reg1("\\)* *\\(([^ )]+).*");
692 regex reg2("File: ([^ ]+).*");
693 regex reg3("No file ([^ ]+)\\..*");
694 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
695 // If an index should be created, MikTex does not write a line like
696 // \openout# = 'sample,idx'.
697 // but intstead only a line like this into the log:
698 // Writing index file sample.idx
699 regex reg5("Writing index file ([^ ]+).*");
700 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
702 ifstream ifs(logfile.c_str());
704 // Ok, the scanning of files here is not sufficient.
705 // Sometimes files are named by "File: xxx" only
706 // So I think we should use some regexps to find files instead.
707 // "(\([^ ]+\)" should match the "(file " variant
708 // "File: \([^ ]+\)" should match the "File: file" variant
712 token = rtrim(token, "\r");
713 if (token.empty()) continue;
715 #ifndef USE_INCLUDED_STRING
720 if (regex_match(STRCONV(token), sub, reg1)) {
721 foundfile = STRCONV(sub.str(1));
722 } else if (regex_match(STRCONV(token), sub, reg2)) {
723 foundfile = STRCONV(sub.str(1));
724 } else if (regex_match(STRCONV(token), sub, reg3)) {
725 foundfile = STRCONV(sub.str(1));
726 } else if (regex_match(STRCONV(token), sub, reg4)) {
727 foundfile = STRCONV(sub.str(1));
728 } else if (regex_match(STRCONV(token), sub, reg5)) {
729 foundfile = STRCONV(sub.str(1));
734 // convert from native os path to unix path
735 foundfile = os::internal_path(foundfile);
737 lyxerr[Debug::DEPEND] << "Found file: "
738 << foundfile << endl;
740 // Ok now we found a file.
741 // Now we should make sure that this is a file that we can
742 // access through the normal paths.
743 // We will not try any fancy search methods to
746 // (1) foundfile is an
747 // absolute path and should
749 if (AbsolutePath(foundfile)) {
750 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
751 << foundfile << endl;
752 // On initial insert we want to do the update at once
753 // since this file can not be a file generated by
755 if (FileInfo(foundfile).exist())
756 head.insert(foundfile, true);
759 // (2) foundfile is in the tmpdir
760 // insert it into head
761 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
762 if (regex_match(STRCONV(foundfile), unwanted)) {
763 lyxerr[Debug::DEPEND]
765 << OnlyFilename(foundfile)
766 << " in the dep file"
768 } else if (suffixIs(foundfile, ".tex")) {
769 // This is a tex file generated by LyX
770 // and latex is not likely to change this
772 lyxerr[Debug::DEPEND]
773 << "Tmpdir TeX file: "
774 << OnlyFilename(foundfile)
776 head.insert(foundfile, true);
778 lyxerr[Debug::DEPEND]
780 << OnlyFilename(foundfile)
782 head.insert(OnlyFilename(foundfile));
785 lyxerr[Debug::DEPEND]
786 << "Not a file or we are unable to find it."
790 // Make sure that the main .tex file is in the dependancy file.
791 head.insert(OnlyFilename(file), true);