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.
17 #include "bufferlist.h"
24 #include "support/filetools.h"
25 #include "support/convert.h"
26 #include "support/lstrings.h"
27 #include "support/lyxlib.h"
28 #include "support/systemcall.h"
29 #include "support/os.h"
31 #include <boost/filesystem/operations.hpp>
32 #include <boost/regex.hpp>
39 using support::absolutePath;
40 using support::bformat;
41 using support::changeExtension;
42 using support::contains;
43 using support::findtexfile;
44 using support::getcwd;
45 using support::onlyFilename;
46 using support::prefixIs;
47 using support::quoteName;
51 using support::suffixIs;
52 using support::Systemcall;
53 using support::unlink;
56 namespace os = support::os;
57 namespace fs = boost::filesystem;
63 #ifndef CXX_GLOBAL_CSTD
74 // TODO: in no particular order
75 // - get rid of the call to
76 // BufferList::updateIncludedTeXfiles, this should either
77 // be done before calling LaTeX::funcs or in a completely
79 // - the makeindex style files should be taken care of with
80 // the dependency mechanism.
81 // - makeindex commandline options should be supported
82 // - somewhere support viewing of bibtex and makeindex log files.
83 // - we should perhaps also scan the bibtex log file
87 docstring runMessage(unsigned int count)
89 return bformat(_("Waiting for LaTeX run number %1$d"), count);
98 void TeXErrors::insertError(int line, string const & error_desc,
99 string const & error_text)
101 Error newerr(line, error_desc, error_text);
102 errors.push_back(newerr);
106 bool operator==(Aux_Info const & a, Aux_Info const & o)
108 return a.aux_file == o.aux_file &&
109 a.citations == o.citations &&
110 a.databases == o.databases &&
111 a.styles == o.styles;
115 bool operator!=(Aux_Info const & a, Aux_Info const & o)
125 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
126 string const & f, string const & p)
127 : cmd(latex), file(f), path(p), runparams(rp)
130 depfile = file + ".dep";
131 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
133 output_file = changeExtension(file,".pdf");
135 output_file = changeExtension(file,".dvi");
140 void LaTeX::deleteFilesOnError() const
142 // currently just a dummy function.
144 // What files do we have to delete?
146 // This will at least make latex do all the runs
149 // but the reason for the error might be in a generated file...
151 string const ofname = onlyFilename(file);
154 string const bbl = changeExtension(ofname, ".bbl");
158 string const ind = changeExtension(ofname, ".ind");
161 // Also remove the aux file
162 string const aux = changeExtension(ofname, ".aux");
167 int LaTeX::run(TeXErrors & terr)
168 // We know that this function will only be run if the lyx buffer
169 // has been changed. We also know that a newly written .tex file
170 // is always different from the previous one because of the date
171 // in it. However it seems safe to run latex (at least) on time each
172 // time the .tex file changes.
174 int scanres = NO_ERRORS;
175 unsigned int count = 0; // number of times run
176 num_errors = 0; // just to make sure.
177 unsigned int const MAX_RUN = 6;
178 DepTable head; // empty head
179 bool rerun = false; // rerun requested
181 // The class LaTeX does not know the temp path.
182 theBufferList().updateIncludedTeXfiles(getcwd(), runparams);
184 // Never write the depfile if an error was encountered.
187 // first check if the file dependencies exist:
188 // ->If it does exist
189 // check if any of the files mentioned in it have
190 // changed (done using a checksum).
192 // run latex once and
193 // remake the dependency file
194 // -> if not changed:
195 // just return there is nothing to do for us.
196 // ->if it doesn't exist
198 // run latex once (we need to run latex once anyway) and
199 // remake the dependency file.
202 bool had_depfile = fs::exists(depfile);
203 bool run_bibtex = false;
204 string aux_file = onlyFilename(changeExtension(file, "aux"));
207 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
208 // Read the dep file:
209 had_depfile = head.read(depfile);
213 // Update the checksums
215 // Can't just check if anything has changed because it might have aborted
216 // on error last time... in which cas we need to re-run latex
217 // and collect the error messages (even if they are the same).
218 if (!fs::exists(output_file)) {
219 lyxerr[Debug::DEPEND]
220 << "re-running LaTeX because output file doesn't exist." << endl;
221 } else if (!head.sumchange()) {
222 lyxerr[Debug::DEPEND] << "return no_change" << endl;
225 lyxerr[Debug::DEPEND]
226 << "Dependency file has changed" << endl;
229 if (head.extchanged(".bib") || head.extchanged(".bst"))
232 lyxerr[Debug::DEPEND]
233 << "Dependency file does not exist, or has wrong format" << endl;
235 /// We scan the aux file even when had_depfile = false,
236 /// because we can run pdflatex on the file after running latex on it,
237 /// in which case we will not need to run bibtex again.
238 vector<Aux_Info> bibtex_info_old;
240 bibtex_info_old = scanAuxFiles(aux_file);
243 lyxerr[Debug::LATEX] << "Run #" << count << endl;
244 message(runMessage(count));
247 scanres = scanLogFile(terr);
248 if (scanres & ERROR_RERUN) {
249 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
251 scanres = scanLogFile(terr);
254 if (scanres & ERRORS) {
255 deleteFilesOnError();
256 return scanres; // return on error
259 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
260 if (!run_bibtex && bibtex_info_old != bibtex_info)
263 // update the dependencies.
264 deplog(head); // reads the latex log
268 // At this point we must run external programs if needed.
269 // makeindex will be run if a .idx file changed or was generated.
270 // And if there were undefined citations or changes in references
271 // the .aux file is checked for signs of bibtex. Bibtex is then run
274 // memoir (at least) writes an empty *idx file in the first place.
275 // A second latex run is needed.
276 rerun = fs::exists(changeExtension(file, ".idx"))
277 && fs::is_empty(changeExtension(file, ".idx"));
280 if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
282 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
283 message(_("Running MakeIndex."));
284 rerun |= runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
288 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
289 if (scanres & UNDEF_CIT || run_bibtex) {
290 // Here we must scan the .aux file and look for
291 // "\bibdata" and/or "\bibstyle". If one of those
292 // tags is found -> run bibtex and set rerun = true;
294 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
295 message(_("Running BibTeX."));
296 updateBibtexDependencies(head, bibtex_info);
297 rerun |= runBibTeX(bibtex_info);
298 } else if (!had_depfile) {
299 /// If we run pdflatex on the file after running latex on it,
300 /// then we do not need to run bibtex, but we do need to
301 /// insert the .bib and .bst files into the .dep-pdf file.
302 updateBibtexDependencies(head, bibtex_info);
306 // we know on this point that latex has been run once (or we just
307 // returned) and the question now is to decide if we need to run
308 // it any more. This is done by asking if any of the files in the
309 // dependency file has changed. (remember that the checksum for
310 // a given file is reported to have changed if it just was created)
311 // -> if changed or rerun == true:
312 // run latex once more and
313 // update the dependency structure
314 // -> if not changed:
315 // we does nothing at this point
317 if (rerun || head.sumchange()) {
320 lyxerr[Debug::DEPEND]
321 << "Dep. file has changed or rerun requested" << endl;
323 << "Run #" << count << endl;
324 message(runMessage(count));
326 scanres = scanLogFile(terr);
327 if (scanres & ERRORS) {
328 deleteFilesOnError();
329 return scanres; // return on error
332 // update the depedencies
333 deplog(head); // reads the latex log
336 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
340 // The inclusion of files generated by external programs like
341 // makeindex or bibtex might have done changes to pagenumbering,
342 // etc. And because of this we must run the external programs
343 // again to make sure everything is redone correctly.
344 // Also there should be no need to run the external programs any
347 // run makeindex if the <file>.idx has changed or was generated.
348 if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
350 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
351 message(_("Running MakeIndex."));
352 rerun = runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
356 // we will only run latex more if the log file asks for it.
357 // or if the sumchange() is true.
358 // -> rerun asked for:
360 // remake the dependency file
361 // goto 2 or return if max runs are reached.
362 // -> rerun not asked for:
363 // just return (fall out of bottom of func)
365 while ((head.sumchange() || rerun || (scanres & RERUN))
366 && count < MAX_RUN) {
367 // Yes rerun until message goes away, or until
368 // MAX_RUNS are reached.
371 lyxerr[Debug::LATEX] << "Run #" << count << endl;
372 message(runMessage(count));
374 scanres = scanLogFile(terr);
375 if (scanres & ERRORS) {
376 deleteFilesOnError();
377 return scanres; // return on error
384 // Write the dependencies to file.
386 lyxerr[Debug::LATEX] << "Done." << endl;
391 int LaTeX::startscript()
393 string tmp = cmd + ' ' + quoteName(file) + " > " + os::nulldev();
395 return one.startscript(Systemcall::Wait, tmp);
399 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams)
401 lyxerr[Debug::LATEX] << "idx file has been made,"
402 " running makeindex on file " << f << endl;
403 string tmp = lyxrc.index_command + " ";
404 tmp = subst(tmp, "$$lang", runparams.document_language);
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 const file2 = changeExtension(file, "")
421 + '.' + convert<string>(i)
423 if (!fs::exists(file2))
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 static regex const reg1("\\\\citation\\{([^}]+)\\}");
447 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
448 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
449 static regex const reg4("\\\\@input\\{([^}]+)\\}");
451 while (getline(ifs, token)) {
452 token = rtrim(token, "\r");
454 if (regex_match(token, sub, reg1)) {
455 string data = sub.str(1);
456 while (!data.empty()) {
458 data = split(data, citation, ',');
459 lyxerr[Debug::LATEX] << "Citation: "
461 aux_info.citations.insert(citation);
463 } else if (regex_match(token, sub, reg2)) {
464 string data = sub.str(1);
465 // data is now all the bib files separated by ','
466 // get them one by one and pass them to the helper
467 while (!data.empty()) {
469 data = split(data, database, ',');
470 database = changeExtension(database, "bib");
471 lyxerr[Debug::LATEX] << "BibTeX database: `"
472 << database << '\'' << endl;
473 aux_info.databases.insert(database);
475 } else if (regex_match(token, sub, reg3)) {
476 string style = sub.str(1);
477 // token is now the style file
478 // pass it to the helper
479 style = changeExtension(style, "bst");
480 lyxerr[Debug::LATEX] << "BibTeX style: `"
481 << style << '\'' << endl;
482 aux_info.styles.insert(style);
483 } else if (regex_match(token, sub, reg4)) {
484 string const file2 = sub.str(1);
485 scanAuxFile(file2, aux_info);
491 void LaTeX::updateBibtexDependencies(DepTable & dep,
492 vector<Aux_Info> const & bibtex_info)
494 // Since a run of Bibtex mandates more latex runs it is ok to
495 // remove all ".bib" and ".bst" files.
496 dep.remove_files_with_extension(".bib");
497 dep.remove_files_with_extension(".bst");
498 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
500 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
501 it != bibtex_info.end(); ++it) {
502 for (set<string>::const_iterator it2 = it->databases.begin();
503 it2 != it->databases.end(); ++it2) {
504 string file = findtexfile(*it2, "bib");
506 dep.insert(file, true);
509 for (set<string>::const_iterator it2 = it->styles.begin();
510 it2 != it->styles.end(); ++it2) {
511 string file = findtexfile(*it2, "bst");
513 dep.insert(file, true);
519 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
522 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
523 it != bibtex_info.end(); ++it) {
524 if (it->databases.empty())
528 string tmp = lyxrc.bibtex_command + " ";
529 tmp += quoteName(onlyFilename(changeExtension(it->aux_file, string())));
531 one.startscript(Systemcall::Wait, tmp);
533 // Return whether bibtex was run
538 int LaTeX::scanLogFile(TeXErrors & terr)
542 int retval = NO_ERRORS;
543 string tmp = onlyFilename(changeExtension(file, ".log"));
544 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
545 ifstream ifs(tmp.c_str());
548 while (getline(ifs, token)) {
549 // MikTeX sometimes inserts \0 in the log file. They can't be
550 // removed directly with the existing string utility
551 // functions, so convert them first to \r, and remove all
552 // \r's afterwards, since we need to remove them anyway.
553 token = subst(token, '\0', '\r');
554 token = subst(token, "\r", "");
556 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
561 if (prefixIs(token, "LaTeX Warning:") ||
562 prefixIs(token, "! pdfTeX warning")) {
563 // Here shall we handle different
565 retval |= LATEX_WARNING;
566 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
567 if (contains(token, "Rerun to get cross-references")) {
570 << "We should rerun." << endl;
571 } else if (contains(token, "Citation")
572 && contains(token, "on page")
573 && contains(token, "undefined")) {
576 } else if (prefixIs(token, "Package")) {
578 retval |= PACKAGE_WARNING;
579 if (contains(token, "natbib Warning:")) {
581 if (contains(token, "Citation")
582 && contains(token, "on page")
583 && contains(token, "undefined")) {
586 } else if (contains(token, "run BibTeX")) {
588 } else if (contains(token, "Rerun LaTeX") ||
589 contains(token, "Rerun to get")) {
590 // at least longtable.sty and bibtopic.sty
593 << "We should rerun." << endl;
596 } else if (token[0] == '(') {
597 if (contains(token, "Rerun LaTeX") ||
598 contains(token, "Rerun to get")) {
601 << "We should rerun." << endl;
604 } else if (prefixIs(token, "! ")) {
605 // Ok, we have something that looks like a TeX Error
606 // but what do we really have.
608 // Just get the error description:
609 string desc(token, 2);
610 if (contains(token, "LaTeX Error:"))
611 retval |= LATEX_ERROR;
616 if (!getline(ifs, tmp))
620 } while (!prefixIs(tmp, "l."));
621 if (prefixIs(tmp, "l.")) {
622 // we have a latex error
624 if (contains(desc, "Package babel Error: You haven't defined the language"))
625 retval |= ERROR_RERUN;
626 // get the line number:
628 sscanf(tmp.c_str(), "l.%d", &line);
629 // get the rest of the message:
630 string errstr(tmp, tmp.find(' '));
633 while (!contains(errstr, "l.")
635 && !prefixIs(tmp, "! ")
636 && !contains(tmp, "(job aborted")) {
642 << "line: " << line << '\n'
643 << "Desc: " << desc << '\n'
644 << "Text: " << errstr << endl;
645 if (line == last_line)
651 if (line_count <= 5) {
652 terr.insertError(line, desc, errstr);
657 // information messages, TeX warnings and other
658 // warnings we have not caught earlier.
659 if (prefixIs(token, "Overfull ")) {
660 retval |= TEX_WARNING;
661 } else if (prefixIs(token, "Underfull ")) {
662 retval |= TEX_WARNING;
663 } else if (contains(token, "Rerun to get citations")) {
664 // Natbib seems to use this.
666 } else if (contains(token, "No pages of output")) {
667 // A dvi file was not created
669 } else if (contains(token, "That makes 100 errors")) {
670 // More than 100 errors were reprted
671 retval |= TOO_MANY_ERRORS;
675 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
682 void handleFoundFile(string const & ff, DepTable & head)
684 // convert from native os path to unix path
685 string const foundfile = os::internal_path(trim(ff));
687 lyxerr[Debug::DEPEND] << "Found file: " << foundfile << endl;
689 // Ok now we found a file.
690 // Now we should make sure that this is a file that we can
691 // access through the normal paths.
692 // We will not try any fancy search methods to
695 // (1) foundfile is an
696 // absolute path and should
698 if (absolutePath(foundfile)) {
699 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
700 << foundfile << endl;
701 // On initial insert we want to do the update at once
702 // since this file can not be a file generated by
704 if (fs::exists(foundfile) && !fs::is_directory(foundfile))
705 head.insert(foundfile, true);
710 string const onlyfile = onlyFilename(foundfile);
712 // (2) foundfile is in the tmpdir
713 // insert it into head
714 if (fs::exists(onlyfile)) {
715 static regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
716 if (regex_match(onlyfile, unwanted)) {
717 lyxerr[Debug::DEPEND]
720 << " in the dep file"
722 } else if (suffixIs(onlyfile, ".tex")) {
723 // This is a tex file generated by LyX
724 // and latex is not likely to change this
726 lyxerr[Debug::DEPEND]
727 << "Tmpdir TeX file: "
730 head.insert(onlyfile, true);
732 lyxerr[Debug::DEPEND]
736 head.insert(onlyfile);
739 lyxerr[Debug::DEPEND]
740 << "Not a file or we are unable to find it."
747 void LaTeX::deplog(DepTable & head)
749 // This function reads the LaTeX log file end extracts all the external
750 // files used by the LaTeX run. The files are then entered into the
753 string const logfile = onlyFilename(changeExtension(file, ".log"));
755 static regex reg1(".*\\([^)]+.*");
756 static regex reg2("File: ([^ ]+).*");
757 static regex reg3("No file ([^ ]+)\\..*");
758 static regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
759 // If an index should be created, MikTex does not write a line like
760 // \openout# = 'sample.idx'.
761 // but instead only a line like this into the log:
762 // Writing index file sample.idx
763 static regex reg5("Writing index file ([^ ]+).*");
764 // If a toc should be created, MikTex does not write a line like
765 // \openout# = `sample.toc'.
766 // but only a line like this into the log:
768 // This line is also written by tetex.
769 // This line is not present if no toc should be created.
770 static regex miktexTocReg("\\\\tf@toc=\\\\write.*");
772 ifstream ifs(logfile.c_str());
774 // Ok, the scanning of files here is not sufficient.
775 // Sometimes files are named by "File: xxx" only
776 // So I think we should use some regexps to find files instead.
777 // "(\([^ ]+\)" should match the "(file " variant, note
778 // that we can have several of these on one line.
779 // "File: \([^ ]+\)" should match the "File: file" variant
783 // MikTeX sometimes inserts \0 in the log file. They can't be
784 // removed directly with the existing string utility
785 // functions, so convert them first to \r, and remove all
786 // \r's afterwards, since we need to remove them anyway.
787 token = subst(token, '\0', '\r');
788 token = subst(token, "\r", "");
794 if (regex_match(token, sub, reg1)) {
795 static regex reg1_1("\\(([^()]+)");
797 string::const_iterator first = token.begin();
798 string::const_iterator end = token.end();
800 while (regex_search(first, end, what, reg1_1)) {
801 first = what[0].second;
802 handleFoundFile(what.str(1), head);
804 } else if (regex_match(token, sub, reg2))
805 handleFoundFile(sub.str(1), head);
806 else if (regex_match(token, sub, reg3))
807 handleFoundFile(sub.str(1), head);
808 else if (regex_match(token, sub, reg4))
809 handleFoundFile(sub.str(1), head);
810 else if (regex_match(token, sub, reg5))
811 handleFoundFile(sub.str(1), head);
812 else if (regex_match(token, sub, miktexTocReg))
813 handleFoundFile(changeExtension(file, ".toc"), head);
816 // Make sure that the main .tex file is in the dependancy file.
817 head.insert(onlyFilename(file), true);