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/lstrings.h"
25 #include "support/lyxlib.h"
26 #include "support/systemcall.h"
27 #include "support/os.h"
28 #include "support/path.h"
30 #include <boost/regex.hpp>
31 #include "support/BoostFormat.h"
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)
75 str << boost::format(_("Waiting for LaTeX run number %1$d")) % count;
77 str << _("Waiting for LaTeX run number ") << count;
79 lf->dispatch(FuncRequest(LFUN_MESSAGE, STRCONV(str.str())));
88 void TeXErrors::insertError(int line, string const & error_desc,
89 string const & error_text)
91 Error newerr(line, error_desc, error_text);
92 errors.push_back(newerr);
96 bool operator==(Aux_Info const & a, Aux_Info const & o)
98 return a.aux_file == o.aux_file &&
99 a.citations == o.citations &&
100 a.databases == o.databases &&
101 a.styles == o.styles;
105 bool operator!=(Aux_Info const & a, Aux_Info const & o)
115 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
116 : cmd(latex), file(f), path(p)
119 depfile = file + ".dep";
120 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
122 output_file = ChangeExtension(file,".pdf");
124 output_file = ChangeExtension(file,".dvi");
129 void LaTeX::deleteFilesOnError() const
131 // currently just a dummy function.
133 // What files do we have to delete?
135 // This will at least make latex do all the runs
136 lyx::unlink(depfile);
138 // but the reason for the error might be in a generated file...
140 string const ofname = OnlyFilename(file);
143 string const bbl = ChangeExtension(ofname, ".bbl");
147 string const ind = ChangeExtension(ofname, ".ind");
150 // Also remove the aux file
151 string const aux = ChangeExtension(ofname, ".aux");
156 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
157 // We know that this function will only be run if the lyx buffer
158 // has been changed. We also know that a newly written .tex file
159 // is always different from the previous one because of the date
160 // in it. However it seems safe to run latex (at least) on time each
161 // time the .tex file changes.
163 int scanres = NO_ERRORS;
164 unsigned int count = 0; // number of times run
165 num_errors = 0; // just to make sure.
166 unsigned int const MAX_RUN = 6;
167 DepTable head; // empty head
168 bool rerun = false; // rerun requested
170 // The class LaTeX does not know the temp path.
171 bufferlist.updateIncludedTeXfiles(lyx::getcwd());
173 // Never write the depfile if an error was encountered.
176 // first check if the file dependencies exist:
177 // ->If it does exist
178 // check if any of the files mentioned in it have
179 // changed (done using a checksum).
181 // run latex once and
182 // remake the dependency file
183 // -> if not changed:
184 // just return there is nothing to do for us.
185 // ->if it doesn't exist
187 // run latex once (we need to run latex once anyway) and
188 // remake the dependency file.
191 FileInfo fi(depfile);
192 bool had_depfile = fi.exist();
193 bool run_bibtex = false;
194 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
197 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
198 // Read the dep file:
199 had_depfile = head.read(depfile);
203 // Update the checksums
205 // Can't just check if anything has changed because it might have aborted
206 // on error last time... in which cas we need to re-run latex
207 // and collect the error messages (even if they are the same).
208 if (!FileInfo(output_file).exist()) {
209 lyxerr[Debug::DEPEND]
210 << "re-running LaTeX because output file doesn't exist." << endl;
211 } else if (!head.sumchange()) {
212 lyxerr[Debug::DEPEND] << "return no_change" << endl;
215 lyxerr[Debug::DEPEND]
216 << "Dependency file has changed" << endl;
219 if (head.extchanged(".bib") || head.extchanged(".bst"))
222 lyxerr[Debug::DEPEND]
223 << "Dependency file does not exist, or has wrong format" << endl;
225 /// We scan the aux file even when had_depfile = false,
226 /// because we can run pdflatex on the file after running latex on it,
227 /// in which case we will not need to run bibtex again.
228 vector<Aux_Info> bibtex_info_old;
230 bibtex_info_old = scanAuxFiles(aux_file);
233 lyxerr[Debug::LATEX] << "Run #" << count << endl;
235 showRunMessage(lfun, count);
239 scanres = scanLogFile(terr);
240 if (scanres & ERROR_RERUN) {
241 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
243 scanres = scanLogFile(terr);
246 if (scanres & ERRORS) {
247 deleteFilesOnError();
248 return scanres; // return on error
251 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
252 if (!run_bibtex && bibtex_info_old != bibtex_info)
255 // update the dependencies.
256 deplog(head); // reads the latex log
260 // At this point we must run external programs if needed.
261 // makeindex will be run if a .idx file changed or was generated.
262 // And if there were undefined citations or changes in references
263 // the .aux file is checked for signs of bibtex. Bibtex is then run
267 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
269 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
271 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
274 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
278 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
279 if (scanres & UNDEF_CIT || run_bibtex) {
280 // Here we must scan the .aux file and look for
281 // "\bibdata" and/or "\bibstyle". If one of those
282 // tags is found -> run bibtex and set rerun = true;
284 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
286 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
289 updateBibtexDependencies(head, bibtex_info);
290 rerun |= runBibTeX(bibtex_info);
291 } else if (!had_depfile) {
292 /// If we run pdflatex on the file after running latex on it,
293 /// then we do not need to run bibtex, but we do need to
294 /// insert the .bib and .bst files into the .dep-pdf file.
295 updateBibtexDependencies(head, bibtex_info);
299 // we know on this point that latex has been run once (or we just
300 // returned) and the question now is to decide if we need to run
301 // it any more. This is done by asking if any of the files in the
302 // dependency file has changed. (remember that the checksum for
303 // a given file is reported to have changed if it just was created)
304 // -> if changed or rerun == true:
305 // run latex once more and
306 // update the dependency structure
307 // -> if not changed:
308 // we does nothing at this point
310 if (rerun || head.sumchange()) {
313 lyxerr[Debug::DEPEND]
314 << "Dep. file has changed or rerun requested" << endl;
316 << "Run #" << count << endl;
318 showRunMessage(lfun, count);
322 scanres = scanLogFile(terr);
323 if (scanres & ERRORS) {
324 deleteFilesOnError();
325 return scanres; // return on error
328 // update the depedencies
329 deplog(head); // reads the latex log
332 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
336 // The inclusion of files generated by external programs like
337 // makeindex or bibtex might have done changes to pagenumbereing,
338 // etc. And because of this we must run the external programs
339 // again to make sure everything is redone correctly.
340 // Also there should be no need to run the external programs any
343 // run makeindex if the <file>.idx has changed or was generated.
344 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
346 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
348 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
351 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
355 // we will only run latex more if the log file asks for it.
356 // or if the sumchange() is true.
357 // -> rerun asked for:
359 // remake the dependency file
360 // goto 2 or return if max runs are reached.
361 // -> rerun not asked for:
362 // just return (fall out of bottom of func)
364 while ((head.sumchange() || rerun || (scanres & RERUN))
365 && count < MAX_RUN) {
366 // Yes rerun until message goes away, or until
367 // MAX_RUNS are reached.
370 lyxerr[Debug::LATEX] << "Run #" << count << endl;
372 showRunMessage(lfun, count);
376 scanres = scanLogFile(terr);
377 if (scanres & ERRORS) {
378 deleteFilesOnError();
379 return scanres; // return on error
386 // Write the dependencies to file.
388 lyxerr[Debug::LATEX] << "Done." << endl;
393 int LaTeX::startscript()
396 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
397 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
398 string tmp = cmd + ' ' + file + " > nul";
401 return one.startscript(Systemcall::Wait, tmp);
405 bool LaTeX::runMakeIndex(string const & f)
407 lyxerr[Debug::LATEX] << "idx file has been made,"
408 " running makeindex on file "
411 // It should be possible to set the switches for makeindex
412 // sorting style and such. It would also be very convenient
413 // to be able to make style files from within LyX. This has
414 // to come for a later time.
415 string tmp = "makeindex -c -q ";
418 one.startscript(Systemcall::Wait, tmp);
423 vector<Aux_Info> const
424 LaTeX::scanAuxFiles(string const & file)
426 vector<Aux_Info> result;
428 result.push_back(scanAuxFile(file));
430 for (int i = 1; i < 1000; ++i) {
431 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
436 result.push_back(scanAuxFile(file2));
442 Aux_Info const LaTeX::scanAuxFile(string const & file)
445 result.aux_file = file;
446 scanAuxFile(file, result);
451 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
453 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
455 ifstream ifs(file.c_str());
457 regex reg1("\\\\citation\\{([^}]+)\\}");
458 regex reg2("\\\\bibdata\\{([^}]+)\\}");
459 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
460 regex reg4("\\\\@input\\{([^}]+)\\}");
462 while (getline(ifs, token)) {
463 token = rtrim(token, "\r");
464 #ifndef USE_INCLUDED_STRING
469 if (regex_match(STRCONV(token), sub, reg1)) {
470 string data = STRCONV(sub.str(1));
471 while (!data.empty()) {
473 data = split(data, citation, ',');
474 lyxerr[Debug::LATEX] << "Citation: "
476 aux_info.citations.insert(citation);
478 } else if (regex_match(STRCONV(token), sub, reg2)) {
479 string data = sub.STRCONV(str(1));
480 // data is now all the bib files separated by ','
481 // get them one by one and pass them to the helper
482 while (!data.empty()) {
484 data = split(data, database, ',');
485 database = ChangeExtension(database, "bib");
486 lyxerr[Debug::LATEX] << "BibTeX database: `"
487 << database << '\'' << endl;
488 aux_info.databases.insert(database);
490 } else if (regex_match(STRCONV(token), sub, reg3)) {
491 string style = STRCONV(sub.str(1));
492 // token is now the style file
493 // pass it to the helper
494 style = ChangeExtension(style, "bst");
495 lyxerr[Debug::LATEX] << "BibTeX style: `"
496 << style << '\'' << endl;
497 aux_info.styles.insert(style);
498 } else if (regex_match(STRCONV(token), sub, reg4)) {
499 string const file2 = STRCONV(sub.str(1));
500 scanAuxFile(file2, aux_info);
506 void LaTeX::updateBibtexDependencies(DepTable & dep,
507 vector<Aux_Info> const & bibtex_info)
509 // Since a run of Bibtex mandates more latex runs it is ok to
510 // remove all ".bib" and ".bst" files.
511 dep.remove_files_with_extension(".bib");
512 dep.remove_files_with_extension(".bst");
513 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
515 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
516 it != bibtex_info.end(); ++it) {
517 for (set<string>::const_iterator it2 = it->databases.begin();
518 it2 != it->databases.end(); ++it2) {
519 string file = findtexfile(*it2, "bib");
521 dep.insert(file, true);
524 for (set<string>::const_iterator it2 = it->styles.begin();
525 it2 != it->styles.end(); ++it2) {
526 string file = findtexfile(*it2, "bst");
528 dep.insert(file, true);
534 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
537 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
538 it != bibtex_info.end(); ++it) {
539 if (it->databases.empty())
543 string tmp = "bibtex ";
544 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
546 one.startscript(Systemcall::Wait, tmp);
548 // Return whether bibtex was run
553 int LaTeX::scanLogFile(TeXErrors & terr)
557 int retval = NO_ERRORS;
558 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
559 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
560 ifstream ifs(tmp.c_str());
563 while (getline(ifs, token)) {
564 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
569 if (prefixIs(token, "LaTeX Warning:")) {
570 // Here shall we handle different
572 retval |= LATEX_WARNING;
573 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
574 if (contains(token, "Rerun to get cross-references")) {
577 << "We should rerun." << endl;
578 } else if (contains(token, "Citation")
579 && contains(token, "on page")
580 && contains(token, "undefined")) {
583 } else if (prefixIs(token, "Package")) {
585 retval |= PACKAGE_WARNING;
586 if (contains(token, "natbib Warning:")) {
588 if (contains(token, "Citation")
589 && contains(token, "on page")
590 && contains(token, "undefined")) {
593 } else if (contains(token, "run BibTeX")) {
595 } else if (contains(token, "Rerun LaTeX") ||
596 contains(token, "Rerun to get")) {
597 // at least longtable.sty and bibtopic.sty
600 << "We should rerun." << endl;
603 } else if (token[0] == '(') {
604 if (contains(token, "Rerun LaTeX") ||
605 contains(token, "Rerun to get")) {
608 << "We should rerun." << endl;
611 } else if (prefixIs(token, "! ")) {
612 // Ok, we have something that looks like a TeX Error
613 // but what do we really have.
615 // Just get the error description:
616 string desc(token, 2);
617 if (contains(token, "LaTeX Error:"))
618 retval |= LATEX_ERROR;
623 if (!getline(ifs, tmp))
627 } while (!prefixIs(tmp, "l."));
628 if (prefixIs(tmp, "l.")) {
629 // we have a latex error
631 if (contains(desc, "Package babel Error: You haven't defined the language"))
632 retval |= ERROR_RERUN;
633 // get the line number:
635 sscanf(tmp.c_str(), "l.%d", &line);
636 // get the rest of the message:
637 string errstr(tmp, tmp.find(' '));
640 while (!contains(errstr, "l.")
642 && !prefixIs(tmp, "! ")
643 && !contains(tmp, "(job aborted")) {
649 << "line: " << line << '\n'
650 << "Desc: " << desc << '\n'
651 << "Text: " << errstr << endl;
652 if (line == last_line)
658 if (line_count <= 5) {
659 terr.insertError(line, desc, errstr);
664 // information messages, TeX warnings and other
665 // warnings we have not caught earlier.
666 if (prefixIs(token, "Overfull ")) {
667 retval |= TEX_WARNING;
668 } else if (prefixIs(token, "Underfull ")) {
669 retval |= TEX_WARNING;
670 } else if (contains(token, "Rerun to get citations")) {
671 // Natbib seems to use this.
673 } else if (contains(token, "No pages of output")) {
674 // A dvi file was not created
676 } else if (contains(token, "That makes 100 errors")) {
677 // More than 100 errors were reprted
678 retval |= TOO_MANY_ERRORS;
682 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
687 void LaTeX::deplog(DepTable & head)
689 // This function reads the LaTeX log file end extracts all the external
690 // files used by the LaTeX run. The files are then entered into the
693 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
695 regex reg1("\\)* *\\(([^ )]+).*");
696 regex reg2("File: ([^ ]+).*");
697 regex reg3("No file ([^ ]+)\\..*");
698 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
699 // If an index should be created, MikTex does not write a line like
700 // \openout# = 'sample,idx'.
701 // but intstead only a line like this into the log:
702 // Writing index file sample.idx
703 regex reg5("Writing index file ([^ ]+).*");
704 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
706 ifstream ifs(logfile.c_str());
708 // Ok, the scanning of files here is not sufficient.
709 // Sometimes files are named by "File: xxx" only
710 // So I think we should use some regexps to find files instead.
711 // "(\([^ ]+\)" should match the "(file " variant
712 // "File: \([^ ]+\)" should match the "File: file" variant
716 token = rtrim(token, "\r");
717 if (token.empty()) continue;
719 #ifndef USE_INCLUDED_STRING
724 if (regex_match(STRCONV(token), sub, reg1)) {
725 foundfile = STRCONV(sub.str(1));
726 } else if (regex_match(STRCONV(token), sub, reg2)) {
727 foundfile = STRCONV(sub.str(1));
728 } else if (regex_match(STRCONV(token), sub, reg3)) {
729 foundfile = STRCONV(sub.str(1));
730 } else if (regex_match(STRCONV(token), sub, reg4)) {
731 foundfile = STRCONV(sub.str(1));
732 } else if (regex_match(STRCONV(token), sub, reg5)) {
733 foundfile = STRCONV(sub.str(1));
738 // convert from native os path to unix path
739 foundfile = os::internal_path(foundfile);
741 lyxerr[Debug::DEPEND] << "Found file: "
742 << foundfile << endl;
744 // Ok now we found a file.
745 // Now we should make sure that this is a file that we can
746 // access through the normal paths.
747 // We will not try any fancy search methods to
750 // (1) foundfile is an
751 // absolute path and should
753 if (AbsolutePath(foundfile)) {
754 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
755 << foundfile << endl;
756 // On initial insert we want to do the update at once
757 // since this file can not be a file generated by
759 if (FileInfo(foundfile).exist())
760 head.insert(foundfile, true);
763 // (2) foundfile is in the tmpdir
764 // insert it into head
765 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
766 if (regex_match(STRCONV(foundfile), unwanted)) {
767 lyxerr[Debug::DEPEND]
769 << OnlyFilename(foundfile)
770 << " in the dep file"
772 } else if (suffixIs(foundfile, ".tex")) {
773 // This is a tex file generated by LyX
774 // and latex is not likely to change this
776 lyxerr[Debug::DEPEND]
777 << "Tmpdir TeX file: "
778 << OnlyFilename(foundfile)
780 head.insert(foundfile, true);
782 lyxerr[Debug::DEPEND]
784 << OnlyFilename(foundfile)
786 head.insert(OnlyFilename(foundfile));
789 lyxerr[Debug::DEPEND]
790 << "Not a file or we are unable to find it."
794 // Make sure that the main .tex file is in the dependancy file.
795 head.insert(OnlyFilename(file), true);