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 lyx::support::AbsolutePath;
35 using lyx::support::bformat;
36 using lyx::support::ChangeExtension;
37 using lyx::support::contains;
38 using lyx::support::FileInfo;
39 using lyx::support::findtexfile;
40 using lyx::support::getcwd;
41 using lyx::support::OnlyFilename;
42 using lyx::support::os;
43 using lyx::support::prefixIs;
44 using lyx::support::QuoteName;
45 using lyx::support::rtrim;
46 using lyx::support::split;
47 using lyx::support::suffixIs;
48 using lyx::support::Systemcall;
49 using lyx::support::unlink;
55 #ifndef CXX_GLOBAL_CSTD
66 // TODO: in no particular order
67 // - get rid of the extern BufferList and the call to
68 // BufferList::updateIncludedTeXfiles, this should either
69 // be done before calling LaTeX::funcs or in a completely
71 // - the bibtex command options should be supported.
72 // - the makeindex style files should be taken care of with
73 // the dependency mechanism.
74 // - makeindex commandline options should be supported
75 // - somewhere support viewing of bibtex and makeindex log files.
76 // - we should perhaps also scan the bibtex log file
77 // - we should perhaps also scan the bibtex log file
79 extern BufferList bufferlist;
83 string runMessage(unsigned int count)
85 return bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
94 void TeXErrors::insertError(int line, string const & error_desc,
95 string const & error_text)
97 Error newerr(line, error_desc, error_text);
98 errors.push_back(newerr);
102 bool operator==(Aux_Info const & a, Aux_Info const & o)
104 return a.aux_file == o.aux_file &&
105 a.citations == o.citations &&
106 a.databases == o.databases &&
107 a.styles == o.styles;
111 bool operator!=(Aux_Info const & a, Aux_Info const & o)
121 LaTeX::LaTeX(string const & latex, LatexRunParams const & rp,
122 string const & f, string const & p)
123 : cmd(latex), file(f), path(p), runparams(rp)
126 depfile = file + ".dep";
127 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
129 output_file = ChangeExtension(file,".pdf");
131 output_file = ChangeExtension(file,".dvi");
136 void LaTeX::deleteFilesOnError() const
138 // currently just a dummy function.
140 // What files do we have to delete?
142 // This will at least make latex do all the runs
145 // but the reason for the error might be in a generated file...
147 string const ofname = OnlyFilename(file);
150 string const bbl = ChangeExtension(ofname, ".bbl");
154 string const ind = ChangeExtension(ofname, ".ind");
157 // Also remove the aux file
158 string const aux = ChangeExtension(ofname, ".aux");
163 int LaTeX::run(TeXErrors & terr)
164 // We know that this function will only be run if the lyx buffer
165 // has been changed. We also know that a newly written .tex file
166 // is always different from the previous one because of the date
167 // in it. However it seems safe to run latex (at least) on time each
168 // time the .tex file changes.
170 int scanres = NO_ERRORS;
171 unsigned int count = 0; // number of times run
172 num_errors = 0; // just to make sure.
173 unsigned int const MAX_RUN = 6;
174 DepTable head; // empty head
175 bool rerun = false; // rerun requested
177 // The class LaTeX does not know the temp path.
178 bufferlist.updateIncludedTeXfiles(getcwd(), runparams);
180 // Never write the depfile if an error was encountered.
183 // first check if the file dependencies exist:
184 // ->If it does exist
185 // check if any of the files mentioned in it have
186 // changed (done using a checksum).
188 // run latex once and
189 // remake the dependency file
190 // -> if not changed:
191 // just return there is nothing to do for us.
192 // ->if it doesn't exist
194 // run latex once (we need to run latex once anyway) and
195 // remake the dependency file.
198 FileInfo fi(depfile);
199 bool had_depfile = fi.exist();
200 bool run_bibtex = false;
201 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
204 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
205 // Read the dep file:
206 had_depfile = head.read(depfile);
210 // Update the checksums
212 // Can't just check if anything has changed because it might have aborted
213 // on error last time... in which cas we need to re-run latex
214 // and collect the error messages (even if they are the same).
215 if (!FileInfo(output_file).exist()) {
216 lyxerr[Debug::DEPEND]
217 << "re-running LaTeX because output file doesn't exist." << endl;
218 } else if (!head.sumchange()) {
219 lyxerr[Debug::DEPEND] << "return no_change" << endl;
222 lyxerr[Debug::DEPEND]
223 << "Dependency file has changed" << endl;
226 if (head.extchanged(".bib") || head.extchanged(".bst"))
229 lyxerr[Debug::DEPEND]
230 << "Dependency file does not exist, or has wrong format" << endl;
232 /// We scan the aux file even when had_depfile = false,
233 /// because we can run pdflatex on the file after running latex on it,
234 /// in which case we will not need to run bibtex again.
235 vector<Aux_Info> bibtex_info_old;
237 bibtex_info_old = scanAuxFiles(aux_file);
240 lyxerr[Debug::LATEX] << "Run #" << count << endl;
241 message(runMessage(count));
244 scanres = scanLogFile(terr);
245 if (scanres & ERROR_RERUN) {
246 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
248 scanres = scanLogFile(terr);
251 if (scanres & ERRORS) {
252 deleteFilesOnError();
253 return scanres; // return on error
256 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
257 if (!run_bibtex && bibtex_info_old != bibtex_info)
260 // update the dependencies.
261 deplog(head); // reads the latex log
265 // At this point we must run external programs if needed.
266 // makeindex will be run if a .idx file changed or was generated.
267 // And if there were undefined citations or changes in references
268 // the .aux file is checked for signs of bibtex. Bibtex is then run
272 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
274 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
275 message(_("Running MakeIndex."));
276 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
280 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
281 if (scanres & UNDEF_CIT || run_bibtex) {
282 // Here we must scan the .aux file and look for
283 // "\bibdata" and/or "\bibstyle". If one of those
284 // tags is found -> run bibtex and set rerun = true;
286 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
287 message(_("Running BibTeX."));
288 updateBibtexDependencies(head, bibtex_info);
289 rerun |= runBibTeX(bibtex_info);
290 } else if (!had_depfile) {
291 /// If we run pdflatex on the file after running latex on it,
292 /// then we do not need to run bibtex, but we do need to
293 /// insert the .bib and .bst files into the .dep-pdf file.
294 updateBibtexDependencies(head, bibtex_info);
298 // we know on this point that latex has been run once (or we just
299 // returned) and the question now is to decide if we need to run
300 // it any more. This is done by asking if any of the files in the
301 // dependency file has changed. (remember that the checksum for
302 // a given file is reported to have changed if it just was created)
303 // -> if changed or rerun == true:
304 // run latex once more and
305 // update the dependency structure
306 // -> if not changed:
307 // we does nothing at this point
309 if (rerun || head.sumchange()) {
312 lyxerr[Debug::DEPEND]
313 << "Dep. file has changed or rerun requested" << endl;
315 << "Run #" << count << endl;
316 message(runMessage(count));
318 scanres = scanLogFile(terr);
319 if (scanres & ERRORS) {
320 deleteFilesOnError();
321 return scanres; // return on error
324 // update the depedencies
325 deplog(head); // reads the latex log
328 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
332 // The inclusion of files generated by external programs like
333 // makeindex or bibtex might have done changes to pagenumbereing,
334 // etc. And because of this we must run the external programs
335 // again to make sure everything is redone correctly.
336 // Also there should be no need to run the external programs any
339 // run makeindex if the <file>.idx has changed or was generated.
340 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
342 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
343 message(_("Running MakeIndex."));
344 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
348 // we will only run latex more if the log file asks for it.
349 // or if the sumchange() is true.
350 // -> rerun asked for:
352 // remake the dependency file
353 // goto 2 or return if max runs are reached.
354 // -> rerun not asked for:
355 // just return (fall out of bottom of func)
357 while ((head.sumchange() || rerun || (scanres & RERUN))
358 && count < MAX_RUN) {
359 // Yes rerun until message goes away, or until
360 // MAX_RUNS are reached.
363 lyxerr[Debug::LATEX] << "Run #" << count << endl;
364 message(runMessage(count));
366 scanres = scanLogFile(terr);
367 if (scanres & ERRORS) {
368 deleteFilesOnError();
369 return scanres; // return on error
376 // Write the dependencies to file.
378 lyxerr[Debug::LATEX] << "Done." << endl;
383 int LaTeX::startscript()
386 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
387 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
388 string tmp = cmd + ' ' + file + " > nul";
391 return one.startscript(Systemcall::Wait, tmp);
395 bool LaTeX::runMakeIndex(string const & f)
397 lyxerr[Debug::LATEX] << "idx file has been made,"
398 " running makeindex on file "
401 // It should be possible to set the switches for makeindex
402 // sorting style and such. It would also be very convenient
403 // to be able to make style files from within LyX. This has
404 // to come for a later time.
405 string tmp = "makeindex -c -q ";
408 one.startscript(Systemcall::Wait, tmp);
413 vector<Aux_Info> const
414 LaTeX::scanAuxFiles(string const & file)
416 vector<Aux_Info> result;
418 result.push_back(scanAuxFile(file));
420 for (int i = 1; i < 1000; ++i) {
421 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
426 result.push_back(scanAuxFile(file2));
432 Aux_Info const LaTeX::scanAuxFile(string const & file)
435 result.aux_file = file;
436 scanAuxFile(file, result);
441 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
443 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
445 ifstream ifs(file.c_str());
447 regex reg1("\\\\citation\\{([^}]+)\\}");
448 regex reg2("\\\\bibdata\\{([^}]+)\\}");
449 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
450 regex reg4("\\\\@input\\{([^}]+)\\}");
452 while (getline(ifs, token)) {
453 token = rtrim(token, "\r");
455 if (regex_match(token, sub, reg1)) {
456 string data = sub.str(1);
457 while (!data.empty()) {
459 data = split(data, citation, ',');
460 lyxerr[Debug::LATEX] << "Citation: "
462 aux_info.citations.insert(citation);
464 } else if (regex_match(token, sub, reg2)) {
465 string data = sub.str(1);
466 // data is now all the bib files separated by ','
467 // get them one by one and pass them to the helper
468 while (!data.empty()) {
470 data = split(data, database, ',');
471 database = ChangeExtension(database, "bib");
472 lyxerr[Debug::LATEX] << "BibTeX database: `"
473 << database << '\'' << endl;
474 aux_info.databases.insert(database);
476 } else if (regex_match(token, sub, reg3)) {
477 string style = sub.str(1);
478 // token is now the style file
479 // pass it to the helper
480 style = ChangeExtension(style, "bst");
481 lyxerr[Debug::LATEX] << "BibTeX style: `"
482 << style << '\'' << endl;
483 aux_info.styles.insert(style);
484 } else if (regex_match(token, sub, reg4)) {
485 string const file2 = sub.str(1);
486 scanAuxFile(file2, aux_info);
492 void LaTeX::updateBibtexDependencies(DepTable & dep,
493 vector<Aux_Info> const & bibtex_info)
495 // Since a run of Bibtex mandates more latex runs it is ok to
496 // remove all ".bib" and ".bst" files.
497 dep.remove_files_with_extension(".bib");
498 dep.remove_files_with_extension(".bst");
499 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
501 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
502 it != bibtex_info.end(); ++it) {
503 for (set<string>::const_iterator it2 = it->databases.begin();
504 it2 != it->databases.end(); ++it2) {
505 string file = findtexfile(*it2, "bib");
507 dep.insert(file, true);
510 for (set<string>::const_iterator it2 = it->styles.begin();
511 it2 != it->styles.end(); ++it2) {
512 string file = findtexfile(*it2, "bst");
514 dep.insert(file, true);
520 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
523 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
524 it != bibtex_info.end(); ++it) {
525 if (it->databases.empty())
529 string tmp = "bibtex ";
530 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
532 one.startscript(Systemcall::Wait, tmp);
534 // Return whether bibtex was run
539 int LaTeX::scanLogFile(TeXErrors & terr)
543 int retval = NO_ERRORS;
544 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
545 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
546 ifstream ifs(tmp.c_str());
549 while (getline(ifs, token)) {
550 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
555 if (prefixIs(token, "LaTeX Warning:")) {
556 // Here shall we handle different
558 retval |= LATEX_WARNING;
559 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
560 if (contains(token, "Rerun to get cross-references")) {
563 << "We should rerun." << endl;
564 } else if (contains(token, "Citation")
565 && contains(token, "on page")
566 && contains(token, "undefined")) {
569 } else if (prefixIs(token, "Package")) {
571 retval |= PACKAGE_WARNING;
572 if (contains(token, "natbib Warning:")) {
574 if (contains(token, "Citation")
575 && contains(token, "on page")
576 && contains(token, "undefined")) {
579 } else if (contains(token, "run BibTeX")) {
581 } else if (contains(token, "Rerun LaTeX") ||
582 contains(token, "Rerun to get")) {
583 // at least longtable.sty and bibtopic.sty
586 << "We should rerun." << endl;
589 } else if (token[0] == '(') {
590 if (contains(token, "Rerun LaTeX") ||
591 contains(token, "Rerun to get")) {
594 << "We should rerun." << endl;
597 } else if (prefixIs(token, "! ")) {
598 // Ok, we have something that looks like a TeX Error
599 // but what do we really have.
601 // Just get the error description:
602 string desc(token, 2);
603 if (contains(token, "LaTeX Error:"))
604 retval |= LATEX_ERROR;
609 if (!getline(ifs, tmp))
613 } while (!prefixIs(tmp, "l."));
614 if (prefixIs(tmp, "l.")) {
615 // we have a latex error
617 if (contains(desc, "Package babel Error: You haven't defined the language"))
618 retval |= ERROR_RERUN;
619 // get the line number:
621 sscanf(tmp.c_str(), "l.%d", &line);
622 // get the rest of the message:
623 string errstr(tmp, tmp.find(' '));
626 while (!contains(errstr, "l.")
628 && !prefixIs(tmp, "! ")
629 && !contains(tmp, "(job aborted")) {
635 << "line: " << line << '\n'
636 << "Desc: " << desc << '\n'
637 << "Text: " << errstr << endl;
638 if (line == last_line)
644 if (line_count <= 5) {
645 terr.insertError(line, desc, errstr);
650 // information messages, TeX warnings and other
651 // warnings we have not caught earlier.
652 if (prefixIs(token, "Overfull ")) {
653 retval |= TEX_WARNING;
654 } else if (prefixIs(token, "Underfull ")) {
655 retval |= TEX_WARNING;
656 } else if (contains(token, "Rerun to get citations")) {
657 // Natbib seems to use this.
659 } else if (contains(token, "No pages of output")) {
660 // A dvi file was not created
662 } else if (contains(token, "That makes 100 errors")) {
663 // More than 100 errors were reprted
664 retval |= TOO_MANY_ERRORS;
668 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
673 void LaTeX::deplog(DepTable & head)
675 // This function reads the LaTeX log file end extracts all the external
676 // files used by the LaTeX run. The files are then entered into the
679 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
681 regex reg1("\\)* *\\(([^ )]+).*");
682 regex reg2("File: ([^ ]+).*");
683 regex reg3("No file ([^ ]+)\\..*");
684 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
685 // If an index should be created, MikTex does not write a line like
686 // \openout# = 'sample,idx'.
687 // but intstead only a line like this into the log:
688 // Writing index file sample.idx
689 regex reg5("Writing index file ([^ ]+).*");
690 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
692 ifstream ifs(logfile.c_str());
694 // Ok, the scanning of files here is not sufficient.
695 // Sometimes files are named by "File: xxx" only
696 // So I think we should use some regexps to find files instead.
697 // "(\([^ ]+\)" should match the "(file " variant
698 // "File: \([^ ]+\)" should match the "File: file" variant
702 token = rtrim(token, "\r");
703 if (token.empty()) continue;
707 if (regex_match(token, sub, reg1)) {
708 foundfile = sub.str(1);
709 } else if (regex_match(token, sub, reg2)) {
710 foundfile = sub.str(1);
711 } else if (regex_match(token, sub, reg3)) {
712 foundfile = sub.str(1);
713 } else if (regex_match(token, sub, reg4)) {
714 foundfile = sub.str(1);
715 } else if (regex_match(token, sub, reg5)) {
716 foundfile = sub.str(1);
721 // convert from native os path to unix path
722 foundfile = os::internal_path(foundfile);
724 lyxerr[Debug::DEPEND] << "Found file: "
725 << foundfile << endl;
727 // Ok now we found a file.
728 // Now we should make sure that this is a file that we can
729 // access through the normal paths.
730 // We will not try any fancy search methods to
733 // (1) foundfile is an
734 // absolute path and should
736 if (AbsolutePath(foundfile)) {
737 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
738 << foundfile << endl;
739 // On initial insert we want to do the update at once
740 // since this file can not be a file generated by
742 if (FileInfo(foundfile).exist())
743 head.insert(foundfile, true);
746 // (2) foundfile is in the tmpdir
747 // insert it into head
748 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
749 if (regex_match(foundfile, unwanted)) {
750 lyxerr[Debug::DEPEND]
752 << OnlyFilename(foundfile)
753 << " in the dep file"
755 } else if (suffixIs(foundfile, ".tex")) {
756 // This is a tex file generated by LyX
757 // and latex is not likely to change this
759 lyxerr[Debug::DEPEND]
760 << "Tmpdir TeX file: "
761 << OnlyFilename(foundfile)
763 head.insert(foundfile, true);
765 lyxerr[Debug::DEPEND]
767 << OnlyFilename(foundfile)
769 head.insert(OnlyFilename(foundfile));
772 lyxerr[Debug::DEPEND]
773 << "Not a file or we are unable to find it."
777 // Make sure that the main .tex file is in the dependancy file.
778 head.insert(OnlyFilename(file), true);