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/tostr.h"
25 #include "support/lstrings.h"
26 #include "support/lyxlib.h"
27 #include "support/systemcall.h"
28 #include "support/os.h"
29 #include "support/path.h"
31 #include <boost/regex.hpp>
34 #include <cstdio> // sscanf
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 void showRunMessage(LyXFunc * lf, unsigned int count)
73 string str = bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
74 lf->dispatch(FuncRequest(LFUN_MESSAGE, str));
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, string const & f, string const & p)
111 : cmd(latex), file(f), path(p)
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
131 lyx::unlink(depfile);
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, LyXFunc * lfun)
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(lyx::getcwd());
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;
230 showRunMessage(lfun, count);
234 scanres = scanLogFile(terr);
235 if (scanres & ERROR_RERUN) {
236 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
238 scanres = scanLogFile(terr);
241 if (scanres & ERRORS) {
242 deleteFilesOnError();
243 return scanres; // return on error
246 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
247 if (!run_bibtex && bibtex_info_old != bibtex_info)
250 // update the dependencies.
251 deplog(head); // reads the latex log
255 // At this point we must run external programs if needed.
256 // makeindex will be run if a .idx file changed or was generated.
257 // And if there were undefined citations or changes in references
258 // the .aux file is checked for signs of bibtex. Bibtex is then run
262 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
264 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
266 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
269 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
273 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
274 if (scanres & UNDEF_CIT || run_bibtex) {
275 // Here we must scan the .aux file and look for
276 // "\bibdata" and/or "\bibstyle". If one of those
277 // tags is found -> run bibtex and set rerun = true;
279 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
281 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
284 updateBibtexDependencies(head, bibtex_info);
285 rerun |= runBibTeX(bibtex_info);
286 } else if (!had_depfile) {
287 /// If we run pdflatex on the file after running latex on it,
288 /// then we do not need to run bibtex, but we do need to
289 /// insert the .bib and .bst files into the .dep-pdf file.
290 updateBibtexDependencies(head, bibtex_info);
294 // we know on this point that latex has been run once (or we just
295 // returned) and the question now is to decide if we need to run
296 // it any more. This is done by asking if any of the files in the
297 // dependency file has changed. (remember that the checksum for
298 // a given file is reported to have changed if it just was created)
299 // -> if changed or rerun == true:
300 // run latex once more and
301 // update the dependency structure
302 // -> if not changed:
303 // we does nothing at this point
305 if (rerun || head.sumchange()) {
308 lyxerr[Debug::DEPEND]
309 << "Dep. file has changed or rerun requested" << endl;
311 << "Run #" << count << endl;
313 showRunMessage(lfun, count);
317 scanres = scanLogFile(terr);
318 if (scanres & ERRORS) {
319 deleteFilesOnError();
320 return scanres; // return on error
323 // update the depedencies
324 deplog(head); // reads the latex log
327 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
331 // The inclusion of files generated by external programs like
332 // makeindex or bibtex might have done changes to pagenumbereing,
333 // etc. And because of this we must run the external programs
334 // again to make sure everything is redone correctly.
335 // Also there should be no need to run the external programs any
338 // run makeindex if the <file>.idx has changed or was generated.
339 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
341 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
343 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
346 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
350 // we will only run latex more if the log file asks for it.
351 // or if the sumchange() is true.
352 // -> rerun asked for:
354 // remake the dependency file
355 // goto 2 or return if max runs are reached.
356 // -> rerun not asked for:
357 // just return (fall out of bottom of func)
359 while ((head.sumchange() || rerun || (scanres & RERUN))
360 && count < MAX_RUN) {
361 // Yes rerun until message goes away, or until
362 // MAX_RUNS are reached.
365 lyxerr[Debug::LATEX] << "Run #" << count << endl;
367 showRunMessage(lfun, count);
371 scanres = scanLogFile(terr);
372 if (scanres & ERRORS) {
373 deleteFilesOnError();
374 return scanres; // return on error
381 // Write the dependencies to file.
383 lyxerr[Debug::LATEX] << "Done." << endl;
388 int LaTeX::startscript()
391 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
392 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
393 string tmp = cmd + ' ' + file + " > nul";
396 return one.startscript(Systemcall::Wait, tmp);
400 bool LaTeX::runMakeIndex(string const & f)
402 lyxerr[Debug::LATEX] << "idx file has been made,"
403 " running makeindex on file "
406 // It should be possible to set the switches for makeindex
407 // sorting style and such. It would also be very convenient
408 // to be able to make style files from within LyX. This has
409 // to come for a later time.
410 string tmp = "makeindex -c -q ";
413 one.startscript(Systemcall::Wait, tmp);
418 vector<Aux_Info> const
419 LaTeX::scanAuxFiles(string const & file)
421 vector<Aux_Info> result;
423 result.push_back(scanAuxFile(file));
425 for (int i = 1; i < 1000; ++i) {
426 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
431 result.push_back(scanAuxFile(file2));
437 Aux_Info const LaTeX::scanAuxFile(string const & file)
440 result.aux_file = file;
441 scanAuxFile(file, result);
446 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
448 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
450 ifstream ifs(file.c_str());
452 regex reg1("\\\\citation\\{([^}]+)\\}");
453 regex reg2("\\\\bibdata\\{([^}]+)\\}");
454 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
455 regex reg4("\\\\@input\\{([^}]+)\\}");
457 while (getline(ifs, token)) {
458 token = rtrim(token, "\r");
459 #ifndef USE_INCLUDED_STRING
464 if (regex_match(STRCONV(token), sub, reg1)) {
465 string data = STRCONV(sub.str(1));
466 while (!data.empty()) {
468 data = split(data, citation, ',');
469 lyxerr[Debug::LATEX] << "Citation: "
471 aux_info.citations.insert(citation);
473 } else if (regex_match(STRCONV(token), sub, reg2)) {
474 string data = sub.STRCONV(str(1));
475 // data is now all the bib files separated by ','
476 // get them one by one and pass them to the helper
477 while (!data.empty()) {
479 data = split(data, database, ',');
480 database = ChangeExtension(database, "bib");
481 lyxerr[Debug::LATEX] << "BibTeX database: `"
482 << database << '\'' << endl;
483 aux_info.databases.insert(database);
485 } else if (regex_match(STRCONV(token), sub, reg3)) {
486 string style = STRCONV(sub.str(1));
487 // token is now the style file
488 // pass it to the helper
489 style = ChangeExtension(style, "bst");
490 lyxerr[Debug::LATEX] << "BibTeX style: `"
491 << style << '\'' << endl;
492 aux_info.styles.insert(style);
493 } else if (regex_match(STRCONV(token), sub, reg4)) {
494 string const file2 = STRCONV(sub.str(1));
495 scanAuxFile(file2, aux_info);
501 void LaTeX::updateBibtexDependencies(DepTable & dep,
502 vector<Aux_Info> const & bibtex_info)
504 // Since a run of Bibtex mandates more latex runs it is ok to
505 // remove all ".bib" and ".bst" files.
506 dep.remove_files_with_extension(".bib");
507 dep.remove_files_with_extension(".bst");
508 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
510 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
511 it != bibtex_info.end(); ++it) {
512 for (set<string>::const_iterator it2 = it->databases.begin();
513 it2 != it->databases.end(); ++it2) {
514 string file = findtexfile(*it2, "bib");
516 dep.insert(file, true);
519 for (set<string>::const_iterator it2 = it->styles.begin();
520 it2 != it->styles.end(); ++it2) {
521 string file = findtexfile(*it2, "bst");
523 dep.insert(file, true);
529 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
532 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
533 it != bibtex_info.end(); ++it) {
534 if (it->databases.empty())
538 string tmp = "bibtex ";
539 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
541 one.startscript(Systemcall::Wait, tmp);
543 // Return whether bibtex was run
548 int LaTeX::scanLogFile(TeXErrors & terr)
552 int retval = NO_ERRORS;
553 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
554 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
555 ifstream ifs(tmp.c_str());
558 while (getline(ifs, token)) {
559 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
564 if (prefixIs(token, "LaTeX Warning:")) {
565 // Here shall we handle different
567 retval |= LATEX_WARNING;
568 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
569 if (contains(token, "Rerun to get cross-references")) {
572 << "We should rerun." << endl;
573 } else if (contains(token, "Citation")
574 && contains(token, "on page")
575 && contains(token, "undefined")) {
578 } else if (prefixIs(token, "Package")) {
580 retval |= PACKAGE_WARNING;
581 if (contains(token, "natbib Warning:")) {
583 if (contains(token, "Citation")
584 && contains(token, "on page")
585 && contains(token, "undefined")) {
588 } else if (contains(token, "run BibTeX")) {
590 } else if (contains(token, "Rerun LaTeX") ||
591 contains(token, "Rerun to get")) {
592 // at least longtable.sty and bibtopic.sty
595 << "We should rerun." << endl;
598 } else if (token[0] == '(') {
599 if (contains(token, "Rerun LaTeX") ||
600 contains(token, "Rerun to get")) {
603 << "We should rerun." << endl;
606 } else if (prefixIs(token, "! ")) {
607 // Ok, we have something that looks like a TeX Error
608 // but what do we really have.
610 // Just get the error description:
611 string desc(token, 2);
612 if (contains(token, "LaTeX Error:"))
613 retval |= LATEX_ERROR;
618 if (!getline(ifs, tmp))
622 } while (!prefixIs(tmp, "l."));
623 if (prefixIs(tmp, "l.")) {
624 // we have a latex error
626 if (contains(desc, "Package babel Error: You haven't defined the language"))
627 retval |= ERROR_RERUN;
628 // get the line number:
630 sscanf(tmp.c_str(), "l.%d", &line);
631 // get the rest of the message:
632 string errstr(tmp, tmp.find(' '));
635 while (!contains(errstr, "l.")
637 && !prefixIs(tmp, "! ")
638 && !contains(tmp, "(job aborted")) {
644 << "line: " << line << '\n'
645 << "Desc: " << desc << '\n'
646 << "Text: " << errstr << endl;
647 if (line == last_line)
653 if (line_count <= 5) {
654 terr.insertError(line, desc, errstr);
659 // information messages, TeX warnings and other
660 // warnings we have not caught earlier.
661 if (prefixIs(token, "Overfull ")) {
662 retval |= TEX_WARNING;
663 } else if (prefixIs(token, "Underfull ")) {
664 retval |= TEX_WARNING;
665 } else if (contains(token, "Rerun to get citations")) {
666 // Natbib seems to use this.
668 } else if (contains(token, "No pages of output")) {
669 // A dvi file was not created
671 } else if (contains(token, "That makes 100 errors")) {
672 // More than 100 errors were reprted
673 retval |= TOO_MANY_ERRORS;
677 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
682 void LaTeX::deplog(DepTable & head)
684 // This function reads the LaTeX log file end extracts all the external
685 // files used by the LaTeX run. The files are then entered into the
688 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
690 regex reg1("\\)* *\\(([^ )]+).*");
691 regex reg2("File: ([^ ]+).*");
692 regex reg3("No file ([^ ]+)\\..*");
693 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
694 // If an index should be created, MikTex does not write a line like
695 // \openout# = 'sample,idx'.
696 // but intstead only a line like this into the log:
697 // Writing index file sample.idx
698 regex reg5("Writing index file ([^ ]+).*");
699 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
701 ifstream ifs(logfile.c_str());
703 // Ok, the scanning of files here is not sufficient.
704 // Sometimes files are named by "File: xxx" only
705 // So I think we should use some regexps to find files instead.
706 // "(\([^ ]+\)" should match the "(file " variant
707 // "File: \([^ ]+\)" should match the "File: file" variant
711 token = rtrim(token, "\r");
712 if (token.empty()) continue;
714 #ifndef USE_INCLUDED_STRING
719 if (regex_match(STRCONV(token), sub, reg1)) {
720 foundfile = STRCONV(sub.str(1));
721 } else if (regex_match(STRCONV(token), sub, reg2)) {
722 foundfile = STRCONV(sub.str(1));
723 } else if (regex_match(STRCONV(token), sub, reg3)) {
724 foundfile = STRCONV(sub.str(1));
725 } else if (regex_match(STRCONV(token), sub, reg4)) {
726 foundfile = STRCONV(sub.str(1));
727 } else if (regex_match(STRCONV(token), sub, reg5)) {
728 foundfile = STRCONV(sub.str(1));
733 // convert from native os path to unix path
734 foundfile = os::internal_path(foundfile);
736 lyxerr[Debug::DEPEND] << "Found file: "
737 << foundfile << endl;
739 // Ok now we found a file.
740 // Now we should make sure that this is a file that we can
741 // access through the normal paths.
742 // We will not try any fancy search methods to
745 // (1) foundfile is an
746 // absolute path and should
748 if (AbsolutePath(foundfile)) {
749 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
750 << foundfile << endl;
751 // On initial insert we want to do the update at once
752 // since this file can not be a file generated by
754 if (FileInfo(foundfile).exist())
755 head.insert(foundfile, true);
758 // (2) foundfile is in the tmpdir
759 // insert it into head
760 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
761 if (regex_match(STRCONV(foundfile), unwanted)) {
762 lyxerr[Debug::DEPEND]
764 << OnlyFilename(foundfile)
765 << " in the dep file"
767 } else if (suffixIs(foundfile, ".tex")) {
768 // This is a tex file generated by LyX
769 // and latex is not likely to change this
771 lyxerr[Debug::DEPEND]
772 << "Tmpdir TeX file: "
773 << OnlyFilename(foundfile)
775 head.insert(foundfile, true);
777 lyxerr[Debug::DEPEND]
779 << OnlyFilename(foundfile)
781 head.insert(OnlyFilename(foundfile));
784 lyxerr[Debug::DEPEND]
785 << "Not a file or we are unable to find it."
789 // Make sure that the main .tex file is in the dependancy file.
790 head.insert(OnlyFilename(file), true);