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/convert.h"
25 #include "support/lstrings.h"
26 #include "support/lyxlib.h"
27 #include "support/systemcall.h"
28 #include "support/os.h"
30 #include <boost/filesystem/operations.hpp>
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::findtexfile;
40 using lyx::support::getcwd;
41 using lyx::support::onlyFilename;
42 using lyx::support::prefixIs;
43 using lyx::support::quoteName;
44 using lyx::support::rtrim;
45 using lyx::support::split;
46 using lyx::support::subst;
47 using lyx::support::suffixIs;
48 using lyx::support::Systemcall;
49 using lyx::support::unlink;
50 using lyx::support::trim;
52 namespace os = lyx::support::os;
53 namespace fs = boost::filesystem;
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$d"), 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 bool had_depfile = fs::exists(depfile);
201 bool run_bibtex = false;
202 string aux_file = onlyFilename(changeExtension(file, "aux"));
205 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
206 // Read the dep file:
207 had_depfile = head.read(depfile);
211 // Update the checksums
213 // Can't just check if anything has changed because it might have aborted
214 // on error last time... in which cas we need to re-run latex
215 // and collect the error messages (even if they are the same).
216 if (!fs::exists(output_file)) {
217 lyxerr[Debug::DEPEND]
218 << "re-running LaTeX because output file doesn't exist." << endl;
219 } else if (!head.sumchange()) {
220 lyxerr[Debug::DEPEND] << "return no_change" << endl;
223 lyxerr[Debug::DEPEND]
224 << "Dependency file has changed" << endl;
227 if (head.extchanged(".bib") || head.extchanged(".bst"))
230 lyxerr[Debug::DEPEND]
231 << "Dependency file does not exist, or has wrong format" << endl;
233 /// We scan the aux file even when had_depfile = false,
234 /// because we can run pdflatex on the file after running latex on it,
235 /// in which case we will not need to run bibtex again.
236 vector<Aux_Info> bibtex_info_old;
238 bibtex_info_old = scanAuxFiles(aux_file);
241 lyxerr[Debug::LATEX] << "Run #" << count << endl;
242 message(runMessage(count));
245 scanres = scanLogFile(terr);
246 if (scanres & ERROR_RERUN) {
247 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
249 scanres = scanLogFile(terr);
252 if (scanres & ERRORS) {
253 deleteFilesOnError();
254 return scanres; // return on error
257 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
258 if (!run_bibtex && bibtex_info_old != bibtex_info)
261 // update the dependencies.
262 deplog(head); // reads the latex log
266 // At this point we must run external programs if needed.
267 // makeindex will be run if a .idx file changed or was generated.
268 // And if there were undefined citations or changes in references
269 // the .aux file is checked for signs of bibtex. Bibtex is then run
273 if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
275 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
276 message(_("Running MakeIndex."));
277 rerun = runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
281 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
282 if (scanres & UNDEF_CIT || run_bibtex) {
283 // Here we must scan the .aux file and look for
284 // "\bibdata" and/or "\bibstyle". If one of those
285 // tags is found -> run bibtex and set rerun = true;
287 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
288 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;
317 message(runMessage(count));
319 scanres = scanLogFile(terr);
320 if (scanres & ERRORS) {
321 deleteFilesOnError();
322 return scanres; // return on error
325 // update the depedencies
326 deplog(head); // reads the latex log
329 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
333 // The inclusion of files generated by external programs like
334 // makeindex or bibtex might have done changes to pagenumbereing,
335 // etc. And because of this we must run the external programs
336 // again to make sure everything is redone correctly.
337 // Also there should be no need to run the external programs any
340 // run makeindex if the <file>.idx has changed or was generated.
341 if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
343 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
344 message(_("Running MakeIndex."));
345 rerun = runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
349 // we will only run latex more if the log file asks for it.
350 // or if the sumchange() is true.
351 // -> rerun asked for:
353 // remake the dependency file
354 // goto 2 or return if max runs are reached.
355 // -> rerun not asked for:
356 // just return (fall out of bottom of func)
358 while ((head.sumchange() || rerun || (scanres & RERUN))
359 && count < MAX_RUN) {
360 // Yes rerun until message goes away, or until
361 // MAX_RUNS are reached.
364 lyxerr[Debug::LATEX] << "Run #" << count << endl;
365 message(runMessage(count));
367 scanres = scanLogFile(terr);
368 if (scanres & ERRORS) {
369 deleteFilesOnError();
370 return scanres; // return on error
377 // Write the dependencies to file.
379 lyxerr[Debug::LATEX] << "Done." << endl;
384 int LaTeX::startscript()
386 string tmp = cmd + ' ' + quoteName(file) + " > " + os::nulldev();
388 return one.startscript(Systemcall::Wait, tmp);
392 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams)
394 lyxerr[Debug::LATEX] << "idx file has been made,"
395 " running makeindex on file "
397 string tmp = lyxrc.index_command + " ";
398 tmp = subst(tmp, "$$lang", runparams.document_language);
401 one.startscript(Systemcall::Wait, tmp);
406 vector<Aux_Info> const
407 LaTeX::scanAuxFiles(string const & file)
409 vector<Aux_Info> result;
411 result.push_back(scanAuxFile(file));
413 for (int i = 1; i < 1000; ++i) {
414 string const file2 = changeExtension(file, "")
415 + '.' + convert<string>(i)
417 if (!fs::exists(file2))
419 result.push_back(scanAuxFile(file2));
425 Aux_Info const LaTeX::scanAuxFile(string const & file)
428 result.aux_file = file;
429 scanAuxFile(file, result);
434 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
436 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
438 ifstream ifs(file.c_str());
440 static regex const reg1("\\\\citation\\{([^}]+)\\}");
441 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
442 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
443 static regex const reg4("\\\\@input\\{([^}]+)\\}");
445 while (getline(ifs, token)) {
446 token = rtrim(token, "\r");
448 if (regex_match(token, sub, reg1)) {
449 string data = sub.str(1);
450 while (!data.empty()) {
452 data = split(data, citation, ',');
453 lyxerr[Debug::LATEX] << "Citation: "
455 aux_info.citations.insert(citation);
457 } else if (regex_match(token, sub, reg2)) {
458 string data = sub.str(1);
459 // data is now all the bib files separated by ','
460 // get them one by one and pass them to the helper
461 while (!data.empty()) {
463 data = split(data, database, ',');
464 database = changeExtension(database, "bib");
465 lyxerr[Debug::LATEX] << "BibTeX database: `"
466 << database << '\'' << endl;
467 aux_info.databases.insert(database);
469 } else if (regex_match(token, sub, reg3)) {
470 string style = sub.str(1);
471 // token is now the style file
472 // pass it to the helper
473 style = changeExtension(style, "bst");
474 lyxerr[Debug::LATEX] << "BibTeX style: `"
475 << style << '\'' << endl;
476 aux_info.styles.insert(style);
477 } else if (regex_match(token, sub, reg4)) {
478 string const file2 = sub.str(1);
479 scanAuxFile(file2, aux_info);
485 void LaTeX::updateBibtexDependencies(DepTable & dep,
486 vector<Aux_Info> const & bibtex_info)
488 // Since a run of Bibtex mandates more latex runs it is ok to
489 // remove all ".bib" and ".bst" files.
490 dep.remove_files_with_extension(".bib");
491 dep.remove_files_with_extension(".bst");
492 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
494 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
495 it != bibtex_info.end(); ++it) {
496 for (set<string>::const_iterator it2 = it->databases.begin();
497 it2 != it->databases.end(); ++it2) {
498 string file = findtexfile(*it2, "bib");
500 dep.insert(file, true);
503 for (set<string>::const_iterator it2 = it->styles.begin();
504 it2 != it->styles.end(); ++it2) {
505 string file = findtexfile(*it2, "bst");
507 dep.insert(file, true);
513 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
516 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
517 it != bibtex_info.end(); ++it) {
518 if (it->databases.empty())
522 string tmp = lyxrc.bibtex_command + " ";
523 tmp += quoteName(onlyFilename(changeExtension(it->aux_file, string())));
525 one.startscript(Systemcall::Wait, tmp);
527 // Return whether bibtex was run
532 int LaTeX::scanLogFile(TeXErrors & terr)
536 int retval = NO_ERRORS;
537 string tmp = onlyFilename(changeExtension(file, ".log"));
538 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
539 ifstream ifs(tmp.c_str());
542 while (getline(ifs, token)) {
543 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
548 if (prefixIs(token, "LaTeX Warning:") ||
549 prefixIs(token, "! pdfTeX warning")) {
550 // Here shall we handle different
552 retval |= LATEX_WARNING;
553 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
554 if (contains(token, "Rerun to get cross-references")) {
557 << "We should rerun." << endl;
558 } else if (contains(token, "Citation")
559 && contains(token, "on page")
560 && contains(token, "undefined")) {
563 } else if (prefixIs(token, "Package")) {
565 retval |= PACKAGE_WARNING;
566 if (contains(token, "natbib Warning:")) {
568 if (contains(token, "Citation")
569 && contains(token, "on page")
570 && contains(token, "undefined")) {
573 } else if (contains(token, "run BibTeX")) {
575 } else if (contains(token, "Rerun LaTeX") ||
576 contains(token, "Rerun to get")) {
577 // at least longtable.sty and bibtopic.sty
580 << "We should rerun." << endl;
583 } else if (token[0] == '(') {
584 if (contains(token, "Rerun LaTeX") ||
585 contains(token, "Rerun to get")) {
588 << "We should rerun." << endl;
591 } else if (prefixIs(token, "! ")) {
592 // Ok, we have something that looks like a TeX Error
593 // but what do we really have.
595 // Just get the error description:
596 string desc(token, 2);
597 if (contains(token, "LaTeX Error:"))
598 retval |= LATEX_ERROR;
603 if (!getline(ifs, tmp))
607 } while (!prefixIs(tmp, "l."));
608 if (prefixIs(tmp, "l.")) {
609 // we have a latex error
611 if (contains(desc, "Package babel Error: You haven't defined the language"))
612 retval |= ERROR_RERUN;
613 // get the line number:
615 sscanf(tmp.c_str(), "l.%d", &line);
616 // get the rest of the message:
617 string errstr(tmp, tmp.find(' '));
620 while (!contains(errstr, "l.")
622 && !prefixIs(tmp, "! ")
623 && !contains(tmp, "(job aborted")) {
629 << "line: " << line << '\n'
630 << "Desc: " << desc << '\n'
631 << "Text: " << errstr << endl;
632 if (line == last_line)
638 if (line_count <= 5) {
639 terr.insertError(line, desc, errstr);
644 // information messages, TeX warnings and other
645 // warnings we have not caught earlier.
646 if (prefixIs(token, "Overfull ")) {
647 retval |= TEX_WARNING;
648 } else if (prefixIs(token, "Underfull ")) {
649 retval |= TEX_WARNING;
650 } else if (contains(token, "Rerun to get citations")) {
651 // Natbib seems to use this.
653 } else if (contains(token, "No pages of output")) {
654 // A dvi file was not created
656 } else if (contains(token, "That makes 100 errors")) {
657 // More than 100 errors were reprted
658 retval |= TOO_MANY_ERRORS;
662 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
669 void handleFoundFile(string const & ff, DepTable & head)
671 // convert from native os path to unix path
672 string const foundfile = os::internal_path(trim(ff));
674 lyxerr[Debug::DEPEND] << "Found file: " << foundfile << endl;
676 // Ok now we found a file.
677 // Now we should make sure that this is a file that we can
678 // access through the normal paths.
679 // We will not try any fancy search methods to
682 // (1) foundfile is an
683 // absolute path and should
685 if (absolutePath(foundfile)) {
686 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
687 << foundfile << endl;
688 // On initial insert we want to do the update at once
689 // since this file can not be a file generated by
691 if (fs::exists(foundfile) && !fs::is_directory(foundfile))
692 head.insert(foundfile, true);
697 string const onlyfile = onlyFilename(foundfile);
699 // (2) foundfile is in the tmpdir
700 // insert it into head
701 if (fs::exists(onlyfile)) {
702 static regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
703 if (regex_match(onlyfile, unwanted)) {
704 lyxerr[Debug::DEPEND]
707 << " in the dep file"
709 } else if (suffixIs(onlyfile, ".tex")) {
710 // This is a tex file generated by LyX
711 // and latex is not likely to change this
713 lyxerr[Debug::DEPEND]
714 << "Tmpdir TeX file: "
717 head.insert(onlyfile, true);
719 lyxerr[Debug::DEPEND]
723 head.insert(onlyfile);
726 lyxerr[Debug::DEPEND]
727 << "Not a file or we are unable to find it."
734 void LaTeX::deplog(DepTable & head)
736 // This function reads the LaTeX log file end extracts all the external
737 // files used by the LaTeX run. The files are then entered into the
740 string const logfile = onlyFilename(changeExtension(file, ".log"));
742 static regex reg1(".*\\([^)]+.*");
743 static regex reg2("File: ([^ ]+).*");
744 static regex reg3("No file ([^ ]+)\\..*");
745 static regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
746 // If an index should be created, MikTex does not write a line like
747 // \openout# = 'sample,idx'.
748 // but intstead only a line like this into the log:
749 // Writing index file sample.idx
750 static regex reg5("Writing index file ([^ ]+).*");
752 ifstream ifs(logfile.c_str());
754 // Ok, the scanning of files here is not sufficient.
755 // Sometimes files are named by "File: xxx" only
756 // So I think we should use some regexps to find files instead.
757 // "(\([^ ]+\)" should match the "(file " variant, note
758 // that we can have several of these on one line.
759 // "File: \([^ ]+\)" should match the "File: file" variant
763 token = rtrim(token, "\r");
769 if (regex_match(token, sub, reg1)) {
770 static regex reg1_1("\\(([^()]+)");
772 string::const_iterator first = token.begin();
773 string::const_iterator end = token.end();
775 while (regex_search(first, end, what, reg1_1)) {
776 first = what[0].second;
777 handleFoundFile(what.str(1), head);
779 } else if (regex_match(token, sub, reg2)) {
780 handleFoundFile(sub.str(1), head);
781 } else if (regex_match(token, sub, reg3)) {
782 handleFoundFile(sub.str(1), head);
783 } else if (regex_match(token, sub, reg4)) {
784 handleFoundFile(sub.str(1), head);
785 } else if (regex_match(token, sub, reg5)) {
786 handleFoundFile(sub.str(1), head);
790 // Make sure that the main .tex file is in the dependancy file.
791 head.insert(onlyFilename(file), true);