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 //WriteStatus(lfun, string(_("LaTeX run number ")) + tostr(count));
187 scanres = scanLogFile(terr);
188 if (scanres & ERROR_RERUN) {
189 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
191 scanres = scanLogFile(terr);
194 if (scanres & ERRORS) {
195 deleteFilesOnError();
196 return scanres; // return on error
199 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
200 if (!run_bibtex && bibtex_info_old != bibtex_info)
203 // update the dependencies.
204 deplog(head); // reads the latex log
208 // At this point we must run external programs if needed.
209 // makeindex will be run if a .idx file changed or was generated.
210 // And if there were undefined citations or changes in references
211 // the .aux file is checked for signs of bibtex. Bibtex is then run
215 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
217 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
218 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
219 // WriteStatus(minib, _("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;
231 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running BibTeX."));
232 //WriteStatus(minib, _("Running BibTeX."));
233 updateBibtexDependencies(head, bibtex_info);
234 rerun |= runBibTeX(bibtex_info);
235 } else if (!had_depfile)
236 /// If we run pdflatex on the file after running latex on it,
237 /// then we do not need to run bibtex, but we do need to
238 /// insert the .bib and .bst files into the .dep-pdf file.
239 updateBibtexDependencies(head, bibtex_info);
242 // we know on this point that latex has been run once (or we just
243 // returned) and the question now is to decide if we need to run
244 // it any more. This is done by asking if any of the files in the
245 // dependency file has changed. (remember that the checksum for
246 // a given file is reported to have changed if it just was created)
247 // -> if changed or rerun == true:
248 // run latex once more and
249 // update the dependency structure
250 // -> if not changed:
251 // we does nothing at this point
253 if (rerun || head.sumchange()) {
256 lyxerr[Debug::DEPEND]
257 << "Dep. file has changed or rerun requested" << endl;
259 << "Run #" << count << endl;
262 str << _("LaTeX run number") << ' ' << count;
263 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
266 // WriteStatus(minib,
267 // string(_("LaTeX run number ")) + tostr(count));
269 scanres = scanLogFile(terr);
270 if (scanres & ERRORS) {
271 deleteFilesOnError();
272 return scanres; // return on error
275 // update the depedencies
276 deplog(head); // reads the latex log
279 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
283 // The inclusion of files generated by external programs like
284 // makeindex or bibtex might have done changes to pagenumbereing,
285 // etc. And because of this we must run the external programs
286 // again to make sure everything is redone correctly.
287 // Also there should be no need to run the external programs any
290 // run makeindex if the <file>.idx has changed or was generated.
291 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
293 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
294 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
295 //WriteStatus(minib, _("Running MakeIndex."));
296 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
300 // we will only run latex more if the log file asks for it.
301 // or if the sumchange() is true.
302 // -> rerun asked for:
304 // remake the dependency file
305 // goto 2 or return if max runs are reached.
306 // -> rerun not asked for:
307 // just return (fall out of bottom of func)
309 while ((head.sumchange() || rerun || (scanres & RERUN))
310 && count < MAX_RUN) {
311 // Yes rerun until message goes away, or until
312 // MAX_RUNS are reached.
315 lyxerr[Debug::LATEX] << "Run #" << count << endl;
318 str << _("LaTeX run number") << ' ' << count;
319 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
322 // WriteStatus(minib, string(_("LaTeX run number ")) + tostr(count));
324 scanres = scanLogFile(terr);
325 if (scanres & ERRORS) {
326 deleteFilesOnError();
327 return scanres; // return on error
334 // Write the dependencies to file.
336 lyxerr[Debug::LATEX] << "Done." << endl;
341 int LaTeX::operator()()
344 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
345 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
346 string tmp = cmd + ' ' + file + " > nul";
349 return one.startscript(Systemcalls::System, tmp);
353 bool LaTeX::runMakeIndex(string const & f)
355 lyxerr[Debug::LATEX] << "idx file has been made,"
356 " running makeindex on file "
359 // It should be possible to set the switches for makeindex
360 // sorting style and such. It would also be very convenient
361 // to be able to make style files from within LyX. This has
362 // to come for a later time. (0.13 perhaps?)
363 string tmp = "makeindex -c -q ";
366 one.startscript(Systemcalls::System, tmp);
371 vector<Aux_Info> const
372 LaTeX::scanAuxFiles(string const & file)
374 vector<Aux_Info> result;
376 result.push_back(scanAuxFile(file));
378 for (int i = 1; i < 1000; ++i) {
379 string file2 = ChangeExtension(file, "") + "." + tostr(i)
384 result.push_back(scanAuxFile(file2));
390 Aux_Info const LaTeX::scanAuxFile(string const & file)
393 result.aux_file = file;
394 scanAuxFile(file, result);
399 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
401 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
403 ifstream ifs(file.c_str());
405 LRegex reg1("\\\\citation\\{([^}]+)\\}");
406 LRegex reg2("\\\\bibdata\\{([^}]+)\\}");
407 LRegex reg3("\\\\bibstyle\\{([^}]+)\\}");
408 LRegex reg4("\\\\@input\\{([^}]+)\\}");
410 while (getline(ifs, token)) {
411 token = strip(token, '\r');
412 if (reg1.exact_match(token)) {
413 LRegex::SubMatches const & sub = reg1.exec(token);
414 string data = LSubstring(token, sub[1].first,
416 while (!data.empty()) {
418 data = split(data, citation, ',');
419 lyxerr[Debug::LATEX] << "Citation: "
421 aux_info.citations.insert(citation);
423 } else if (reg2.exact_match(token)) {
424 LRegex::SubMatches const & sub = reg2.exec(token);
425 string data = LSubstring(token, sub[1].first,
427 // data is now all the bib files separated by ','
428 // get them one by one and pass them to the helper
429 while (!data.empty()) {
431 data = split(data, database, ',');
432 database = ChangeExtension(database, "bib");
433 lyxerr[Debug::LATEX] << "Bibtex database: `"
434 << database << "'" << endl;
435 aux_info.databases.insert(database);
437 } else if (reg3.exact_match(token)) {
438 LRegex::SubMatches const & sub = reg3.exec(token);
439 string style = LSubstring(token, sub[1].first,
441 // token is now the style file
442 // pass it to the helper
443 style = ChangeExtension(style, "bst");
444 lyxerr[Debug::LATEX] << "Bibtex style: `"
445 << style << "'" << endl;
446 aux_info.styles.insert(style);
447 } else if (reg4.exact_match(token)) {
448 LRegex::SubMatches const & sub = reg4.exec(token);
449 string file2 = LSubstring(token, sub[1].first,
451 scanAuxFile(file2, aux_info);
457 void LaTeX::updateBibtexDependencies(DepTable & dep,
458 vector<Aux_Info> const & bibtex_info)
460 // Since a run of Bibtex mandates more latex runs it is ok to
461 // remove all ".bib" and ".bst" files.
462 dep.remove_files_with_extension(".bib");
463 dep.remove_files_with_extension(".bst");
464 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
466 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
467 it != bibtex_info.end(); ++it) {
468 for (set<string>::const_iterator it2 = it->databases.begin();
469 it2 != it->databases.end(); ++it2) {
470 string file = findtexfile(*it2, "bib");
472 dep.insert(file, true);
475 for (set<string>::const_iterator it2 = it->styles.begin();
476 it2 != it->styles.end(); ++it2) {
477 string file = findtexfile(*it2, "bst");
479 dep.insert(file, true);
485 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
488 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
489 it != bibtex_info.end(); ++it) {
490 if (it->databases.empty())
494 string tmp = "bibtex ";
495 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
497 one.startscript(Systemcalls::System, tmp);
499 // Return whether bibtex was run
504 int LaTeX::scanLogFile(TeXErrors & terr)
508 int retval = NO_ERRORS;
509 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
510 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
511 ifstream ifs(tmp.c_str());
514 while (getline(ifs, token)) {
515 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
520 if (prefixIs(token, "LaTeX Warning:")) {
521 // Here shall we handle different
523 retval |= LATEX_WARNING;
524 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
525 if (contains(token, "Rerun to get cross-references")) {
528 << "We should rerun." << endl;
529 } else if (contains(token, "Citation")
530 && contains(token, "on page")
531 && contains(token, "undefined")) {
534 } else if (prefixIs(token, "Package")) {
536 retval |= PACKAGE_WARNING;
537 if (contains(token, "natbib Warning:")) {
539 if (contains(token, "Citation")
540 && contains(token, "on page")
541 && contains(token, "undefined")) {
544 } else if (contains(token, "run BibTeX")) {
546 } else if (contains(token, "Rerun LaTeX") ||
547 contains(token, "Rerun to get")) {
548 // at least longtable.sty and bibtopic.sty
551 << "We should rerun." << endl;
554 } else if (prefixIs(token, "(")) {
555 if (contains(token, "Rerun LaTeX") ||
556 contains(token, "Rerun to get")) {
559 << "We should rerun." << endl;
562 } else if (prefixIs(token, "! ")) {
563 // Ok, we have something that looks like a TeX Error
564 // but what do we really have.
566 // Just get the error description:
567 string desc(token, 2);
568 if (contains(token, "LaTeX Error:"))
569 retval |= LATEX_ERROR;
574 if (!getline(ifs, tmp))
578 } while (!prefixIs(tmp, "l."));
579 if (prefixIs(tmp, "l.")) {
580 // we have a latex error
582 if (contains(desc, "Package babel Error: You haven't defined the language"))
583 retval |= ERROR_RERUN;
584 // get the line number:
586 sscanf(tmp.c_str(), "l.%d", &line);
587 // get the rest of the message:
588 string errstr(tmp, tmp.find(' '));
591 while (!contains(errstr, "l.")
593 && !prefixIs(tmp, "! ")
594 && !contains(tmp, "(job aborted")) {
600 << "line: " << line << '\n'
601 << "Desc: " << desc << '\n'
602 << "Text: " << errstr << endl;
603 if (line == last_line)
609 if (line_count <= 5) {
610 terr.insertError(line, desc, errstr);
615 // information messages, TeX warnings and other
616 // warnings we have not caught earlier.
617 if (prefixIs(token, "Overfull ")) {
618 retval |= TEX_WARNING;
619 } else if (prefixIs(token, "Underfull ")) {
620 retval |= TEX_WARNING;
621 } else if (contains(token, "Rerun to get citations")) {
622 // Natbib seems to use this.
624 } else if (contains(token, "No pages of output")) {
625 // A dvi file was not created
627 } else if (contains(token, "That makes 100 errors")) {
628 // More than 100 errors were reprted
629 retval |= TOO_MANY_ERRORS;
633 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
638 void LaTeX::deplog(DepTable & head)
640 // This function reads the LaTeX log file end extracts all the external
641 // files used by the LaTeX run. The files are then entered into the
644 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
646 LRegex reg1("\\)* *\\(([^ )]+).*");
647 LRegex reg2("File: ([^ ]+).*");
648 LRegex reg3("No file ([^ ]+)\\..*");
649 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
650 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
652 ifstream ifs(logfile.c_str());
654 // Ok, the scanning of files here is not sufficient.
655 // Sometimes files are named by "File: xxx" only
656 // So I think we should use some regexps to find files instead.
657 // "(\([^ ]+\)" should match the "(file " variant
658 // "File: \([^ ]+\)" should match the "File: file" variant
662 token = strip(token, '\r');
663 if (token.empty()) continue;
665 if (reg1.exact_match(token)) {
666 LRegex::SubMatches const & sub = reg1.exec(token);
667 foundfile = LSubstring(token, sub[1].first,
669 } else if (reg2.exact_match(token)) {
670 LRegex::SubMatches const & sub = reg2.exec(token);
671 foundfile = LSubstring(token, sub[1].first,
673 } else if (reg3.exact_match(token)) {
674 LRegex::SubMatches const & sub = reg3.exec(token);
675 foundfile = LSubstring(token, sub[1].first,
677 } else if (reg4.exact_match(token)) {
678 LRegex::SubMatches const & sub = reg4.exec(token);
679 foundfile = LSubstring(token, sub[1].first,
685 lyxerr[Debug::DEPEND] << "Found file: "
686 << foundfile << endl;
688 // Ok now we found a file.
689 // Now we should make sure that this is a file that we can
690 // access through the normal paths.
691 // We will not try any fancy search methods to
694 // (1) foundfile is an
695 // absolute path and should
697 if (AbsolutePath(foundfile)) {
698 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
699 << foundfile << endl;
700 // On initial insert we want to do the update at once
701 // since this file can not be a file generated by
703 if (FileInfo(foundfile).exist())
704 head.insert(foundfile, true);
707 // (2) foundfile is in the tmpdir
708 // insert it into head
709 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
710 if (unwanted.exact_match(foundfile)) {
711 lyxerr[Debug::DEPEND]
713 << OnlyFilename(foundfile)
714 << " in the dep file"
716 } else if (suffixIs(foundfile, ".tex")) {
717 // This is a tex file generated by LyX
718 // and latex is not likely to change this
720 lyxerr[Debug::DEPEND]
721 << "Tmpdir TeX file: "
722 << OnlyFilename(foundfile)
724 head.insert(foundfile, true);
726 lyxerr[Debug::DEPEND]
728 << OnlyFilename(foundfile)
730 head.insert(OnlyFilename(foundfile));
733 lyxerr[Debug::DEPEND]
734 << "Not a file or we are unable to find it."
738 // Make sure that the main .tex file is in the dependancy file.
739 head.insert(OnlyFilename(file), true);