1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
5 * Copyright 1995 Matthias Ettrich
6 * Copyright 1995-2001 The LyX Team.
8 * This file is Copyright 1996-2001
11 * ======================================================
17 #include "bufferlist.h"
21 #include "funcrequest.h"
22 #include "support/filetools.h"
23 #include "support/FileInfo.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 #ifndef CXX_GLOBAL_CSTD
45 using boost::regex_match;
47 #ifndef USE_INCLUDED_STRING
53 // TODO: in no particular order
54 // - get rid of the extern BufferList and the call to
55 // BufferList::updateIncludedTeXfiles, this should either
56 // be done before calling LaTeX::funcs or in a completely
58 // - the bibtex command options should be supported.
59 // - the makeindex style files should be taken care of with
60 // the dependency mechanism.
61 // - makeindex commandline options should be supported
62 // - somewhere support viewing of bibtex and makeindex log files.
63 // - we should perhaps also scan the bibtex log file
64 // - we should perhaps also scan the bibtex log file
66 extern BufferList bufferlist;
70 void showRunMessage(LyXFunc * lf, unsigned int count)
72 string str = bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
73 lf->dispatch(FuncRequest(LFUN_MESSAGE, str));
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, string const & f, string const & p)
110 : cmd(latex), file(f), path(p)
113 depfile = file + ".dep";
114 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
116 output_file = ChangeExtension(file,".pdf");
118 output_file = ChangeExtension(file,".dvi");
123 void LaTeX::deleteFilesOnError() const
125 // currently just a dummy function.
127 // What files do we have to delete?
129 // This will at least make latex do all the runs
130 lyx::unlink(depfile);
132 // but the reason for the error might be in a generated file...
134 string const ofname = OnlyFilename(file);
137 string const bbl = ChangeExtension(ofname, ".bbl");
141 string const ind = ChangeExtension(ofname, ".ind");
144 // Also remove the aux file
145 string const aux = ChangeExtension(ofname, ".aux");
150 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
151 // We know that this function will only be run if the lyx buffer
152 // has been changed. We also know that a newly written .tex file
153 // is always different from the previous one because of the date
154 // in it. However it seems safe to run latex (at least) on time each
155 // time the .tex file changes.
157 int scanres = NO_ERRORS;
158 unsigned int count = 0; // number of times run
159 num_errors = 0; // just to make sure.
160 unsigned int const MAX_RUN = 6;
161 DepTable head; // empty head
162 bool rerun = false; // rerun requested
164 // The class LaTeX does not know the temp path.
165 bufferlist.updateIncludedTeXfiles(lyx::getcwd());
167 // Never write the depfile if an error was encountered.
170 // first check if the file dependencies exist:
171 // ->If it does exist
172 // check if any of the files mentioned in it have
173 // changed (done using a checksum).
175 // run latex once and
176 // remake the dependency file
177 // -> if not changed:
178 // just return there is nothing to do for us.
179 // ->if it doesn't exist
181 // run latex once (we need to run latex once anyway) and
182 // remake the dependency file.
185 FileInfo fi(depfile);
186 bool had_depfile = fi.exist();
187 bool run_bibtex = false;
188 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
191 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
192 // Read the dep file:
193 had_depfile = head.read(depfile);
197 // Update the checksums
199 // Can't just check if anything has changed because it might have aborted
200 // on error last time... in which cas we need to re-run latex
201 // and collect the error messages (even if they are the same).
202 if (!FileInfo(output_file).exist()) {
203 lyxerr[Debug::DEPEND]
204 << "re-running LaTeX because output file doesn't exist." << endl;
205 } else if (!head.sumchange()) {
206 lyxerr[Debug::DEPEND] << "return no_change" << endl;
209 lyxerr[Debug::DEPEND]
210 << "Dependency file has changed" << endl;
213 if (head.extchanged(".bib") || head.extchanged(".bst"))
216 lyxerr[Debug::DEPEND]
217 << "Dependency file does not exist, or has wrong format" << endl;
219 /// We scan the aux file even when had_depfile = false,
220 /// because we can run pdflatex on the file after running latex on it,
221 /// in which case we will not need to run bibtex again.
222 vector<Aux_Info> bibtex_info_old;
224 bibtex_info_old = scanAuxFiles(aux_file);
227 lyxerr[Debug::LATEX] << "Run #" << count << endl;
229 showRunMessage(lfun, 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;
265 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
268 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
272 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
273 if (scanres & UNDEF_CIT || run_bibtex) {
274 // Here we must scan the .aux file and look for
275 // "\bibdata" and/or "\bibstyle". If one of those
276 // tags is found -> run bibtex and set rerun = true;
278 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
280 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
283 updateBibtexDependencies(head, bibtex_info);
284 rerun |= runBibTeX(bibtex_info);
285 } else if (!had_depfile) {
286 /// If we run pdflatex on the file after running latex on it,
287 /// then we do not need to run bibtex, but we do need to
288 /// insert the .bib and .bst files into the .dep-pdf file.
289 updateBibtexDependencies(head, bibtex_info);
293 // we know on this point that latex has been run once (or we just
294 // returned) and the question now is to decide if we need to run
295 // it any more. This is done by asking if any of the files in the
296 // dependency file has changed. (remember that the checksum for
297 // a given file is reported to have changed if it just was created)
298 // -> if changed or rerun == true:
299 // run latex once more and
300 // update the dependency structure
301 // -> if not changed:
302 // we does nothing at this point
304 if (rerun || head.sumchange()) {
307 lyxerr[Debug::DEPEND]
308 << "Dep. file has changed or rerun requested" << endl;
310 << "Run #" << count << endl;
312 showRunMessage(lfun, count);
316 scanres = scanLogFile(terr);
317 if (scanres & ERRORS) {
318 deleteFilesOnError();
319 return scanres; // return on error
322 // update the depedencies
323 deplog(head); // reads the latex log
326 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
330 // The inclusion of files generated by external programs like
331 // makeindex or bibtex might have done changes to pagenumbereing,
332 // etc. And because of this we must run the external programs
333 // again to make sure everything is redone correctly.
334 // Also there should be no need to run the external programs any
337 // run makeindex if the <file>.idx has changed or was generated.
338 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
340 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
342 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
345 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
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;
366 showRunMessage(lfun, count);
370 scanres = scanLogFile(terr);
371 if (scanres & ERRORS) {
372 deleteFilesOnError();
373 return scanres; // return on error
380 // Write the dependencies to file.
382 lyxerr[Debug::LATEX] << "Done." << endl;
387 int LaTeX::startscript()
390 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
391 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
392 string tmp = cmd + ' ' + file + " > nul";
395 return one.startscript(Systemcall::Wait, tmp);
399 bool LaTeX::runMakeIndex(string const & f)
401 lyxerr[Debug::LATEX] << "idx file has been made,"
402 " running makeindex on file "
405 // It should be possible to set the switches for makeindex
406 // sorting style and such. It would also be very convenient
407 // to be able to make style files from within LyX. This has
408 // to come for a later time.
409 string tmp = "makeindex -c -q ";
412 one.startscript(Systemcall::Wait, tmp);
417 vector<Aux_Info> const
418 LaTeX::scanAuxFiles(string const & file)
420 vector<Aux_Info> result;
422 result.push_back(scanAuxFile(file));
424 for (int i = 1; i < 1000; ++i) {
425 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
430 result.push_back(scanAuxFile(file2));
436 Aux_Info const LaTeX::scanAuxFile(string const & file)
439 result.aux_file = file;
440 scanAuxFile(file, result);
445 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
447 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
449 ifstream ifs(file.c_str());
451 regex reg1("\\\\citation\\{([^}]+)\\}");
452 regex reg2("\\\\bibdata\\{([^}]+)\\}");
453 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
454 regex reg4("\\\\@input\\{([^}]+)\\}");
456 while (getline(ifs, token)) {
457 token = rtrim(token, "\r");
458 #ifndef USE_INCLUDED_STRING
463 if (regex_match(STRCONV(token), sub, reg1)) {
464 string data = STRCONV(sub.str(1));
465 while (!data.empty()) {
467 data = split(data, citation, ',');
468 lyxerr[Debug::LATEX] << "Citation: "
470 aux_info.citations.insert(citation);
472 } else if (regex_match(STRCONV(token), sub, reg2)) {
473 string data = sub.STRCONV(str(1));
474 // data is now all the bib files separated by ','
475 // get them one by one and pass them to the helper
476 while (!data.empty()) {
478 data = split(data, database, ',');
479 database = ChangeExtension(database, "bib");
480 lyxerr[Debug::LATEX] << "BibTeX database: `"
481 << database << '\'' << endl;
482 aux_info.databases.insert(database);
484 } else if (regex_match(STRCONV(token), sub, reg3)) {
485 string style = STRCONV(sub.str(1));
486 // token is now the style file
487 // pass it to the helper
488 style = ChangeExtension(style, "bst");
489 lyxerr[Debug::LATEX] << "BibTeX style: `"
490 << style << '\'' << endl;
491 aux_info.styles.insert(style);
492 } else if (regex_match(STRCONV(token), sub, reg4)) {
493 string const file2 = STRCONV(sub.str(1));
494 scanAuxFile(file2, aux_info);
500 void LaTeX::updateBibtexDependencies(DepTable & dep,
501 vector<Aux_Info> const & bibtex_info)
503 // Since a run of Bibtex mandates more latex runs it is ok to
504 // remove all ".bib" and ".bst" files.
505 dep.remove_files_with_extension(".bib");
506 dep.remove_files_with_extension(".bst");
507 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
509 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
510 it != bibtex_info.end(); ++it) {
511 for (set<string>::const_iterator it2 = it->databases.begin();
512 it2 != it->databases.end(); ++it2) {
513 string file = findtexfile(*it2, "bib");
515 dep.insert(file, true);
518 for (set<string>::const_iterator it2 = it->styles.begin();
519 it2 != it->styles.end(); ++it2) {
520 string file = findtexfile(*it2, "bst");
522 dep.insert(file, true);
528 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
531 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
532 it != bibtex_info.end(); ++it) {
533 if (it->databases.empty())
537 string tmp = "bibtex ";
538 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
540 one.startscript(Systemcall::Wait, tmp);
542 // Return whether bibtex was run
547 int LaTeX::scanLogFile(TeXErrors & terr)
551 int retval = NO_ERRORS;
552 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
553 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
554 ifstream ifs(tmp.c_str());
557 while (getline(ifs, token)) {
558 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
563 if (prefixIs(token, "LaTeX Warning:")) {
564 // Here shall we handle different
566 retval |= LATEX_WARNING;
567 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
568 if (contains(token, "Rerun to get cross-references")) {
571 << "We should rerun." << endl;
572 } else if (contains(token, "Citation")
573 && contains(token, "on page")
574 && contains(token, "undefined")) {
577 } else if (prefixIs(token, "Package")) {
579 retval |= PACKAGE_WARNING;
580 if (contains(token, "natbib Warning:")) {
582 if (contains(token, "Citation")
583 && contains(token, "on page")
584 && contains(token, "undefined")) {
587 } else if (contains(token, "run BibTeX")) {
589 } else if (contains(token, "Rerun LaTeX") ||
590 contains(token, "Rerun to get")) {
591 // at least longtable.sty and bibtopic.sty
594 << "We should rerun." << endl;
597 } else if (token[0] == '(') {
598 if (contains(token, "Rerun LaTeX") ||
599 contains(token, "Rerun to get")) {
602 << "We should rerun." << endl;
605 } else if (prefixIs(token, "! ")) {
606 // Ok, we have something that looks like a TeX Error
607 // but what do we really have.
609 // Just get the error description:
610 string desc(token, 2);
611 if (contains(token, "LaTeX Error:"))
612 retval |= LATEX_ERROR;
617 if (!getline(ifs, tmp))
621 } while (!prefixIs(tmp, "l."));
622 if (prefixIs(tmp, "l.")) {
623 // we have a latex error
625 if (contains(desc, "Package babel Error: You haven't defined the language"))
626 retval |= ERROR_RERUN;
627 // get the line number:
629 sscanf(tmp.c_str(), "l.%d", &line);
630 // get the rest of the message:
631 string errstr(tmp, tmp.find(' '));
634 while (!contains(errstr, "l.")
636 && !prefixIs(tmp, "! ")
637 && !contains(tmp, "(job aborted")) {
643 << "line: " << line << '\n'
644 << "Desc: " << desc << '\n'
645 << "Text: " << errstr << endl;
646 if (line == last_line)
652 if (line_count <= 5) {
653 terr.insertError(line, desc, errstr);
658 // information messages, TeX warnings and other
659 // warnings we have not caught earlier.
660 if (prefixIs(token, "Overfull ")) {
661 retval |= TEX_WARNING;
662 } else if (prefixIs(token, "Underfull ")) {
663 retval |= TEX_WARNING;
664 } else if (contains(token, "Rerun to get citations")) {
665 // Natbib seems to use this.
667 } else if (contains(token, "No pages of output")) {
668 // A dvi file was not created
670 } else if (contains(token, "That makes 100 errors")) {
671 // More than 100 errors were reprted
672 retval |= TOO_MANY_ERRORS;
676 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
681 void LaTeX::deplog(DepTable & head)
683 // This function reads the LaTeX log file end extracts all the external
684 // files used by the LaTeX run. The files are then entered into the
687 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
689 regex reg1("\\)* *\\(([^ )]+).*");
690 regex reg2("File: ([^ ]+).*");
691 regex reg3("No file ([^ ]+)\\..*");
692 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
693 // If an index should be created, MikTex does not write a line like
694 // \openout# = 'sample,idx'.
695 // but intstead only a line like this into the log:
696 // Writing index file sample.idx
697 regex reg5("Writing index file ([^ ]+).*");
698 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
700 ifstream ifs(logfile.c_str());
702 // Ok, the scanning of files here is not sufficient.
703 // Sometimes files are named by "File: xxx" only
704 // So I think we should use some regexps to find files instead.
705 // "(\([^ ]+\)" should match the "(file " variant
706 // "File: \([^ ]+\)" should match the "File: file" variant
710 token = rtrim(token, "\r");
711 if (token.empty()) continue;
713 #ifndef USE_INCLUDED_STRING
718 if (regex_match(STRCONV(token), sub, reg1)) {
719 foundfile = STRCONV(sub.str(1));
720 } else if (regex_match(STRCONV(token), sub, reg2)) {
721 foundfile = STRCONV(sub.str(1));
722 } else if (regex_match(STRCONV(token), sub, reg3)) {
723 foundfile = STRCONV(sub.str(1));
724 } else if (regex_match(STRCONV(token), sub, reg4)) {
725 foundfile = STRCONV(sub.str(1));
726 } else if (regex_match(STRCONV(token), sub, reg5)) {
727 foundfile = STRCONV(sub.str(1));
732 // convert from native os path to unix path
733 foundfile = os::internal_path(foundfile);
735 lyxerr[Debug::DEPEND] << "Found file: "
736 << foundfile << endl;
738 // Ok now we found a file.
739 // Now we should make sure that this is a file that we can
740 // access through the normal paths.
741 // We will not try any fancy search methods to
744 // (1) foundfile is an
745 // absolute path and should
747 if (AbsolutePath(foundfile)) {
748 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
749 << foundfile << endl;
750 // On initial insert we want to do the update at once
751 // since this file can not be a file generated by
753 if (FileInfo(foundfile).exist())
754 head.insert(foundfile, true);
757 // (2) foundfile is in the tmpdir
758 // insert it into head
759 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
760 if (regex_match(STRCONV(foundfile), unwanted)) {
761 lyxerr[Debug::DEPEND]
763 << OnlyFilename(foundfile)
764 << " in the dep file"
766 } else if (suffixIs(foundfile, ".tex")) {
767 // This is a tex file generated by LyX
768 // and latex is not likely to change this
770 lyxerr[Debug::DEPEND]
771 << "Tmpdir TeX file: "
772 << OnlyFilename(foundfile)
774 head.insert(foundfile, true);
776 lyxerr[Debug::DEPEND]
778 << OnlyFilename(foundfile)
780 head.insert(OnlyFilename(foundfile));
783 lyxerr[Debug::DEPEND]
784 << "Not a file or we are unable to find it."
788 // Make sure that the main .tex file is in the dependancy file.
789 head.insert(OnlyFilename(file), true);