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"
21 #include "support/filetools.h"
22 #include "support/FileInfo.h"
23 #include "support/tostr.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>
33 #include <cstdio> // sscanf
35 using namespace lyx::support;
37 #ifndef CXX_GLOBAL_CSTD
47 using boost::regex_match;
49 #ifndef USE_INCLUDED_STRING
55 // TODO: in no particular order
56 // - get rid of the extern BufferList and the call to
57 // BufferList::updateIncludedTeXfiles, this should either
58 // be done before calling LaTeX::funcs or in a completely
60 // - the bibtex command options should be supported.
61 // - the makeindex style files should be taken care of with
62 // the dependency mechanism.
63 // - makeindex commandline options should be supported
64 // - somewhere support viewing of bibtex and makeindex log files.
65 // - we should perhaps also scan the bibtex log file
66 // - we should perhaps also scan the bibtex log file
68 extern BufferList bufferlist;
72 string runMessage(unsigned int count)
74 return bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
83 void TeXErrors::insertError(int line, string const & error_desc,
84 string const & error_text)
86 Error newerr(line, error_desc, error_text);
87 errors.push_back(newerr);
91 bool operator==(Aux_Info const & a, Aux_Info const & o)
93 return a.aux_file == o.aux_file &&
94 a.citations == o.citations &&
95 a.databases == o.databases &&
100 bool operator!=(Aux_Info const & a, Aux_Info const & o)
110 LaTeX::LaTeX(string const & latex, LatexRunParams const & rp,
111 string const & f, string const & p)
112 : cmd(latex), file(f), path(p), runparams(rp)
115 depfile = file + ".dep";
116 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
118 output_file = ChangeExtension(file,".pdf");
120 output_file = ChangeExtension(file,".dvi");
125 void LaTeX::deleteFilesOnError() const
127 // currently just a dummy function.
129 // What files do we have to delete?
131 // This will at least make latex do all the runs
134 // but the reason for the error might be in a generated file...
136 string const ofname = OnlyFilename(file);
139 string const bbl = ChangeExtension(ofname, ".bbl");
143 string const ind = ChangeExtension(ofname, ".ind");
146 // Also remove the aux file
147 string const aux = ChangeExtension(ofname, ".aux");
152 int LaTeX::run(TeXErrors & terr)
153 // We know that this function will only be run if the lyx buffer
154 // has been changed. We also know that a newly written .tex file
155 // is always different from the previous one because of the date
156 // in it. However it seems safe to run latex (at least) on time each
157 // time the .tex file changes.
159 int scanres = NO_ERRORS;
160 unsigned int count = 0; // number of times run
161 num_errors = 0; // just to make sure.
162 unsigned int const MAX_RUN = 6;
163 DepTable head; // empty head
164 bool rerun = false; // rerun requested
166 // The class LaTeX does not know the temp path.
167 bufferlist.updateIncludedTeXfiles(getcwd(), runparams);
169 // Never write the depfile if an error was encountered.
172 // first check if the file dependencies exist:
173 // ->If it does exist
174 // check if any of the files mentioned in it have
175 // changed (done using a checksum).
177 // run latex once and
178 // remake the dependency file
179 // -> if not changed:
180 // just return there is nothing to do for us.
181 // ->if it doesn't exist
183 // run latex once (we need to run latex once anyway) and
184 // remake the dependency file.
187 FileInfo fi(depfile);
188 bool had_depfile = fi.exist();
189 bool run_bibtex = false;
190 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
193 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
194 // Read the dep file:
195 had_depfile = head.read(depfile);
199 // Update the checksums
201 // Can't just check if anything has changed because it might have aborted
202 // on error last time... in which cas we need to re-run latex
203 // and collect the error messages (even if they are the same).
204 if (!FileInfo(output_file).exist()) {
205 lyxerr[Debug::DEPEND]
206 << "re-running LaTeX because output file doesn't exist." << endl;
207 } else if (!head.sumchange()) {
208 lyxerr[Debug::DEPEND] << "return no_change" << endl;
211 lyxerr[Debug::DEPEND]
212 << "Dependency file has changed" << endl;
215 if (head.extchanged(".bib") || head.extchanged(".bst"))
218 lyxerr[Debug::DEPEND]
219 << "Dependency file does not exist, or has wrong format" << endl;
221 /// We scan the aux file even when had_depfile = false,
222 /// because we can run pdflatex on the file after running latex on it,
223 /// in which case we will not need to run bibtex again.
224 vector<Aux_Info> bibtex_info_old;
226 bibtex_info_old = scanAuxFiles(aux_file);
229 lyxerr[Debug::LATEX] << "Run #" << count << endl;
230 message(runMessage(count));
233 scanres = scanLogFile(terr);
234 if (scanres & ERROR_RERUN) {
235 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
237 scanres = scanLogFile(terr);
240 if (scanres & ERRORS) {
241 deleteFilesOnError();
242 return scanres; // return on error
245 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
246 if (!run_bibtex && bibtex_info_old != bibtex_info)
249 // update the dependencies.
250 deplog(head); // reads the latex log
254 // At this point we must run external programs if needed.
255 // makeindex will be run if a .idx file changed or was generated.
256 // And if there were undefined citations or changes in references
257 // the .aux file is checked for signs of bibtex. Bibtex is then run
261 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
263 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
264 message(_("Running MakeIndex."));
265 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
269 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
270 if (scanres & UNDEF_CIT || run_bibtex) {
271 // Here we must scan the .aux file and look for
272 // "\bibdata" and/or "\bibstyle". If one of those
273 // tags is found -> run bibtex and set rerun = true;
275 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
276 message(_("Running BibTeX."));
277 updateBibtexDependencies(head, bibtex_info);
278 rerun |= runBibTeX(bibtex_info);
279 } else if (!had_depfile) {
280 /// If we run pdflatex on the file after running latex on it,
281 /// then we do not need to run bibtex, but we do need to
282 /// insert the .bib and .bst files into the .dep-pdf file.
283 updateBibtexDependencies(head, bibtex_info);
287 // we know on this point that latex has been run once (or we just
288 // returned) and the question now is to decide if we need to run
289 // it any more. This is done by asking if any of the files in the
290 // dependency file has changed. (remember that the checksum for
291 // a given file is reported to have changed if it just was created)
292 // -> if changed or rerun == true:
293 // run latex once more and
294 // update the dependency structure
295 // -> if not changed:
296 // we does nothing at this point
298 if (rerun || head.sumchange()) {
301 lyxerr[Debug::DEPEND]
302 << "Dep. file has changed or rerun requested" << endl;
304 << "Run #" << count << endl;
305 message(runMessage(count));
307 scanres = scanLogFile(terr);
308 if (scanres & ERRORS) {
309 deleteFilesOnError();
310 return scanres; // return on error
313 // update the depedencies
314 deplog(head); // reads the latex log
317 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
321 // The inclusion of files generated by external programs like
322 // makeindex or bibtex might have done changes to pagenumbereing,
323 // etc. And because of this we must run the external programs
324 // again to make sure everything is redone correctly.
325 // Also there should be no need to run the external programs any
328 // run makeindex if the <file>.idx has changed or was generated.
329 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
331 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
332 message(_("Running MakeIndex."));
333 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
337 // we will only run latex more if the log file asks for it.
338 // or if the sumchange() is true.
339 // -> rerun asked for:
341 // remake the dependency file
342 // goto 2 or return if max runs are reached.
343 // -> rerun not asked for:
344 // just return (fall out of bottom of func)
346 while ((head.sumchange() || rerun || (scanres & RERUN))
347 && count < MAX_RUN) {
348 // Yes rerun until message goes away, or until
349 // MAX_RUNS are reached.
352 lyxerr[Debug::LATEX] << "Run #" << count << endl;
353 message(runMessage(count));
355 scanres = scanLogFile(terr);
356 if (scanres & ERRORS) {
357 deleteFilesOnError();
358 return scanres; // return on error
365 // Write the dependencies to file.
367 lyxerr[Debug::LATEX] << "Done." << endl;
372 int LaTeX::startscript()
375 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
376 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
377 string tmp = cmd + ' ' + file + " > nul";
380 return one.startscript(Systemcall::Wait, tmp);
384 bool LaTeX::runMakeIndex(string const & f)
386 lyxerr[Debug::LATEX] << "idx file has been made,"
387 " running makeindex on file "
390 // It should be possible to set the switches for makeindex
391 // sorting style and such. It would also be very convenient
392 // to be able to make style files from within LyX. This has
393 // to come for a later time.
394 string tmp = "makeindex -c -q ";
397 one.startscript(Systemcall::Wait, tmp);
402 vector<Aux_Info> const
403 LaTeX::scanAuxFiles(string const & file)
405 vector<Aux_Info> result;
407 result.push_back(scanAuxFile(file));
409 for (int i = 1; i < 1000; ++i) {
410 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
415 result.push_back(scanAuxFile(file2));
421 Aux_Info const LaTeX::scanAuxFile(string const & file)
424 result.aux_file = file;
425 scanAuxFile(file, result);
430 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
432 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
434 ifstream ifs(file.c_str());
436 regex reg1("\\\\citation\\{([^}]+)\\}");
437 regex reg2("\\\\bibdata\\{([^}]+)\\}");
438 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
439 regex reg4("\\\\@input\\{([^}]+)\\}");
441 while (getline(ifs, token)) {
442 token = rtrim(token, "\r");
443 #ifndef USE_INCLUDED_STRING
448 if (regex_match(STRCONV(token), sub, reg1)) {
449 string data = STRCONV(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(STRCONV(token), sub, reg2)) {
458 string data = sub.STRCONV(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(STRCONV(token), sub, reg3)) {
470 string style = STRCONV(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(STRCONV(token), sub, reg4)) {
478 string const file2 = STRCONV(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 = "bibtex ";
523 tmp += 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 // Here shall we handle different
551 retval |= LATEX_WARNING;
552 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
553 if (contains(token, "Rerun to get cross-references")) {
556 << "We should rerun." << endl;
557 } else if (contains(token, "Citation")
558 && contains(token, "on page")
559 && contains(token, "undefined")) {
562 } else if (prefixIs(token, "Package")) {
564 retval |= PACKAGE_WARNING;
565 if (contains(token, "natbib Warning:")) {
567 if (contains(token, "Citation")
568 && contains(token, "on page")
569 && contains(token, "undefined")) {
572 } else if (contains(token, "run BibTeX")) {
574 } else if (contains(token, "Rerun LaTeX") ||
575 contains(token, "Rerun to get")) {
576 // at least longtable.sty and bibtopic.sty
579 << "We should rerun." << endl;
582 } else if (token[0] == '(') {
583 if (contains(token, "Rerun LaTeX") ||
584 contains(token, "Rerun to get")) {
587 << "We should rerun." << endl;
590 } else if (prefixIs(token, "! ")) {
591 // Ok, we have something that looks like a TeX Error
592 // but what do we really have.
594 // Just get the error description:
595 string desc(token, 2);
596 if (contains(token, "LaTeX Error:"))
597 retval |= LATEX_ERROR;
602 if (!getline(ifs, tmp))
606 } while (!prefixIs(tmp, "l."));
607 if (prefixIs(tmp, "l.")) {
608 // we have a latex error
610 if (contains(desc, "Package babel Error: You haven't defined the language"))
611 retval |= ERROR_RERUN;
612 // get the line number:
614 sscanf(tmp.c_str(), "l.%d", &line);
615 // get the rest of the message:
616 string errstr(tmp, tmp.find(' '));
619 while (!contains(errstr, "l.")
621 && !prefixIs(tmp, "! ")
622 && !contains(tmp, "(job aborted")) {
628 << "line: " << line << '\n'
629 << "Desc: " << desc << '\n'
630 << "Text: " << errstr << endl;
631 if (line == last_line)
637 if (line_count <= 5) {
638 terr.insertError(line, desc, errstr);
643 // information messages, TeX warnings and other
644 // warnings we have not caught earlier.
645 if (prefixIs(token, "Overfull ")) {
646 retval |= TEX_WARNING;
647 } else if (prefixIs(token, "Underfull ")) {
648 retval |= TEX_WARNING;
649 } else if (contains(token, "Rerun to get citations")) {
650 // Natbib seems to use this.
652 } else if (contains(token, "No pages of output")) {
653 // A dvi file was not created
655 } else if (contains(token, "That makes 100 errors")) {
656 // More than 100 errors were reprted
657 retval |= TOO_MANY_ERRORS;
661 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
666 void LaTeX::deplog(DepTable & head)
668 // This function reads the LaTeX log file end extracts all the external
669 // files used by the LaTeX run. The files are then entered into the
672 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
674 regex reg1("\\)* *\\(([^ )]+).*");
675 regex reg2("File: ([^ ]+).*");
676 regex reg3("No file ([^ ]+)\\..*");
677 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
678 // If an index should be created, MikTex does not write a line like
679 // \openout# = 'sample,idx'.
680 // but intstead only a line like this into the log:
681 // Writing index file sample.idx
682 regex reg5("Writing index file ([^ ]+).*");
683 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
685 ifstream ifs(logfile.c_str());
687 // Ok, the scanning of files here is not sufficient.
688 // Sometimes files are named by "File: xxx" only
689 // So I think we should use some regexps to find files instead.
690 // "(\([^ ]+\)" should match the "(file " variant
691 // "File: \([^ ]+\)" should match the "File: file" variant
695 token = rtrim(token, "\r");
696 if (token.empty()) continue;
698 #ifndef USE_INCLUDED_STRING
703 if (regex_match(STRCONV(token), sub, reg1)) {
704 foundfile = STRCONV(sub.str(1));
705 } else if (regex_match(STRCONV(token), sub, reg2)) {
706 foundfile = STRCONV(sub.str(1));
707 } else if (regex_match(STRCONV(token), sub, reg3)) {
708 foundfile = STRCONV(sub.str(1));
709 } else if (regex_match(STRCONV(token), sub, reg4)) {
710 foundfile = STRCONV(sub.str(1));
711 } else if (regex_match(STRCONV(token), sub, reg5)) {
712 foundfile = STRCONV(sub.str(1));
717 // convert from native os path to unix path
718 foundfile = os::internal_path(foundfile);
720 lyxerr[Debug::DEPEND] << "Found file: "
721 << foundfile << endl;
723 // Ok now we found a file.
724 // Now we should make sure that this is a file that we can
725 // access through the normal paths.
726 // We will not try any fancy search methods to
729 // (1) foundfile is an
730 // absolute path and should
732 if (AbsolutePath(foundfile)) {
733 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
734 << foundfile << endl;
735 // On initial insert we want to do the update at once
736 // since this file can not be a file generated by
738 if (FileInfo(foundfile).exist())
739 head.insert(foundfile, true);
742 // (2) foundfile is in the tmpdir
743 // insert it into head
744 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
745 if (regex_match(STRCONV(foundfile), unwanted)) {
746 lyxerr[Debug::DEPEND]
748 << OnlyFilename(foundfile)
749 << " in the dep file"
751 } else if (suffixIs(foundfile, ".tex")) {
752 // This is a tex file generated by LyX
753 // and latex is not likely to change this
755 lyxerr[Debug::DEPEND]
756 << "Tmpdir TeX file: "
757 << OnlyFilename(foundfile)
759 head.insert(foundfile, true);
761 lyxerr[Debug::DEPEND]
763 << OnlyFilename(foundfile)
765 head.insert(OnlyFilename(foundfile));
768 lyxerr[Debug::DEPEND]
769 << "Not a file or we are unable to find it."
773 // Make sure that the main .tex file is in the dependancy file.
774 head.insert(OnlyFilename(file), true);