1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
5 * Copyright 1995 Matthias Ettrich
6 * Copyright 1995-2000 The LyX Team.
8 * This file is Copyright 1996-2000
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 "bufferlist.h"
32 #include "minibuffer.h"
34 #include "lyx_gui_misc.h"
42 // TODO: in no particular order
43 // - get rid of the extern BufferList and the call to
44 // BufferList::updateIncludedTeXfiles, this should either
45 // be done before calling LaTeX::funcs or in a completely
47 // - the bibtex command options should be supported.
48 // - the makeindex style files should be taken care of with
49 // the dependency mechanism.
50 // - makeindex commandline options should be supported
51 // - somewhere support viewing of bibtex and makeindex log files.
52 // - we should perhaps also scan the bibtex log file
53 // - we should perhaps also scan the bibtex log file
55 extern BufferList bufferlist;
61 void TeXErrors::insertError(int line, string const & error_desc,
62 string const & error_text)
64 Error newerr(line, error_desc, error_text);
65 errors.push_back(newerr);
72 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
73 : cmd(latex), file(f), path(p)
76 depfile = file + ".dep";
77 if (prefixIs(cmd, "pdf")) // Do we use pdflatex ?
82 void LaTeX::deleteFilesOnError() const
84 // currently just a dummy function.
86 // What files do we have to delete?
88 // This will at least make latex do all the runs
91 // but the reason for the error might be in a generated file...
93 string ofname = OnlyFilename(file);
96 string bbl = ChangeExtension(ofname, ".bbl");
100 string ind = ChangeExtension(ofname, ".ind");
103 // Also remove the aux file
104 string aux = ChangeExtension(ofname, ".aux");
109 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
110 // We know that this function will only be run if the lyx buffer
111 // has been changed. We also know that a newly written .tex file
112 // is always different from the previous one because of the date
113 // in it. However it seems safe to run latex (at least) on time each
114 // time the .tex file changes.
116 int scanres = NO_ERRORS;
117 unsigned int count = 0; // number of times run
118 num_errors = 0; // just to make sure.
119 const unsigned int MAX_RUN = 6;
120 DepTable head; // empty head
121 bool rerun = false; // rerun requested
123 // The class LaTeX does not know the temp path.
124 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
126 // Never write the depfile if an error was encountered.
129 // first check if the file dependencies exist:
130 // ->If it does exist
131 // check if any of the files mentioned in it have
132 // changed (done using a checksum).
134 // run latex once and
135 // remake the dependency file
136 // -> if not changed:
137 // just return there is nothing to do for us.
138 // ->if it doesn't exist
140 // run latex once (we need to run latex once anyway) and
141 // remake the dependency file.
144 FileInfo fi(depfile);
145 bool had_depfile = fi.exist();
146 bool run_bibtex = false;
147 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
150 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
151 // Read the dep file:
153 // Update the checksums
155 if (!head.sumchange()) {
156 lyxerr[Debug::DEPEND] << "return no_change" << endl;
159 lyxerr[Debug::DEPEND]
160 << "Dependency file has changed" << endl;
162 if (head.extchanged(".bib") || head.extchanged(".bst"))
165 lyxerr[Debug::DEPEND]
166 << "Dependency file does not exist" << endl;
168 /// We scan the aux file even when had_depfile = false,
169 /// because we can run pdflatex on the file after running latex on it,
170 /// in which case we will not need to run bibtex again.
171 vector<Aux_Info> bibtex_info_old;
173 bibtex_info_old = scanAuxFiles(aux_file);
176 lyxerr[Debug::LATEX] << "Run #" << count << endl;
177 WriteStatus(minib, string(_("LaTeX run number ")) + tostr(count));
179 scanres = scanLogFile(terr);
180 if (scanres & ERROR_RERUN) {
181 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
183 scanres = scanLogFile(terr);
186 if (scanres & ERRORS) {
187 deleteFilesOnError();
188 return scanres; // return on error
191 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
192 if (!run_bibtex && bibtex_info_old != bibtex_info)
195 // update the dependencies.
196 deplog(head); // reads the latex log
200 // At this point we must run external programs if needed.
201 // makeindex will be run if a .idx file changed or was generated.
202 // And if there were undefined citations or changes in references
203 // the .aux file is checked for signs of bibtex. Bibtex is then run
207 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
209 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
210 WriteStatus(minib, _("Running MakeIndex."));
211 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
215 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
216 if (scanres & UNDEF_CIT || run_bibtex) {
217 // Here we must scan the .aux file and look for
218 // "\bibdata" and/or "\bibstyle". If one of those
219 // tags is found -> run bibtex and set rerun = true;
221 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
222 WriteStatus(minib, _("Running BibTeX."));
223 updateBibtexDependencies(head, bibtex_info);
224 rerun |= runBibTeX(bibtex_info);
225 } else if (!had_depfile)
226 /// If we run pdflatex on the file after running latex on it,
227 /// then we do not need to run bibtex, but we do need to
228 /// insert the .bib and .bst files into the .dep-pdf file.
229 updateBibtexDependencies(head, bibtex_info);
232 // we know on this point that latex has been run once (or we just
233 // returned) and the question now is to decide if we need to run
234 // it any more. This is done by asking if any of the files in the
235 // dependency file has changed. (remember that the checksum for
236 // a given file is reported to have changed if it just was created)
237 // -> if changed or rerun == true:
238 // run latex once more and
239 // update the dependency structure
240 // -> if not changed:
241 // we does nothing at this point
243 if (rerun || head.sumchange()) {
246 lyxerr[Debug::DEPEND]
247 << "Dep. file has changed or rerun requested" << endl;
249 << "Run #" << count << endl;
251 string(_("LaTeX run number ")) + tostr(count));
253 scanres = scanLogFile(terr);
254 if (scanres & ERRORS) {
255 deleteFilesOnError();
256 return scanres; // return on error
259 // update the depedencies
260 deplog(head); // reads the latex log
263 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
267 // The inclusion of files generated by external programs like
268 // makeindex or bibtex might have done changes to pagenumbereing,
269 // etc. And because of this we must run the external programs
270 // again to make sure everything is redone correctly.
271 // Also there should be no need to run the external programs any
274 // run makeindex if the <file>.idx has changed or was generated.
275 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
277 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
278 WriteStatus(minib, _("Running MakeIndex."));
279 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
283 // we will only run latex more if the log file asks for it.
284 // or if the sumchange() is true.
285 // -> rerun asked for:
287 // remake the dependency file
288 // goto 2 or return if max runs are reached.
289 // -> rerun not asked for:
290 // just return (fall out of bottom of func)
292 while ((head.sumchange() || rerun || (scanres & RERUN))
293 && count < MAX_RUN) {
294 // Yes rerun until message goes away, or until
295 // MAX_RUNS are reached.
298 lyxerr[Debug::LATEX] << "Run #" << count << endl;
299 WriteStatus(minib, string(_("LaTeX run number ")) + tostr(count));
301 scanres = scanLogFile(terr);
302 if (scanres & ERRORS) {
303 deleteFilesOnError();
304 return scanres; // return on error
311 // Write the dependencies to file.
313 lyxerr[Debug::LATEX] << "Done." << endl;
318 int LaTeX::operator()()
321 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
322 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
323 string tmp = cmd + ' ' + file + " > nul";
326 return one.startscript(Systemcalls::System, tmp);
330 bool LaTeX::runMakeIndex(string const & f)
332 lyxerr[Debug::LATEX] << "idx file has been made,"
333 " running makeindex on file "
336 // It should be possible to set the switches for makeindex
337 // sorting style and such. It would also be very convenient
338 // to be able to make style files from within LyX. This has
339 // to come for a later time. (0.13 perhaps?)
340 string tmp = "makeindex -c -q ";
343 one.startscript(Systemcalls::System, tmp);
348 vector<Aux_Info> const
349 LaTeX::scanAuxFiles(string const & file)
351 vector<Aux_Info> result;
353 result.push_back(scanAuxFile(file));
355 for (int i = 1; i < 1000; ++i) {
356 string file2 = ChangeExtension(file, "") + "." + tostr(i)
361 result.push_back(scanAuxFile(file2));
367 Aux_Info const LaTeX::scanAuxFile(string const & file)
370 result.aux_file = file;
371 scanAuxFile(file, result);
376 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
378 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
380 ifstream ifs(file.c_str());
382 LRegex reg1("\\\\citation\\{([^}]+)\\}");
383 LRegex reg2("\\\\bibdata\\{([^}]+)\\}");
384 LRegex reg3("\\\\bibstyle\\{([^}]+)\\}");
385 LRegex reg4("\\\\@input\\{([^}]+)\\}");
387 while (getline(ifs, token)) {
388 if (reg1.exact_match(token)) {
389 LRegex::SubMatches const & sub = reg1.exec(token);
390 string data = LSubstring(token, sub[1].first,
392 while (!data.empty()) {
394 data = split(data, citation, ',');
395 lyxerr[Debug::LATEX] << "Citation: "
397 aux_info.citations.insert(citation);
399 } else if (reg2.exact_match(token)) {
400 LRegex::SubMatches const & sub = reg2.exec(token);
401 string data = LSubstring(token, sub[1].first,
403 // data is now all the bib files separated by ','
404 // get them one by one and pass them to the helper
405 while (!data.empty()) {
407 data = split(data, database, ',');
408 database = ChangeExtension(database, "bib");
409 lyxerr[Debug::LATEX] << "Bibtex database: `"
410 << database << "'" << endl;
411 aux_info.databases.insert(database);
413 } else if (reg3.exact_match(token)) {
414 LRegex::SubMatches const & sub = reg3.exec(token);
415 string style = LSubstring(token, sub[1].first,
417 // token is now the style file
418 // pass it to the helper
419 style = ChangeExtension(style, "bst");
420 lyxerr[Debug::LATEX] << "Bibtex style: `"
421 << style << "'" << endl;
422 aux_info.styles.insert(style);
423 } else if (reg4.exact_match(token)) {
424 LRegex::SubMatches const & sub = reg4.exec(token);
425 string file2 = LSubstring(token, sub[1].first,
427 scanAuxFile(file2, aux_info);
433 void LaTeX::updateBibtexDependencies(DepTable & dep,
434 vector<Aux_Info> const & bibtex_info)
436 // Since a run of Bibtex mandates more latex runs it is ok to
437 // remove all ".bib" and ".bst" files.
438 dep.remove_files_with_extension(".bib");
439 dep.remove_files_with_extension(".bst");
440 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
442 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
443 it != bibtex_info.end(); ++it) {
444 for (set<string>::const_iterator it2 = it->databases.begin();
445 it2 != it->databases.end(); ++it2) {
446 string file = findtexfile(*it2, "bib");
448 dep.insert(file, true);
451 for (set<string>::const_iterator it2 = it->styles.begin();
452 it2 != it->styles.end(); ++it2) {
453 string file = findtexfile(*it2, "bst");
455 dep.insert(file, true);
461 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
464 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
465 it != bibtex_info.end(); ++it) {
466 if (it->databases.empty())
470 string tmp = "bibtex ";
471 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
473 one.startscript(Systemcalls::System, tmp);
475 // Return whether bibtex was run
480 int LaTeX::scanLogFile(TeXErrors & terr)
484 int retval = NO_ERRORS;
485 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
486 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
487 ifstream ifs(tmp.c_str());
490 while (getline(ifs, token)) {
491 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
496 if (prefixIs(token, "LaTeX Warning:")) {
497 // Here shall we handle different
499 retval |= LATEX_WARNING;
500 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
501 if (contains(token, "Rerun to get cross-references")) {
504 << "We should rerun." << endl;
505 } else if (contains(token, "Citation")
506 && contains(token, "on page")
507 && contains(token, "undefined")) {
510 } else if (prefixIs(token, "Package")) {
512 retval |= PACKAGE_WARNING;
513 if (contains(token, "natbib Warning:")) {
515 if (contains(token, "Citation")
516 && contains(token, "on page")
517 && contains(token, "undefined")) {
520 } else if (contains(token, "run BibTeX")) {
522 } else if (contains(token, "Rerun LaTeX.")) {
523 // at least longtable.sty might use this.
526 } else if (prefixIs(token, "! ")) {
527 // Ok, we have something that looks like a TeX Error
528 // but what do we really have.
530 // Just get the error description:
531 string desc(token, 2);
532 if (contains(token, "LaTeX Error:"))
533 retval |= LATEX_ERROR;
538 if (!getline(ifs, tmp))
542 } while (!prefixIs(tmp, "l."));
543 if (prefixIs(tmp, "l.")) {
544 // we have a latex error
546 if (contains(desc, "Package babel Error: You haven't defined the language"))
547 retval |= ERROR_RERUN;
548 // get the line number:
550 sscanf(tmp.c_str(), "l.%d", &line);
551 // get the rest of the message:
552 string errstr(tmp, tmp.find(' '));
555 while (!contains(errstr, "l.")
557 && !prefixIs(tmp, "! ")
558 && !contains(tmp, "(job aborted")) {
564 << "line: " << line << '\n'
565 << "Desc: " << desc << '\n'
566 << "Text: " << errstr << endl;
567 if (line == last_line)
573 if (line_count <= 5) {
574 terr.insertError(line, desc, errstr);
579 // information messages, TeX warnings and other
580 // warnings we have not caught earlier.
581 if (prefixIs(token, "Overfull ")) {
582 retval |= TEX_WARNING;
583 } else if (prefixIs(token, "Underfull ")) {
584 retval |= TEX_WARNING;
585 } else if (contains(token, "Rerun to get citations")) {
586 // Natbib seems to use this.
588 } else if (contains(token, "No pages of output")) {
589 // A dvi file was not created
591 } else if (contains(token, "That makes 100 errors")) {
592 // More than 100 errors were reprted
593 retval |= TOO_MANY_ERRORS;
597 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
602 void LaTeX::deplog(DepTable & head)
604 // This function reads the LaTeX log file end extracts all the external
605 // files used by the LaTeX run. The files are then entered into the
608 string logfile = OnlyFilename(ChangeExtension(file, ".log"));
610 LRegex reg1(")* *\\(([^ \\)]+).*");
611 LRegex reg2("File: ([^ ]+).*");
612 LRegex reg3("No file ([^ ]+)\\..*");
613 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
614 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
616 ifstream ifs(logfile.c_str());
618 // Ok, the scanning of files here is not sufficient.
619 // Sometimes files are named by "File: xxx" only
620 // So I think we should use some regexps to find files instead.
621 // "(\([^ ]+\)" should match the "(file " variant
622 // "File: \([^ ]+\)" should match the "File: file" variant
626 if (token.empty()) continue;
628 if (reg1.exact_match(token)) {
629 LRegex::SubMatches const & sub = reg1.exec(token);
630 foundfile = LSubstring(token, sub[1].first,
632 } else if (reg2.exact_match(token)) {
633 LRegex::SubMatches const & sub = reg2.exec(token);
634 foundfile = LSubstring(token, sub[1].first,
636 } else if (reg3.exact_match(token)) {
637 LRegex::SubMatches const & sub = reg3.exec(token);
638 foundfile = LSubstring(token, sub[1].first,
640 } else if (reg4.exact_match(token)) {
641 LRegex::SubMatches const & sub = reg4.exec(token);
642 foundfile = LSubstring(token, sub[1].first,
648 lyxerr[Debug::DEPEND] << "Found file: "
649 << foundfile << endl;
651 // Ok now we found a file.
652 // Now we should make sure that this is a file that we can
653 // access through the normal paths.
654 // We will not try any fancy search methods to
657 // (1) foundfile is an
658 // absolute path and should
660 if (AbsolutePath(foundfile)) {
661 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
662 << foundfile << endl;
663 // On initial insert we want to do the update at once
664 // since this file can not be a file generated by
666 head.insert(foundfile, true);
669 // (2) foundfile is in the tmpdir
670 // insert it into head
671 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
672 if (unwanted.exact_match(foundfile)) {
673 lyxerr[Debug::DEPEND]
675 << OnlyFilename(foundfile)
676 << " in the dep file"
678 } else if (suffixIs(foundfile, ".tex")) {
679 // This is a tex file generated by LyX
680 // and latex is not likely to change this
682 lyxerr[Debug::DEPEND]
683 << "Tmpdir TeX file: "
684 << OnlyFilename(foundfile)
686 head.insert(foundfile, true);
688 lyxerr[Debug::DEPEND]
690 << OnlyFilename(foundfile)
692 head.insert(OnlyFilename(foundfile));
695 lyxerr[Debug::DEPEND]
696 << "Not a file or we are unable to find it."