3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
12 * Full author contact details are available in file CREDITS.
18 #include "bufferlist.h"
23 #include "support/filetools.h"
24 #include "support/FileInfo.h"
25 #include "support/tostr.h"
26 #include "support/lstrings.h"
27 #include "support/lyxlib.h"
28 #include "support/systemcall.h"
29 #include "support/os.h"
31 #include <boost/regex.hpp>
35 using lyx::support::AbsolutePath;
36 using lyx::support::bformat;
37 using lyx::support::ChangeExtension;
38 using lyx::support::contains;
39 using lyx::support::FileInfo;
40 using lyx::support::findtexfile;
41 using lyx::support::getcwd;
42 using lyx::support::OnlyFilename;
43 using lyx::support::prefixIs;
44 using lyx::support::QuoteName;
45 using lyx::support::rtrim;
46 using lyx::support::split;
47 using lyx::support::subst;
48 using lyx::support::suffixIs;
49 using lyx::support::Systemcall;
50 using lyx::support::unlink;
51 using lyx::support::trim;
53 namespace os = lyx::support::os;
59 #ifndef CXX_GLOBAL_CSTD
70 // TODO: in no particular order
71 // - get rid of the extern BufferList and the call to
72 // BufferList::updateIncludedTeXfiles, this should either
73 // be done before calling LaTeX::funcs or in a completely
75 // - the makeindex style files should be taken care of with
76 // the dependency mechanism.
77 // - makeindex commandline options should be supported
78 // - somewhere support viewing of bibtex and makeindex log files.
79 // - we should perhaps also scan the bibtex log file
81 extern BufferList bufferlist;
85 string runMessage(unsigned int count)
87 return bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
96 void TeXErrors::insertError(int line, string const & error_desc,
97 string const & error_text)
99 Error newerr(line, error_desc, error_text);
100 errors.push_back(newerr);
104 bool operator==(Aux_Info const & a, Aux_Info const & o)
106 return a.aux_file == o.aux_file &&
107 a.citations == o.citations &&
108 a.databases == o.databases &&
109 a.styles == o.styles;
113 bool operator!=(Aux_Info const & a, Aux_Info const & o)
123 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
124 string const & f, string const & p)
125 : cmd(latex), file(f), path(p), runparams(rp)
128 depfile = file + ".dep";
129 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
131 output_file = ChangeExtension(file,".pdf");
133 output_file = ChangeExtension(file,".dvi");
138 void LaTeX::deleteFilesOnError() const
140 // currently just a dummy function.
142 // What files do we have to delete?
144 // This will at least make latex do all the runs
147 // but the reason for the error might be in a generated file...
149 string const ofname = OnlyFilename(file);
152 string const bbl = ChangeExtension(ofname, ".bbl");
156 string const ind = ChangeExtension(ofname, ".ind");
159 // Also remove the aux file
160 string const aux = ChangeExtension(ofname, ".aux");
165 int LaTeX::run(TeXErrors & terr)
166 // We know that this function will only be run if the lyx buffer
167 // has been changed. We also know that a newly written .tex file
168 // is always different from the previous one because of the date
169 // in it. However it seems safe to run latex (at least) on time each
170 // time the .tex file changes.
172 int scanres = NO_ERRORS;
173 unsigned int count = 0; // number of times run
174 num_errors = 0; // just to make sure.
175 unsigned int const MAX_RUN = 6;
176 DepTable head; // empty head
177 bool rerun = false; // rerun requested
179 // The class LaTeX does not know the temp path.
180 bufferlist.updateIncludedTeXfiles(getcwd(), runparams);
182 // Never write the depfile if an error was encountered.
185 // first check if the file dependencies exist:
186 // ->If it does exist
187 // check if any of the files mentioned in it have
188 // changed (done using a checksum).
190 // run latex once and
191 // remake the dependency file
192 // -> if not changed:
193 // just return there is nothing to do for us.
194 // ->if it doesn't exist
196 // run latex once (we need to run latex once anyway) and
197 // remake the dependency file.
200 FileInfo fi(depfile);
201 bool had_depfile = fi.exist();
202 bool run_bibtex = false;
203 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
206 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
207 // Read the dep file:
208 had_depfile = head.read(depfile);
212 // Update the checksums
214 // Can't just check if anything has changed because it might have aborted
215 // on error last time... in which cas we need to re-run latex
216 // and collect the error messages (even if they are the same).
217 if (!FileInfo(output_file).exist()) {
218 lyxerr[Debug::DEPEND]
219 << "re-running LaTeX because output file doesn't exist." << endl;
220 } else if (!head.sumchange()) {
221 lyxerr[Debug::DEPEND] << "return no_change" << endl;
224 lyxerr[Debug::DEPEND]
225 << "Dependency file has changed" << endl;
228 if (head.extchanged(".bib") || head.extchanged(".bst"))
231 lyxerr[Debug::DEPEND]
232 << "Dependency file does not exist, or has wrong format" << endl;
234 /// We scan the aux file even when had_depfile = false,
235 /// because we can run pdflatex on the file after running latex on it,
236 /// in which case we will not need to run bibtex again.
237 vector<Aux_Info> bibtex_info_old;
239 bibtex_info_old = scanAuxFiles(aux_file);
242 lyxerr[Debug::LATEX] << "Run #" << count << endl;
243 message(runMessage(count));
246 scanres = scanLogFile(terr);
247 if (scanres & ERROR_RERUN) {
248 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
250 scanres = scanLogFile(terr);
253 if (scanres & ERRORS) {
254 deleteFilesOnError();
255 return scanres; // return on error
258 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
259 if (!run_bibtex && bibtex_info_old != bibtex_info)
262 // update the dependencies.
263 deplog(head); // reads the latex log
267 // At this point we must run external programs if needed.
268 // makeindex will be run if a .idx file changed or was generated.
269 // And if there were undefined citations or changes in references
270 // the .aux file is checked for signs of bibtex. Bibtex is then run
274 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
276 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
277 message(_("Running MakeIndex."));
278 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")), runparams);
282 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
283 if (scanres & UNDEF_CIT || run_bibtex) {
284 // Here we must scan the .aux file and look for
285 // "\bibdata" and/or "\bibstyle". If one of those
286 // tags is found -> run bibtex and set rerun = true;
288 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
289 message(_("Running BibTeX."));
290 updateBibtexDependencies(head, bibtex_info);
291 rerun |= runBibTeX(bibtex_info);
292 } else if (!had_depfile) {
293 /// If we run pdflatex on the file after running latex on it,
294 /// then we do not need to run bibtex, but we do need to
295 /// insert the .bib and .bst files into the .dep-pdf file.
296 updateBibtexDependencies(head, bibtex_info);
300 // we know on this point that latex has been run once (or we just
301 // returned) and the question now is to decide if we need to run
302 // it any more. This is done by asking if any of the files in the
303 // dependency file has changed. (remember that the checksum for
304 // a given file is reported to have changed if it just was created)
305 // -> if changed or rerun == true:
306 // run latex once more and
307 // update the dependency structure
308 // -> if not changed:
309 // we does nothing at this point
311 if (rerun || head.sumchange()) {
314 lyxerr[Debug::DEPEND]
315 << "Dep. file has changed or rerun requested" << endl;
317 << "Run #" << count << endl;
318 message(runMessage(count));
320 scanres = scanLogFile(terr);
321 if (scanres & ERRORS) {
322 deleteFilesOnError();
323 return scanres; // return on error
326 // update the depedencies
327 deplog(head); // reads the latex log
330 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
334 // The inclusion of files generated by external programs like
335 // makeindex or bibtex might have done changes to pagenumbereing,
336 // etc. And because of this we must run the external programs
337 // again to make sure everything is redone correctly.
338 // Also there should be no need to run the external programs any
341 // run makeindex if the <file>.idx has changed or was generated.
342 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
344 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
345 message(_("Running MakeIndex."));
346 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")), runparams);
350 // we will only run latex more if the log file asks for it.
351 // or if the sumchange() is true.
352 // -> rerun asked for:
354 // remake the dependency file
355 // goto 2 or return if max runs are reached.
356 // -> rerun not asked for:
357 // just return (fall out of bottom of func)
359 while ((head.sumchange() || rerun || (scanres & RERUN))
360 && count < MAX_RUN) {
361 // Yes rerun until message goes away, or until
362 // MAX_RUNS are reached.
365 lyxerr[Debug::LATEX] << "Run #" << count << endl;
366 message(runMessage(count));
368 scanres = scanLogFile(terr);
369 if (scanres & ERRORS) {
370 deleteFilesOnError();
371 return scanres; // return on error
378 // Write the dependencies to file.
380 lyxerr[Debug::LATEX] << "Done." << endl;
385 int LaTeX::startscript()
388 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
389 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
390 string tmp = cmd + ' ' + file + " > nul";
393 return one.startscript(Systemcall::Wait, tmp);
397 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams)
399 lyxerr[Debug::LATEX] << "idx file has been made,"
400 " running makeindex on file "
402 string tmp = lyxrc.index_command + " ";
403 tmp = subst(tmp, "$$lang", runparams.document_language);
406 one.startscript(Systemcall::Wait, tmp);
411 vector<Aux_Info> const
412 LaTeX::scanAuxFiles(string const & file)
414 vector<Aux_Info> result;
416 result.push_back(scanAuxFile(file));
418 for (int i = 1; i < 1000; ++i) {
419 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
424 result.push_back(scanAuxFile(file2));
430 Aux_Info const LaTeX::scanAuxFile(string const & file)
433 result.aux_file = file;
434 scanAuxFile(file, result);
439 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
441 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
443 ifstream ifs(file.c_str());
445 static regex const reg1("\\\\citation\\{([^}]+)\\}");
446 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
447 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
448 static regex const reg4("\\\\@input\\{([^}]+)\\}");
450 while (getline(ifs, token)) {
451 token = rtrim(token, "\r");
453 if (regex_match(token, sub, reg1)) {
454 string data = sub.str(1);
455 while (!data.empty()) {
457 data = split(data, citation, ',');
458 lyxerr[Debug::LATEX] << "Citation: "
460 aux_info.citations.insert(citation);
462 } else if (regex_match(token, sub, reg2)) {
463 string data = sub.str(1);
464 // data is now all the bib files separated by ','
465 // get them one by one and pass them to the helper
466 while (!data.empty()) {
468 data = split(data, database, ',');
469 database = ChangeExtension(database, "bib");
470 lyxerr[Debug::LATEX] << "BibTeX database: `"
471 << database << '\'' << endl;
472 aux_info.databases.insert(database);
474 } else if (regex_match(token, sub, reg3)) {
475 string style = sub.str(1);
476 // token is now the style file
477 // pass it to the helper
478 style = ChangeExtension(style, "bst");
479 lyxerr[Debug::LATEX] << "BibTeX style: `"
480 << style << '\'' << endl;
481 aux_info.styles.insert(style);
482 } else if (regex_match(token, sub, reg4)) {
483 string const file2 = sub.str(1);
484 scanAuxFile(file2, aux_info);
490 void LaTeX::updateBibtexDependencies(DepTable & dep,
491 vector<Aux_Info> const & bibtex_info)
493 // Since a run of Bibtex mandates more latex runs it is ok to
494 // remove all ".bib" and ".bst" files.
495 dep.remove_files_with_extension(".bib");
496 dep.remove_files_with_extension(".bst");
497 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
499 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
500 it != bibtex_info.end(); ++it) {
501 for (set<string>::const_iterator it2 = it->databases.begin();
502 it2 != it->databases.end(); ++it2) {
503 string file = findtexfile(*it2, "bib");
505 dep.insert(file, true);
508 for (set<string>::const_iterator it2 = it->styles.begin();
509 it2 != it->styles.end(); ++it2) {
510 string file = findtexfile(*it2, "bst");
512 dep.insert(file, true);
518 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
521 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
522 it != bibtex_info.end(); ++it) {
523 if (it->databases.empty())
527 string tmp = lyxrc.bibtex_command + " ";
528 tmp += QuoteName(OnlyFilename(ChangeExtension(it->aux_file, string())));
530 one.startscript(Systemcall::Wait, tmp);
532 // Return whether bibtex was run
537 int LaTeX::scanLogFile(TeXErrors & terr)
541 int retval = NO_ERRORS;
542 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
543 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
544 ifstream ifs(tmp.c_str());
547 while (getline(ifs, token)) {
548 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
553 if (prefixIs(token, "LaTeX Warning:")) {
554 // Here shall we handle different
556 retval |= LATEX_WARNING;
557 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
558 if (contains(token, "Rerun to get cross-references")) {
561 << "We should rerun." << endl;
562 } else if (contains(token, "Citation")
563 && contains(token, "on page")
564 && contains(token, "undefined")) {
567 } else if (prefixIs(token, "Package")) {
569 retval |= PACKAGE_WARNING;
570 if (contains(token, "natbib Warning:")) {
572 if (contains(token, "Citation")
573 && contains(token, "on page")
574 && contains(token, "undefined")) {
577 } else if (contains(token, "run BibTeX")) {
579 } else if (contains(token, "Rerun LaTeX") ||
580 contains(token, "Rerun to get")) {
581 // at least longtable.sty and bibtopic.sty
584 << "We should rerun." << endl;
587 } else if (token[0] == '(') {
588 if (contains(token, "Rerun LaTeX") ||
589 contains(token, "Rerun to get")) {
592 << "We should rerun." << endl;
595 } else if (prefixIs(token, "! ")) {
596 // Ok, we have something that looks like a TeX Error
597 // but what do we really have.
599 // Just get the error description:
600 string desc(token, 2);
601 if (contains(token, "LaTeX Error:"))
602 retval |= LATEX_ERROR;
607 if (!getline(ifs, tmp))
611 } while (!prefixIs(tmp, "l."));
612 if (prefixIs(tmp, "l.")) {
613 // we have a latex error
615 if (contains(desc, "Package babel Error: You haven't defined the language"))
616 retval |= ERROR_RERUN;
617 // get the line number:
619 sscanf(tmp.c_str(), "l.%d", &line);
620 // get the rest of the message:
621 string errstr(tmp, tmp.find(' '));
624 while (!contains(errstr, "l.")
626 && !prefixIs(tmp, "! ")
627 && !contains(tmp, "(job aborted")) {
633 << "line: " << line << '\n'
634 << "Desc: " << desc << '\n'
635 << "Text: " << errstr << endl;
636 if (line == last_line)
642 if (line_count <= 5) {
643 terr.insertError(line, desc, errstr);
648 // information messages, TeX warnings and other
649 // warnings we have not caught earlier.
650 if (prefixIs(token, "Overfull ")) {
651 retval |= TEX_WARNING;
652 } else if (prefixIs(token, "Underfull ")) {
653 retval |= TEX_WARNING;
654 } else if (contains(token, "Rerun to get citations")) {
655 // Natbib seems to use this.
657 } else if (contains(token, "No pages of output")) {
658 // A dvi file was not created
660 } else if (contains(token, "That makes 100 errors")) {
661 // More than 100 errors were reprted
662 retval |= TOO_MANY_ERRORS;
666 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
673 void handleFoundFile(string const & ff, DepTable & head)
675 // convert from native os path to unix path
676 string const foundfile = os::internal_path(trim(ff));
678 lyxerr[Debug::DEPEND] << "Found file: " << foundfile << endl;
680 // Ok now we found a file.
681 // Now we should make sure that this is a file that we can
682 // access through the normal paths.
683 // We will not try any fancy search methods to
686 // (1) foundfile is an
687 // absolute path and should
689 if (AbsolutePath(foundfile)) {
690 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
691 << foundfile << endl;
692 // On initial insert we want to do the update at once
693 // since this file can not be a file generated by
695 if (FileInfo(foundfile).exist())
696 head.insert(foundfile, true);
701 string const onlyfile = OnlyFilename(foundfile);
703 // (2) foundfile is in the tmpdir
704 // insert it into head
705 if (FileInfo(onlyfile).exist()) {
706 static regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
707 if (regex_match(onlyfile, unwanted)) {
708 lyxerr[Debug::DEPEND]
711 << " in the dep file"
713 } else if (suffixIs(onlyfile, ".tex")) {
714 // This is a tex file generated by LyX
715 // and latex is not likely to change this
717 lyxerr[Debug::DEPEND]
718 << "Tmpdir TeX file: "
721 head.insert(onlyfile, true);
723 lyxerr[Debug::DEPEND]
727 head.insert(onlyfile);
730 lyxerr[Debug::DEPEND]
731 << "Not a file or we are unable to find it."
738 void LaTeX::deplog(DepTable & head)
740 // This function reads the LaTeX log file end extracts all the external
741 // files used by the LaTeX run. The files are then entered into the
744 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
746 static regex reg1(".*\\([^)]+.*");
747 static regex reg2("File: ([^ ]+).*");
748 static regex reg3("No file ([^ ]+)\\..*");
749 static regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
750 // If an index should be created, MikTex does not write a line like
751 // \openout# = 'sample,idx'.
752 // but intstead only a line like this into the log:
753 // Writing index file sample.idx
754 static regex reg5("Writing index file ([^ ]+).*");
756 ifstream ifs(logfile.c_str());
758 // Ok, the scanning of files here is not sufficient.
759 // Sometimes files are named by "File: xxx" only
760 // So I think we should use some regexps to find files instead.
761 // "(\([^ ]+\)" should match the "(file " variant, note
762 // that we can have several of these on one line.
763 // "File: \([^ ]+\)" should match the "File: file" variant
767 token = rtrim(token, "\r");
773 if (regex_match(token, sub, reg1)) {
774 static regex reg1_1("\\(([^()]+)");
776 string::const_iterator first = token.begin();
777 string::const_iterator end = token.end();
779 while (regex_search(first, end, what, reg1_1)) {
780 first = what[0].second;
781 handleFoundFile(what.str(1), head);
783 } else if (regex_match(token, sub, reg2)) {
784 handleFoundFile(sub.str(1), head);
785 } else if (regex_match(token, sub, reg3)) {
786 handleFoundFile(sub.str(1), head);
787 } else if (regex_match(token, sub, reg4)) {
788 handleFoundFile(sub.str(1), head);
789 } else if (regex_match(token, sub, reg5)) {
790 handleFoundFile(sub.str(1), head);
794 // Make sure that the main .tex file is in the dependancy file.
795 head.insert(OnlyFilename(file), true);