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 #pragma implementation
21 #include "support/filetools.h"
23 #include "support/FileInfo.h"
25 #include "support/lyxlib.h"
26 #include "support/syscall.h"
27 #include "support/syscontr.h"
28 #include "support/path.h"
29 #include "support/LRegex.h"
30 #include "support/LSubstring.h"
31 #include "support/lstrings.h"
32 #include "bufferlist.h"
34 #include "lyx_gui_misc.h"
43 // TODO: in no particular order
44 // - get rid of the extern BufferList and the call to
45 // BufferList::updateIncludedTeXfiles, this should either
46 // be done before calling LaTeX::funcs or in a completely
48 // - the bibtex command options should be supported.
49 // - the makeindex style files should be taken care of with
50 // the dependency mechanism.
51 // - makeindex commandline options should be supported
52 // - somewhere support viewing of bibtex and makeindex log files.
53 // - we should perhaps also scan the bibtex log file
54 // - we should perhaps also scan the bibtex log file
56 extern BufferList bufferlist;
62 void TeXErrors::insertError(int line, string const & error_desc,
63 string const & error_text)
65 Error newerr(line, error_desc, error_text);
66 errors.push_back(newerr);
73 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
74 : cmd(latex), file(f), path(p)
77 depfile = file + ".dep";
78 if (prefixIs(cmd, "pdf")) // Do we use pdflatex ?
83 void LaTeX::deleteFilesOnError() const
85 // currently just a dummy function.
87 // What files do we have to delete?
89 // This will at least make latex do all the runs
92 // but the reason for the error might be in a generated file...
94 string ofname = OnlyFilename(file);
97 string bbl = ChangeExtension(ofname, ".bbl");
101 string ind = ChangeExtension(ofname, ".ind");
104 // Also remove the aux file
105 string aux = ChangeExtension(ofname, ".aux");
110 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
111 // We know that this function will only be run if the lyx buffer
112 // has been changed. We also know that a newly written .tex file
113 // is always different from the previous one because of the date
114 // in it. However it seems safe to run latex (at least) on time each
115 // time the .tex file changes.
117 int scanres = NO_ERRORS;
118 unsigned int count = 0; // number of times run
119 num_errors = 0; // just to make sure.
120 const unsigned int MAX_RUN = 6;
121 DepTable head; // empty head
122 bool rerun = false; // rerun requested
124 // The class LaTeX does not know the temp path.
125 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
127 // Never write the depfile if an error was encountered.
130 // first check if the file dependencies exist:
131 // ->If it does exist
132 // check if any of the files mentioned in it have
133 // changed (done using a checksum).
135 // run latex once and
136 // remake the dependency file
137 // -> if not changed:
138 // just return there is nothing to do for us.
139 // ->if it doesn't exist
141 // run latex once (we need to run latex once anyway) and
142 // remake the dependency file.
145 FileInfo fi(depfile);
146 bool had_depfile = fi.exist();
147 bool run_bibtex = false;
148 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
151 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
152 // Read the dep file:
154 // Update the checksums
156 if (!head.sumchange()) {
157 lyxerr[Debug::DEPEND] << "return no_change" << endl;
160 lyxerr[Debug::DEPEND]
161 << "Dependency file has changed" << endl;
163 if (head.extchanged(".bib") || head.extchanged(".bst"))
166 lyxerr[Debug::DEPEND]
167 << "Dependency file does not exist" << endl;
169 /// We scan the aux file even when had_depfile = false,
170 /// because we can run pdflatex on the file after running latex on it,
171 /// in which case we will not need to run bibtex again.
172 vector<Aux_Info> bibtex_info_old;
174 bibtex_info_old = scanAuxFiles(aux_file);
177 lyxerr[Debug::LATEX] << "Run #" << count << endl;
180 str << _("LaTeX run number") << ' ' << count;
181 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
185 scanres = scanLogFile(terr);
186 if (scanres & ERROR_RERUN) {
187 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
189 scanres = scanLogFile(terr);
192 if (scanres & ERRORS) {
193 deleteFilesOnError();
194 return scanres; // return on error
197 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
198 if (!run_bibtex && bibtex_info_old != bibtex_info)
201 // update the dependencies.
202 deplog(head); // reads the latex log
206 // At this point we must run external programs if needed.
207 // makeindex will be run if a .idx file changed or was generated.
208 // And if there were undefined citations or changes in references
209 // the .aux file is checked for signs of bibtex. Bibtex is then run
213 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
215 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
217 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
220 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
224 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
225 if (scanres & UNDEF_CIT || run_bibtex) {
226 // Here we must scan the .aux file and look for
227 // "\bibdata" and/or "\bibstyle". If one of those
228 // tags is found -> run bibtex and set rerun = true;
230 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
232 lfun->dispatch(LFUN_MESSAGE, _("Running BibTeX."));
235 updateBibtexDependencies(head, bibtex_info);
236 rerun |= runBibTeX(bibtex_info);
237 } else if (!had_depfile) {
238 /// If we run pdflatex on the file after running latex on it,
239 /// then we do not need to run bibtex, but we do need to
240 /// insert the .bib and .bst files into the .dep-pdf file.
241 updateBibtexDependencies(head, bibtex_info);
245 // we know on this point that latex has been run once (or we just
246 // returned) and the question now is to decide if we need to run
247 // it any more. This is done by asking if any of the files in the
248 // dependency file has changed. (remember that the checksum for
249 // a given file is reported to have changed if it just was created)
250 // -> if changed or rerun == true:
251 // run latex once more and
252 // update the dependency structure
253 // -> if not changed:
254 // we does nothing at this point
256 if (rerun || head.sumchange()) {
259 lyxerr[Debug::DEPEND]
260 << "Dep. file has changed or rerun requested" << endl;
262 << "Run #" << count << endl;
265 str << _("LaTeX run number") << ' ' << count;
266 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
270 scanres = scanLogFile(terr);
271 if (scanres & ERRORS) {
272 deleteFilesOnError();
273 return scanres; // return on error
276 // update the depedencies
277 deplog(head); // reads the latex log
280 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
284 // The inclusion of files generated by external programs like
285 // makeindex or bibtex might have done changes to pagenumbereing,
286 // etc. And because of this we must run the external programs
287 // again to make sure everything is redone correctly.
288 // Also there should be no need to run the external programs any
291 // run makeindex if the <file>.idx has changed or was generated.
292 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
294 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
296 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
299 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
303 // we will only run latex more if the log file asks for it.
304 // or if the sumchange() is true.
305 // -> rerun asked for:
307 // remake the dependency file
308 // goto 2 or return if max runs are reached.
309 // -> rerun not asked for:
310 // just return (fall out of bottom of func)
312 while ((head.sumchange() || rerun || (scanres & RERUN))
313 && count < MAX_RUN) {
314 // Yes rerun until message goes away, or until
315 // MAX_RUNS are reached.
318 lyxerr[Debug::LATEX] << "Run #" << count << endl;
321 str << _("LaTeX run number") << ' ' << count;
322 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
326 scanres = scanLogFile(terr);
327 if (scanres & ERRORS) {
328 deleteFilesOnError();
329 return scanres; // return on error
336 // Write the dependencies to file.
338 lyxerr[Debug::LATEX] << "Done." << endl;
343 int LaTeX::operator()()
346 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
347 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
348 string tmp = cmd + ' ' + file + " > nul";
351 return one.startscript(Systemcalls::System, tmp);
355 bool LaTeX::runMakeIndex(string const & f)
357 lyxerr[Debug::LATEX] << "idx file has been made,"
358 " running makeindex on file "
361 // It should be possible to set the switches for makeindex
362 // sorting style and such. It would also be very convenient
363 // to be able to make style files from within LyX. This has
364 // to come for a later time. (0.13 perhaps?)
365 string tmp = "makeindex -c -q ";
368 one.startscript(Systemcalls::System, tmp);
373 vector<Aux_Info> const
374 LaTeX::scanAuxFiles(string const & file)
376 vector<Aux_Info> result;
378 result.push_back(scanAuxFile(file));
380 for (int i = 1; i < 1000; ++i) {
381 string file2 = ChangeExtension(file, "") + "." + tostr(i)
386 result.push_back(scanAuxFile(file2));
392 Aux_Info const LaTeX::scanAuxFile(string const & file)
395 result.aux_file = file;
396 scanAuxFile(file, result);
401 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
403 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
405 ifstream ifs(file.c_str());
407 LRegex reg1("\\\\citation\\{([^}]+)\\}");
408 LRegex reg2("\\\\bibdata\\{([^}]+)\\}");
409 LRegex reg3("\\\\bibstyle\\{([^}]+)\\}");
410 LRegex reg4("\\\\@input\\{([^}]+)\\}");
412 while (getline(ifs, token)) {
413 token = strip(token, '\r');
414 if (reg1.exact_match(token)) {
415 LRegex::SubMatches const & sub = reg1.exec(token);
416 string data = LSubstring(token, sub[1].first,
418 while (!data.empty()) {
420 data = split(data, citation, ',');
421 lyxerr[Debug::LATEX] << "Citation: "
423 aux_info.citations.insert(citation);
425 } else if (reg2.exact_match(token)) {
426 LRegex::SubMatches const & sub = reg2.exec(token);
427 string data = LSubstring(token, sub[1].first,
429 // data is now all the bib files separated by ','
430 // get them one by one and pass them to the helper
431 while (!data.empty()) {
433 data = split(data, database, ',');
434 database = ChangeExtension(database, "bib");
435 lyxerr[Debug::LATEX] << "Bibtex database: `"
436 << database << "'" << endl;
437 aux_info.databases.insert(database);
439 } else if (reg3.exact_match(token)) {
440 LRegex::SubMatches const & sub = reg3.exec(token);
441 string style = LSubstring(token, sub[1].first,
443 // token is now the style file
444 // pass it to the helper
445 style = ChangeExtension(style, "bst");
446 lyxerr[Debug::LATEX] << "Bibtex style: `"
447 << style << "'" << endl;
448 aux_info.styles.insert(style);
449 } else if (reg4.exact_match(token)) {
450 LRegex::SubMatches const & sub = reg4.exec(token);
451 string file2 = LSubstring(token, sub[1].first,
453 scanAuxFile(file2, aux_info);
459 void LaTeX::updateBibtexDependencies(DepTable & dep,
460 vector<Aux_Info> const & bibtex_info)
462 // Since a run of Bibtex mandates more latex runs it is ok to
463 // remove all ".bib" and ".bst" files.
464 dep.remove_files_with_extension(".bib");
465 dep.remove_files_with_extension(".bst");
466 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
468 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
469 it != bibtex_info.end(); ++it) {
470 for (set<string>::const_iterator it2 = it->databases.begin();
471 it2 != it->databases.end(); ++it2) {
472 string file = findtexfile(*it2, "bib");
474 dep.insert(file, true);
477 for (set<string>::const_iterator it2 = it->styles.begin();
478 it2 != it->styles.end(); ++it2) {
479 string file = findtexfile(*it2, "bst");
481 dep.insert(file, true);
487 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
490 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
491 it != bibtex_info.end(); ++it) {
492 if (it->databases.empty())
496 string tmp = "bibtex ";
497 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
499 one.startscript(Systemcalls::System, tmp);
501 // Return whether bibtex was run
506 int LaTeX::scanLogFile(TeXErrors & terr)
510 int retval = NO_ERRORS;
511 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
512 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
513 ifstream ifs(tmp.c_str());
516 while (getline(ifs, token)) {
517 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
522 if (prefixIs(token, "LaTeX Warning:")) {
523 // Here shall we handle different
525 retval |= LATEX_WARNING;
526 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
527 if (contains(token, "Rerun to get cross-references")) {
530 << "We should rerun." << endl;
531 } else if (contains(token, "Citation")
532 && contains(token, "on page")
533 && contains(token, "undefined")) {
536 } else if (prefixIs(token, "Package")) {
538 retval |= PACKAGE_WARNING;
539 if (contains(token, "natbib Warning:")) {
541 if (contains(token, "Citation")
542 && contains(token, "on page")
543 && contains(token, "undefined")) {
546 } else if (contains(token, "run BibTeX")) {
548 } else if (contains(token, "Rerun LaTeX") ||
549 contains(token, "Rerun to get")) {
550 // at least longtable.sty and bibtopic.sty
553 << "We should rerun." << endl;
556 } else if (prefixIs(token, "(")) {
557 if (contains(token, "Rerun LaTeX") ||
558 contains(token, "Rerun to get")) {
561 << "We should rerun." << endl;
564 } else if (prefixIs(token, "! ")) {
565 // Ok, we have something that looks like a TeX Error
566 // but what do we really have.
568 // Just get the error description:
569 string desc(token, 2);
570 if (contains(token, "LaTeX Error:"))
571 retval |= LATEX_ERROR;
576 if (!getline(ifs, tmp))
580 } while (!prefixIs(tmp, "l."));
581 if (prefixIs(tmp, "l.")) {
582 // we have a latex error
584 if (contains(desc, "Package babel Error: You haven't defined the language"))
585 retval |= ERROR_RERUN;
586 // get the line number:
588 sscanf(tmp.c_str(), "l.%d", &line);
589 // get the rest of the message:
590 string errstr(tmp, tmp.find(' '));
593 while (!contains(errstr, "l.")
595 && !prefixIs(tmp, "! ")
596 && !contains(tmp, "(job aborted")) {
602 << "line: " << line << '\n'
603 << "Desc: " << desc << '\n'
604 << "Text: " << errstr << endl;
605 if (line == last_line)
611 if (line_count <= 5) {
612 terr.insertError(line, desc, errstr);
617 // information messages, TeX warnings and other
618 // warnings we have not caught earlier.
619 if (prefixIs(token, "Overfull ")) {
620 retval |= TEX_WARNING;
621 } else if (prefixIs(token, "Underfull ")) {
622 retval |= TEX_WARNING;
623 } else if (contains(token, "Rerun to get citations")) {
624 // Natbib seems to use this.
626 } else if (contains(token, "No pages of output")) {
627 // A dvi file was not created
629 } else if (contains(token, "That makes 100 errors")) {
630 // More than 100 errors were reprted
631 retval |= TOO_MANY_ERRORS;
635 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
640 void LaTeX::deplog(DepTable & head)
642 // This function reads the LaTeX log file end extracts all the external
643 // files used by the LaTeX run. The files are then entered into the
646 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
648 LRegex reg1("\\)* *\\(([^ )]+).*");
649 LRegex reg2("File: ([^ ]+).*");
650 LRegex reg3("No file ([^ ]+)\\..*");
651 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
652 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
654 ifstream ifs(logfile.c_str());
656 // Ok, the scanning of files here is not sufficient.
657 // Sometimes files are named by "File: xxx" only
658 // So I think we should use some regexps to find files instead.
659 // "(\([^ ]+\)" should match the "(file " variant
660 // "File: \([^ ]+\)" should match the "File: file" variant
664 token = strip(token, '\r');
665 if (token.empty()) continue;
667 if (reg1.exact_match(token)) {
668 LRegex::SubMatches const & sub = reg1.exec(token);
669 foundfile = LSubstring(token, sub[1].first,
671 } else if (reg2.exact_match(token)) {
672 LRegex::SubMatches const & sub = reg2.exec(token);
673 foundfile = LSubstring(token, sub[1].first,
675 } else if (reg3.exact_match(token)) {
676 LRegex::SubMatches const & sub = reg3.exec(token);
677 foundfile = LSubstring(token, sub[1].first,
679 } else if (reg4.exact_match(token)) {
680 LRegex::SubMatches const & sub = reg4.exec(token);
681 foundfile = LSubstring(token, sub[1].first,
687 lyxerr[Debug::DEPEND] << "Found file: "
688 << foundfile << endl;
690 // Ok now we found a file.
691 // Now we should make sure that this is a file that we can
692 // access through the normal paths.
693 // We will not try any fancy search methods to
696 // (1) foundfile is an
697 // absolute path and should
699 if (AbsolutePath(foundfile)) {
700 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
701 << foundfile << endl;
702 // On initial insert we want to do the update at once
703 // since this file can not be a file generated by
705 if (FileInfo(foundfile).exist())
706 head.insert(foundfile, true);
709 // (2) foundfile is in the tmpdir
710 // insert it into head
711 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
712 if (unwanted.exact_match(foundfile)) {
713 lyxerr[Debug::DEPEND]
715 << OnlyFilename(foundfile)
716 << " in the dep file"
718 } else if (suffixIs(foundfile, ".tex")) {
719 // This is a tex file generated by LyX
720 // and latex is not likely to change this
722 lyxerr[Debug::DEPEND]
723 << "Tmpdir TeX file: "
724 << OnlyFilename(foundfile)
726 head.insert(foundfile, true);
728 lyxerr[Debug::DEPEND]
730 << OnlyFilename(foundfile)
732 head.insert(OnlyFilename(foundfile));
735 lyxerr[Debug::DEPEND]
736 << "Not a file or we are unable to find it."
740 // Make sure that the main .tex file is in the dependancy file.
741 head.insert(OnlyFilename(file), true);