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 "frontends/Application.h"
26 #include "support/filetools.h"
27 #include "support/convert.h"
28 #include "support/lstrings.h"
29 #include "support/lyxlib.h"
30 #include "support/systemcall.h"
31 #include "support/os.h"
33 #include <boost/filesystem/operations.hpp>
34 #include <boost/regex.hpp>
38 using lyx::support::absolutePath;
39 using lyx::support::bformat;
40 using lyx::support::changeExtension;
41 using lyx::support::contains;
42 using lyx::support::findtexfile;
43 using lyx::support::getcwd;
44 using lyx::support::onlyFilename;
45 using lyx::support::prefixIs;
46 using lyx::support::quoteName;
47 using lyx::support::rtrim;
48 using lyx::support::split;
49 using lyx::support::subst;
50 using lyx::support::suffixIs;
51 using lyx::support::Systemcall;
52 using lyx::support::unlink;
53 using lyx::support::trim;
57 namespace os = lyx::support::os;
58 namespace fs = boost::filesystem;
64 #ifndef CXX_GLOBAL_CSTD
75 // TODO: in no particular order
76 // - get rid of the call to
77 // BufferList::updateIncludedTeXfiles, this should either
78 // be done before calling LaTeX::funcs or in a completely
80 // - the makeindex style files should be taken care of with
81 // the dependency mechanism.
82 // - makeindex commandline options should be supported
83 // - somewhere support viewing of bibtex and makeindex log files.
84 // - we should perhaps also scan the bibtex log file
88 docstring runMessage(unsigned int count)
90 return bformat(_("Waiting for LaTeX run number %1$d"), count);
99 void TeXErrors::insertError(int line, string const & error_desc,
100 string const & error_text)
102 Error newerr(line, error_desc, error_text);
103 errors.push_back(newerr);
107 bool operator==(Aux_Info const & a, Aux_Info const & o)
109 return a.aux_file == o.aux_file &&
110 a.citations == o.citations &&
111 a.databases == o.databases &&
112 a.styles == o.styles;
116 bool operator!=(Aux_Info const & a, Aux_Info const & o)
126 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
127 string const & f, string const & p)
128 : cmd(latex), file(f), path(p), runparams(rp)
131 depfile = file + ".dep";
132 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
134 output_file = changeExtension(file,".pdf");
136 output_file = changeExtension(file,".dvi");
141 void LaTeX::deleteFilesOnError() const
143 // currently just a dummy function.
145 // What files do we have to delete?
147 // This will at least make latex do all the runs
150 // but the reason for the error might be in a generated file...
152 string const ofname = onlyFilename(file);
155 string const bbl = changeExtension(ofname, ".bbl");
159 string const ind = changeExtension(ofname, ".ind");
162 // Also remove the aux file
163 string const aux = changeExtension(ofname, ".aux");
168 int LaTeX::run(TeXErrors & terr)
169 // We know that this function will only be run if the lyx buffer
170 // has been changed. We also know that a newly written .tex file
171 // is always different from the previous one because of the date
172 // in it. However it seems safe to run latex (at least) on time each
173 // time the .tex file changes.
175 int scanres = NO_ERRORS;
176 unsigned int count = 0; // number of times run
177 num_errors = 0; // just to make sure.
178 unsigned int const MAX_RUN = 6;
179 DepTable head; // empty head
180 bool rerun = false; // rerun requested
182 // The class LaTeX does not know the temp path.
183 theApp->bufferList().updateIncludedTeXfiles(getcwd(), runparams);
185 // Never write the depfile if an error was encountered.
188 // first check if the file dependencies exist:
189 // ->If it does exist
190 // check if any of the files mentioned in it have
191 // changed (done using a checksum).
193 // run latex once and
194 // remake the dependency file
195 // -> if not changed:
196 // just return there is nothing to do for us.
197 // ->if it doesn't exist
199 // run latex once (we need to run latex once anyway) and
200 // remake the dependency file.
203 bool had_depfile = fs::exists(depfile);
204 bool run_bibtex = false;
205 string aux_file = onlyFilename(changeExtension(file, "aux"));
208 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
209 // Read the dep file:
210 had_depfile = head.read(depfile);
214 // Update the checksums
216 // Can't just check if anything has changed because it might have aborted
217 // on error last time... in which cas we need to re-run latex
218 // and collect the error messages (even if they are the same).
219 if (!fs::exists(output_file)) {
220 lyxerr[Debug::DEPEND]
221 << "re-running LaTeX because output file doesn't exist." << endl;
222 } else if (!head.sumchange()) {
223 lyxerr[Debug::DEPEND] << "return no_change" << endl;
226 lyxerr[Debug::DEPEND]
227 << "Dependency file has changed" << endl;
230 if (head.extchanged(".bib") || head.extchanged(".bst"))
233 lyxerr[Debug::DEPEND]
234 << "Dependency file does not exist, or has wrong format" << endl;
236 /// We scan the aux file even when had_depfile = false,
237 /// because we can run pdflatex on the file after running latex on it,
238 /// in which case we will not need to run bibtex again.
239 vector<Aux_Info> bibtex_info_old;
241 bibtex_info_old = scanAuxFiles(aux_file);
244 lyxerr[Debug::LATEX] << "Run #" << count << endl;
245 message(runMessage(count));
248 scanres = scanLogFile(terr);
249 if (scanres & ERROR_RERUN) {
250 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
252 scanres = scanLogFile(terr);
255 if (scanres & ERRORS) {
256 deleteFilesOnError();
257 return scanres; // return on error
260 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
261 if (!run_bibtex && bibtex_info_old != bibtex_info)
264 // update the dependencies.
265 deplog(head); // reads the latex log
269 // At this point we must run external programs if needed.
270 // makeindex will be run if a .idx file changed or was generated.
271 // And if there were undefined citations or changes in references
272 // the .aux file is checked for signs of bibtex. Bibtex is then run
275 // memoir (at least) writes an empty *idx file in the first place.
276 // A second latex run is needed.
277 rerun = fs::exists(changeExtension(file, ".idx"))
278 && fs::is_empty(changeExtension(file, ".idx"));
281 if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
283 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
284 message(_("Running MakeIndex."));
285 rerun |= runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
289 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
290 if (scanres & UNDEF_CIT || run_bibtex) {
291 // Here we must scan the .aux file and look for
292 // "\bibdata" and/or "\bibstyle". If one of those
293 // tags is found -> run bibtex and set rerun = true;
295 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
296 message(_("Running BibTeX."));
297 updateBibtexDependencies(head, bibtex_info);
298 rerun |= runBibTeX(bibtex_info);
299 } else if (!had_depfile) {
300 /// If we run pdflatex on the file after running latex on it,
301 /// then we do not need to run bibtex, but we do need to
302 /// insert the .bib and .bst files into the .dep-pdf file.
303 updateBibtexDependencies(head, bibtex_info);
307 // we know on this point that latex has been run once (or we just
308 // returned) and the question now is to decide if we need to run
309 // it any more. This is done by asking if any of the files in the
310 // dependency file has changed. (remember that the checksum for
311 // a given file is reported to have changed if it just was created)
312 // -> if changed or rerun == true:
313 // run latex once more and
314 // update the dependency structure
315 // -> if not changed:
316 // we does nothing at this point
318 if (rerun || head.sumchange()) {
321 lyxerr[Debug::DEPEND]
322 << "Dep. file has changed or rerun requested" << endl;
324 << "Run #" << count << endl;
325 message(runMessage(count));
327 scanres = scanLogFile(terr);
328 if (scanres & ERRORS) {
329 deleteFilesOnError();
330 return scanres; // return on error
333 // update the depedencies
334 deplog(head); // reads the latex log
337 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
341 // The inclusion of files generated by external programs like
342 // makeindex or bibtex might have done changes to pagenumbering,
343 // etc. And because of this we must run the external programs
344 // again to make sure everything is redone correctly.
345 // Also there should be no need to run the external programs any
348 // run makeindex if the <file>.idx has changed or was generated.
349 if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
351 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
352 message(_("Running MakeIndex."));
353 rerun = runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
357 // we will only run latex more if the log file asks for it.
358 // or if the sumchange() is true.
359 // -> rerun asked for:
361 // remake the dependency file
362 // goto 2 or return if max runs are reached.
363 // -> rerun not asked for:
364 // just return (fall out of bottom of func)
366 while ((head.sumchange() || rerun || (scanres & RERUN))
367 && count < MAX_RUN) {
368 // Yes rerun until message goes away, or until
369 // MAX_RUNS are reached.
372 lyxerr[Debug::LATEX] << "Run #" << count << endl;
373 message(runMessage(count));
375 scanres = scanLogFile(terr);
376 if (scanres & ERRORS) {
377 deleteFilesOnError();
378 return scanres; // return on error
385 // Write the dependencies to file.
387 lyxerr[Debug::LATEX] << "Done." << endl;
392 int LaTeX::startscript()
394 string tmp = cmd + ' ' + quoteName(file) + " > " + os::nulldev();
396 return one.startscript(Systemcall::Wait, tmp);
400 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams)
402 lyxerr[Debug::LATEX] << "idx file has been made,"
403 " running makeindex on file "
405 string tmp = lyxrc.index_command + " ";
406 tmp = subst(tmp, "$$lang", runparams.document_language);
409 one.startscript(Systemcall::Wait, tmp);
414 vector<Aux_Info> const
415 LaTeX::scanAuxFiles(string const & file)
417 vector<Aux_Info> result;
419 result.push_back(scanAuxFile(file));
421 for (int i = 1; i < 1000; ++i) {
422 string const file2 = changeExtension(file, "")
423 + '.' + convert<string>(i)
425 if (!fs::exists(file2))
427 result.push_back(scanAuxFile(file2));
433 Aux_Info const LaTeX::scanAuxFile(string const & file)
436 result.aux_file = file;
437 scanAuxFile(file, result);
442 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
444 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
446 ifstream ifs(file.c_str());
448 static regex const reg1("\\\\citation\\{([^}]+)\\}");
449 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
450 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
451 static regex const reg4("\\\\@input\\{([^}]+)\\}");
453 while (getline(ifs, token)) {
454 token = rtrim(token, "\r");
456 if (regex_match(token, sub, reg1)) {
457 string data = sub.str(1);
458 while (!data.empty()) {
460 data = split(data, citation, ',');
461 lyxerr[Debug::LATEX] << "Citation: "
463 aux_info.citations.insert(citation);
465 } else if (regex_match(token, sub, reg2)) {
466 string data = sub.str(1);
467 // data is now all the bib files separated by ','
468 // get them one by one and pass them to the helper
469 while (!data.empty()) {
471 data = split(data, database, ',');
472 database = changeExtension(database, "bib");
473 lyxerr[Debug::LATEX] << "BibTeX database: `"
474 << database << '\'' << endl;
475 aux_info.databases.insert(database);
477 } else if (regex_match(token, sub, reg3)) {
478 string style = sub.str(1);
479 // token is now the style file
480 // pass it to the helper
481 style = changeExtension(style, "bst");
482 lyxerr[Debug::LATEX] << "BibTeX style: `"
483 << style << '\'' << endl;
484 aux_info.styles.insert(style);
485 } else if (regex_match(token, sub, reg4)) {
486 string const file2 = sub.str(1);
487 scanAuxFile(file2, aux_info);
493 void LaTeX::updateBibtexDependencies(DepTable & dep,
494 vector<Aux_Info> const & bibtex_info)
496 // Since a run of Bibtex mandates more latex runs it is ok to
497 // remove all ".bib" and ".bst" files.
498 dep.remove_files_with_extension(".bib");
499 dep.remove_files_with_extension(".bst");
500 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
502 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
503 it != bibtex_info.end(); ++it) {
504 for (set<string>::const_iterator it2 = it->databases.begin();
505 it2 != it->databases.end(); ++it2) {
506 string file = findtexfile(*it2, "bib");
508 dep.insert(file, true);
511 for (set<string>::const_iterator it2 = it->styles.begin();
512 it2 != it->styles.end(); ++it2) {
513 string file = findtexfile(*it2, "bst");
515 dep.insert(file, true);
521 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
524 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
525 it != bibtex_info.end(); ++it) {
526 if (it->databases.empty())
530 string tmp = lyxrc.bibtex_command + " ";
531 tmp += quoteName(onlyFilename(changeExtension(it->aux_file, string())));
533 one.startscript(Systemcall::Wait, tmp);
535 // Return whether bibtex was run
540 int LaTeX::scanLogFile(TeXErrors & terr)
544 int retval = NO_ERRORS;
545 string tmp = onlyFilename(changeExtension(file, ".log"));
546 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
547 ifstream ifs(tmp.c_str());
550 while (getline(ifs, token)) {
551 // MikTeX sometimes inserts \0 in the log file. They can't be
552 // removed directly with the existing string utility
553 // functions, so convert them first to \r, and remove all
554 // \r's afterwards, since we need to remove them anyway.
555 token = subst(token, '\0', '\r');
556 token = subst(token, "\r", "");
558 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
563 if (prefixIs(token, "LaTeX Warning:") ||
564 prefixIs(token, "! pdfTeX warning")) {
565 // Here shall we handle different
567 retval |= LATEX_WARNING;
568 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
569 if (contains(token, "Rerun to get cross-references")) {
572 << "We should rerun." << endl;
573 } else if (contains(token, "Citation")
574 && contains(token, "on page")
575 && contains(token, "undefined")) {
578 } else if (prefixIs(token, "Package")) {
580 retval |= PACKAGE_WARNING;
581 if (contains(token, "natbib Warning:")) {
583 if (contains(token, "Citation")
584 && contains(token, "on page")
585 && contains(token, "undefined")) {
588 } else if (contains(token, "run BibTeX")) {
590 } else if (contains(token, "Rerun LaTeX") ||
591 contains(token, "Rerun to get")) {
592 // at least longtable.sty and bibtopic.sty
595 << "We should rerun." << endl;
598 } else if (token[0] == '(') {
599 if (contains(token, "Rerun LaTeX") ||
600 contains(token, "Rerun to get")) {
603 << "We should rerun." << endl;
606 } else if (prefixIs(token, "! ")) {
607 // Ok, we have something that looks like a TeX Error
608 // but what do we really have.
610 // Just get the error description:
611 string desc(token, 2);
612 if (contains(token, "LaTeX Error:"))
613 retval |= LATEX_ERROR;
618 if (!getline(ifs, tmp))
622 } while (!prefixIs(tmp, "l."));
623 if (prefixIs(tmp, "l.")) {
624 // we have a latex error
626 if (contains(desc, "Package babel Error: You haven't defined the language"))
627 retval |= ERROR_RERUN;
628 // get the line number:
630 sscanf(tmp.c_str(), "l.%d", &line);
631 // get the rest of the message:
632 string errstr(tmp, tmp.find(' '));
635 while (!contains(errstr, "l.")
637 && !prefixIs(tmp, "! ")
638 && !contains(tmp, "(job aborted")) {
644 << "line: " << line << '\n'
645 << "Desc: " << desc << '\n'
646 << "Text: " << errstr << endl;
647 if (line == last_line)
653 if (line_count <= 5) {
654 terr.insertError(line, desc, errstr);
659 // information messages, TeX warnings and other
660 // warnings we have not caught earlier.
661 if (prefixIs(token, "Overfull ")) {
662 retval |= TEX_WARNING;
663 } else if (prefixIs(token, "Underfull ")) {
664 retval |= TEX_WARNING;
665 } else if (contains(token, "Rerun to get citations")) {
666 // Natbib seems to use this.
668 } else if (contains(token, "No pages of output")) {
669 // A dvi file was not created
671 } else if (contains(token, "That makes 100 errors")) {
672 // More than 100 errors were reprted
673 retval |= TOO_MANY_ERRORS;
677 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
684 void handleFoundFile(string const & ff, DepTable & head)
686 // convert from native os path to unix path
687 string const foundfile = os::internal_path(trim(ff));
689 lyxerr[Debug::DEPEND] << "Found file: " << foundfile << endl;
691 // Ok now we found a file.
692 // Now we should make sure that this is a file that we can
693 // access through the normal paths.
694 // We will not try any fancy search methods to
697 // (1) foundfile is an
698 // absolute path and should
700 if (absolutePath(foundfile)) {
701 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
702 << foundfile << endl;
703 // On initial insert we want to do the update at once
704 // since this file can not be a file generated by
706 if (fs::exists(foundfile) && !fs::is_directory(foundfile))
707 head.insert(foundfile, true);
712 string const onlyfile = onlyFilename(foundfile);
714 // (2) foundfile is in the tmpdir
715 // insert it into head
716 if (fs::exists(onlyfile)) {
717 static regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
718 if (regex_match(onlyfile, unwanted)) {
719 lyxerr[Debug::DEPEND]
722 << " in the dep file"
724 } else if (suffixIs(onlyfile, ".tex")) {
725 // This is a tex file generated by LyX
726 // and latex is not likely to change this
728 lyxerr[Debug::DEPEND]
729 << "Tmpdir TeX file: "
732 head.insert(onlyfile, true);
734 lyxerr[Debug::DEPEND]
738 head.insert(onlyfile);
741 lyxerr[Debug::DEPEND]
742 << "Not a file or we are unable to find it."
749 void LaTeX::deplog(DepTable & head)
751 // This function reads the LaTeX log file end extracts all the external
752 // files used by the LaTeX run. The files are then entered into the
755 string const logfile = onlyFilename(changeExtension(file, ".log"));
757 static regex reg1(".*\\([^)]+.*");
758 static regex reg2("File: ([^ ]+).*");
759 static regex reg3("No file ([^ ]+)\\..*");
760 static regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
761 // If an index should be created, MikTex does not write a line like
762 // \openout# = 'sample.idx'.
763 // but instead only a line like this into the log:
764 // Writing index file sample.idx
765 static regex reg5("Writing index file ([^ ]+).*");
766 // If a toc should be created, MikTex does not write a line like
767 // \openout# = `sample.toc'.
768 // but only a line like this into the log:
770 // This line is also written by tetex.
771 // This line is not present if no toc should be created.
772 static regex miktexTocReg("\\\\tf@toc=\\\\write.*");
774 ifstream ifs(logfile.c_str());
776 // Ok, the scanning of files here is not sufficient.
777 // Sometimes files are named by "File: xxx" only
778 // So I think we should use some regexps to find files instead.
779 // "(\([^ ]+\)" should match the "(file " variant, note
780 // that we can have several of these on one line.
781 // "File: \([^ ]+\)" should match the "File: file" variant
785 // MikTeX sometimes inserts \0 in the log file. They can't be
786 // removed directly with the existing string utility
787 // functions, so convert them first to \r, and remove all
788 // \r's afterwards, since we need to remove them anyway.
789 token = subst(token, '\0', '\r');
790 token = subst(token, "\r", "");
796 if (regex_match(token, sub, reg1)) {
797 static regex reg1_1("\\(([^()]+)");
799 string::const_iterator first = token.begin();
800 string::const_iterator end = token.end();
802 while (regex_search(first, end, what, reg1_1)) {
803 first = what[0].second;
804 handleFoundFile(what.str(1), head);
806 } else if (regex_match(token, sub, reg2))
807 handleFoundFile(sub.str(1), head);
808 else if (regex_match(token, sub, reg3))
809 handleFoundFile(sub.str(1), head);
810 else if (regex_match(token, sub, reg4))
811 handleFoundFile(sub.str(1), head);
812 else if (regex_match(token, sub, reg5))
813 handleFoundFile(sub.str(1), head);
814 else if (regex_match(token, sub, miktexTocReg))
815 handleFoundFile(changeExtension(file, ".toc"), head);
818 // Make sure that the main .tex file is in the dependancy file.
819 head.insert(onlyFilename(file), true);