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"
22 #include "support/filetools.h"
23 #include "support/FileInfo.h"
24 #include "support/tostr.h"
25 #include "support/lstrings.h"
26 #include "support/lyxlib.h"
27 #include "support/systemcall.h"
28 #include "support/os.h"
30 #include <boost/regex.hpp>
34 using namespace lyx::support;
36 #ifndef CXX_GLOBAL_CSTD
46 using boost::regex_match;
48 #ifndef USE_INCLUDED_STRING
54 // TODO: in no particular order
55 // - get rid of the extern BufferList and the call to
56 // BufferList::updateIncludedTeXfiles, this should either
57 // be done before calling LaTeX::funcs or in a completely
59 // - the bibtex command options should be supported.
60 // - the makeindex style files should be taken care of with
61 // the dependency mechanism.
62 // - makeindex commandline options should be supported
63 // - somewhere support viewing of bibtex and makeindex log files.
64 // - we should perhaps also scan the bibtex log file
65 // - we should perhaps also scan the bibtex log file
67 extern BufferList bufferlist;
71 string runMessage(unsigned int count)
73 return bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
82 void TeXErrors::insertError(int line, string const & error_desc,
83 string const & error_text)
85 Error newerr(line, error_desc, error_text);
86 errors.push_back(newerr);
90 bool operator==(Aux_Info const & a, Aux_Info const & o)
92 return a.aux_file == o.aux_file &&
93 a.citations == o.citations &&
94 a.databases == o.databases &&
99 bool operator!=(Aux_Info const & a, Aux_Info const & o)
109 LaTeX::LaTeX(string const & latex, LatexRunParams const & rp,
110 string const & f, string const & p)
111 : cmd(latex), file(f), path(p), runparams(rp)
114 depfile = file + ".dep";
115 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
117 output_file = ChangeExtension(file,".pdf");
119 output_file = ChangeExtension(file,".dvi");
124 void LaTeX::deleteFilesOnError() const
126 // currently just a dummy function.
128 // What files do we have to delete?
130 // This will at least make latex do all the runs
133 // but the reason for the error might be in a generated file...
135 string const ofname = OnlyFilename(file);
138 string const bbl = ChangeExtension(ofname, ".bbl");
142 string const ind = ChangeExtension(ofname, ".ind");
145 // Also remove the aux file
146 string const aux = ChangeExtension(ofname, ".aux");
151 int LaTeX::run(TeXErrors & terr)
152 // We know that this function will only be run if the lyx buffer
153 // has been changed. We also know that a newly written .tex file
154 // is always different from the previous one because of the date
155 // in it. However it seems safe to run latex (at least) on time each
156 // time the .tex file changes.
158 int scanres = NO_ERRORS;
159 unsigned int count = 0; // number of times run
160 num_errors = 0; // just to make sure.
161 unsigned int const MAX_RUN = 6;
162 DepTable head; // empty head
163 bool rerun = false; // rerun requested
165 // The class LaTeX does not know the temp path.
166 bufferlist.updateIncludedTeXfiles(getcwd(), runparams);
168 // Never write the depfile if an error was encountered.
171 // first check if the file dependencies exist:
172 // ->If it does exist
173 // check if any of the files mentioned in it have
174 // changed (done using a checksum).
176 // run latex once and
177 // remake the dependency file
178 // -> if not changed:
179 // just return there is nothing to do for us.
180 // ->if it doesn't exist
182 // run latex once (we need to run latex once anyway) and
183 // remake the dependency file.
186 FileInfo fi(depfile);
187 bool had_depfile = fi.exist();
188 bool run_bibtex = false;
189 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
192 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
193 // Read the dep file:
194 had_depfile = head.read(depfile);
198 // Update the checksums
200 // Can't just check if anything has changed because it might have aborted
201 // on error last time... in which cas we need to re-run latex
202 // and collect the error messages (even if they are the same).
203 if (!FileInfo(output_file).exist()) {
204 lyxerr[Debug::DEPEND]
205 << "re-running LaTeX because output file doesn't exist." << endl;
206 } else if (!head.sumchange()) {
207 lyxerr[Debug::DEPEND] << "return no_change" << endl;
210 lyxerr[Debug::DEPEND]
211 << "Dependency file has changed" << endl;
214 if (head.extchanged(".bib") || head.extchanged(".bst"))
217 lyxerr[Debug::DEPEND]
218 << "Dependency file does not exist, or has wrong format" << endl;
220 /// We scan the aux file even when had_depfile = false,
221 /// because we can run pdflatex on the file after running latex on it,
222 /// in which case we will not need to run bibtex again.
223 vector<Aux_Info> bibtex_info_old;
225 bibtex_info_old = scanAuxFiles(aux_file);
228 lyxerr[Debug::LATEX] << "Run #" << count << endl;
229 message(runMessage(count));
232 scanres = scanLogFile(terr);
233 if (scanres & ERROR_RERUN) {
234 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
236 scanres = scanLogFile(terr);
239 if (scanres & ERRORS) {
240 deleteFilesOnError();
241 return scanres; // return on error
244 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
245 if (!run_bibtex && bibtex_info_old != bibtex_info)
248 // update the dependencies.
249 deplog(head); // reads the latex log
253 // At this point we must run external programs if needed.
254 // makeindex will be run if a .idx file changed or was generated.
255 // And if there were undefined citations or changes in references
256 // the .aux file is checked for signs of bibtex. Bibtex is then run
260 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
262 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
263 message(_("Running MakeIndex."));
264 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
268 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
269 if (scanres & UNDEF_CIT || run_bibtex) {
270 // Here we must scan the .aux file and look for
271 // "\bibdata" and/or "\bibstyle". If one of those
272 // tags is found -> run bibtex and set rerun = true;
274 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
275 message(_("Running BibTeX."));
276 updateBibtexDependencies(head, bibtex_info);
277 rerun |= runBibTeX(bibtex_info);
278 } else if (!had_depfile) {
279 /// If we run pdflatex on the file after running latex on it,
280 /// then we do not need to run bibtex, but we do need to
281 /// insert the .bib and .bst files into the .dep-pdf file.
282 updateBibtexDependencies(head, bibtex_info);
286 // we know on this point that latex has been run once (or we just
287 // returned) and the question now is to decide if we need to run
288 // it any more. This is done by asking if any of the files in the
289 // dependency file has changed. (remember that the checksum for
290 // a given file is reported to have changed if it just was created)
291 // -> if changed or rerun == true:
292 // run latex once more and
293 // update the dependency structure
294 // -> if not changed:
295 // we does nothing at this point
297 if (rerun || head.sumchange()) {
300 lyxerr[Debug::DEPEND]
301 << "Dep. file has changed or rerun requested" << endl;
303 << "Run #" << count << endl;
304 message(runMessage(count));
306 scanres = scanLogFile(terr);
307 if (scanres & ERRORS) {
308 deleteFilesOnError();
309 return scanres; // return on error
312 // update the depedencies
313 deplog(head); // reads the latex log
316 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
320 // The inclusion of files generated by external programs like
321 // makeindex or bibtex might have done changes to pagenumbereing,
322 // etc. And because of this we must run the external programs
323 // again to make sure everything is redone correctly.
324 // Also there should be no need to run the external programs any
327 // run makeindex if the <file>.idx has changed or was generated.
328 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
330 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
331 message(_("Running MakeIndex."));
332 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
336 // we will only run latex more if the log file asks for it.
337 // or if the sumchange() is true.
338 // -> rerun asked for:
340 // remake the dependency file
341 // goto 2 or return if max runs are reached.
342 // -> rerun not asked for:
343 // just return (fall out of bottom of func)
345 while ((head.sumchange() || rerun || (scanres & RERUN))
346 && count < MAX_RUN) {
347 // Yes rerun until message goes away, or until
348 // MAX_RUNS are reached.
351 lyxerr[Debug::LATEX] << "Run #" << count << endl;
352 message(runMessage(count));
354 scanres = scanLogFile(terr);
355 if (scanres & ERRORS) {
356 deleteFilesOnError();
357 return scanres; // return on error
364 // Write the dependencies to file.
366 lyxerr[Debug::LATEX] << "Done." << endl;
371 int LaTeX::startscript()
374 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
375 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
376 string tmp = cmd + ' ' + file + " > nul";
379 return one.startscript(Systemcall::Wait, tmp);
383 bool LaTeX::runMakeIndex(string const & f)
385 lyxerr[Debug::LATEX] << "idx file has been made,"
386 " running makeindex on file "
389 // It should be possible to set the switches for makeindex
390 // sorting style and such. It would also be very convenient
391 // to be able to make style files from within LyX. This has
392 // to come for a later time.
393 string tmp = "makeindex -c -q ";
396 one.startscript(Systemcall::Wait, tmp);
401 vector<Aux_Info> const
402 LaTeX::scanAuxFiles(string const & file)
404 vector<Aux_Info> result;
406 result.push_back(scanAuxFile(file));
408 for (int i = 1; i < 1000; ++i) {
409 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
414 result.push_back(scanAuxFile(file2));
420 Aux_Info const LaTeX::scanAuxFile(string const & file)
423 result.aux_file = file;
424 scanAuxFile(file, result);
429 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
431 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
433 ifstream ifs(file.c_str());
435 regex reg1("\\\\citation\\{([^}]+)\\}");
436 regex reg2("\\\\bibdata\\{([^}]+)\\}");
437 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
438 regex reg4("\\\\@input\\{([^}]+)\\}");
440 while (getline(ifs, token)) {
441 token = rtrim(token, "\r");
442 #ifndef USE_INCLUDED_STRING
447 if (regex_match(STRCONV(token), sub, reg1)) {
448 string data = STRCONV(sub.str(1));
449 while (!data.empty()) {
451 data = split(data, citation, ',');
452 lyxerr[Debug::LATEX] << "Citation: "
454 aux_info.citations.insert(citation);
456 } else if (regex_match(STRCONV(token), sub, reg2)) {
457 string data = sub.STRCONV(str(1));
458 // data is now all the bib files separated by ','
459 // get them one by one and pass them to the helper
460 while (!data.empty()) {
462 data = split(data, database, ',');
463 database = ChangeExtension(database, "bib");
464 lyxerr[Debug::LATEX] << "BibTeX database: `"
465 << database << '\'' << endl;
466 aux_info.databases.insert(database);
468 } else if (regex_match(STRCONV(token), sub, reg3)) {
469 string style = STRCONV(sub.str(1));
470 // token is now the style file
471 // pass it to the helper
472 style = ChangeExtension(style, "bst");
473 lyxerr[Debug::LATEX] << "BibTeX style: `"
474 << style << '\'' << endl;
475 aux_info.styles.insert(style);
476 } else if (regex_match(STRCONV(token), sub, reg4)) {
477 string const file2 = STRCONV(sub.str(1));
478 scanAuxFile(file2, aux_info);
484 void LaTeX::updateBibtexDependencies(DepTable & dep,
485 vector<Aux_Info> const & bibtex_info)
487 // Since a run of Bibtex mandates more latex runs it is ok to
488 // remove all ".bib" and ".bst" files.
489 dep.remove_files_with_extension(".bib");
490 dep.remove_files_with_extension(".bst");
491 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
493 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
494 it != bibtex_info.end(); ++it) {
495 for (set<string>::const_iterator it2 = it->databases.begin();
496 it2 != it->databases.end(); ++it2) {
497 string file = findtexfile(*it2, "bib");
499 dep.insert(file, true);
502 for (set<string>::const_iterator it2 = it->styles.begin();
503 it2 != it->styles.end(); ++it2) {
504 string file = findtexfile(*it2, "bst");
506 dep.insert(file, true);
512 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
515 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
516 it != bibtex_info.end(); ++it) {
517 if (it->databases.empty())
521 string tmp = "bibtex ";
522 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
524 one.startscript(Systemcall::Wait, tmp);
526 // Return whether bibtex was run
531 int LaTeX::scanLogFile(TeXErrors & terr)
535 int retval = NO_ERRORS;
536 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
537 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
538 ifstream ifs(tmp.c_str());
541 while (getline(ifs, token)) {
542 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
547 if (prefixIs(token, "LaTeX Warning:")) {
548 // Here shall we handle different
550 retval |= LATEX_WARNING;
551 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
552 if (contains(token, "Rerun to get cross-references")) {
555 << "We should rerun." << endl;
556 } else if (contains(token, "Citation")
557 && contains(token, "on page")
558 && contains(token, "undefined")) {
561 } else if (prefixIs(token, "Package")) {
563 retval |= PACKAGE_WARNING;
564 if (contains(token, "natbib Warning:")) {
566 if (contains(token, "Citation")
567 && contains(token, "on page")
568 && contains(token, "undefined")) {
571 } else if (contains(token, "run BibTeX")) {
573 } else if (contains(token, "Rerun LaTeX") ||
574 contains(token, "Rerun to get")) {
575 // at least longtable.sty and bibtopic.sty
578 << "We should rerun." << endl;
581 } else if (token[0] == '(') {
582 if (contains(token, "Rerun LaTeX") ||
583 contains(token, "Rerun to get")) {
586 << "We should rerun." << endl;
589 } else if (prefixIs(token, "! ")) {
590 // Ok, we have something that looks like a TeX Error
591 // but what do we really have.
593 // Just get the error description:
594 string desc(token, 2);
595 if (contains(token, "LaTeX Error:"))
596 retval |= LATEX_ERROR;
601 if (!getline(ifs, tmp))
605 } while (!prefixIs(tmp, "l."));
606 if (prefixIs(tmp, "l.")) {
607 // we have a latex error
609 if (contains(desc, "Package babel Error: You haven't defined the language"))
610 retval |= ERROR_RERUN;
611 // get the line number:
613 sscanf(tmp.c_str(), "l.%d", &line);
614 // get the rest of the message:
615 string errstr(tmp, tmp.find(' '));
618 while (!contains(errstr, "l.")
620 && !prefixIs(tmp, "! ")
621 && !contains(tmp, "(job aborted")) {
627 << "line: " << line << '\n'
628 << "Desc: " << desc << '\n'
629 << "Text: " << errstr << endl;
630 if (line == last_line)
636 if (line_count <= 5) {
637 terr.insertError(line, desc, errstr);
642 // information messages, TeX warnings and other
643 // warnings we have not caught earlier.
644 if (prefixIs(token, "Overfull ")) {
645 retval |= TEX_WARNING;
646 } else if (prefixIs(token, "Underfull ")) {
647 retval |= TEX_WARNING;
648 } else if (contains(token, "Rerun to get citations")) {
649 // Natbib seems to use this.
651 } else if (contains(token, "No pages of output")) {
652 // A dvi file was not created
654 } else if (contains(token, "That makes 100 errors")) {
655 // More than 100 errors were reprted
656 retval |= TOO_MANY_ERRORS;
660 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
665 void LaTeX::deplog(DepTable & head)
667 // This function reads the LaTeX log file end extracts all the external
668 // files used by the LaTeX run. The files are then entered into the
671 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
673 regex reg1("\\)* *\\(([^ )]+).*");
674 regex reg2("File: ([^ ]+).*");
675 regex reg3("No file ([^ ]+)\\..*");
676 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
677 // If an index should be created, MikTex does not write a line like
678 // \openout# = 'sample,idx'.
679 // but intstead only a line like this into the log:
680 // Writing index file sample.idx
681 regex reg5("Writing index file ([^ ]+).*");
682 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
684 ifstream ifs(logfile.c_str());
686 // Ok, the scanning of files here is not sufficient.
687 // Sometimes files are named by "File: xxx" only
688 // So I think we should use some regexps to find files instead.
689 // "(\([^ ]+\)" should match the "(file " variant
690 // "File: \([^ ]+\)" should match the "File: file" variant
694 token = rtrim(token, "\r");
695 if (token.empty()) continue;
697 #ifndef USE_INCLUDED_STRING
702 if (regex_match(STRCONV(token), sub, reg1)) {
703 foundfile = STRCONV(sub.str(1));
704 } else if (regex_match(STRCONV(token), sub, reg2)) {
705 foundfile = STRCONV(sub.str(1));
706 } else if (regex_match(STRCONV(token), sub, reg3)) {
707 foundfile = STRCONV(sub.str(1));
708 } else if (regex_match(STRCONV(token), sub, reg4)) {
709 foundfile = STRCONV(sub.str(1));
710 } else if (regex_match(STRCONV(token), sub, reg5)) {
711 foundfile = STRCONV(sub.str(1));
716 // convert from native os path to unix path
717 foundfile = os::internal_path(foundfile);
719 lyxerr[Debug::DEPEND] << "Found file: "
720 << foundfile << endl;
722 // Ok now we found a file.
723 // Now we should make sure that this is a file that we can
724 // access through the normal paths.
725 // We will not try any fancy search methods to
728 // (1) foundfile is an
729 // absolute path and should
731 if (AbsolutePath(foundfile)) {
732 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
733 << foundfile << endl;
734 // On initial insert we want to do the update at once
735 // since this file can not be a file generated by
737 if (FileInfo(foundfile).exist())
738 head.insert(foundfile, true);
741 // (2) foundfile is in the tmpdir
742 // insert it into head
743 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
744 if (regex_match(STRCONV(foundfile), unwanted)) {
745 lyxerr[Debug::DEPEND]
747 << OnlyFilename(foundfile)
748 << " in the dep file"
750 } else if (suffixIs(foundfile, ".tex")) {
751 // This is a tex file generated by LyX
752 // and latex is not likely to change this
754 lyxerr[Debug::DEPEND]
755 << "Tmpdir TeX file: "
756 << OnlyFilename(foundfile)
758 head.insert(foundfile, true);
760 lyxerr[Debug::DEPEND]
762 << OnlyFilename(foundfile)
764 head.insert(OnlyFilename(foundfile));
767 lyxerr[Debug::DEPEND]
768 << "Not a file or we are unable to find it."
772 // Make sure that the main .tex file is in the dependancy file.
773 head.insert(OnlyFilename(file), true);