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"
39 // TODO: in no particular order
40 // - get rid of the extern BufferList and the call to
41 // BufferList::updateIncludedTeXfiles, this should either
42 // be done before calling LaTeX::funcs or in a completely
44 // - the bibtex command options should be supported.
45 // - the makeindex style files should be taken care of with
46 // the dependency mechanism.
47 // - makeindex commandline options should be supported
48 // - somewhere support viewing of bibtex and makeindex log files.
49 // - we should perhaps also scan the bibtex log file
50 // - we should perhaps also scan the bibtex log file
52 extern BufferList bufferlist;
54 struct texfile_struct {
55 LaTeX::TEX_FILES file;
56 char const * extension;
60 const texfile_struct all_files[] = {
61 { LaTeX::AUX, ".aux"},
62 { LaTeX::BBL, ".bbl"},
63 { LaTeX::DVI, ".dvi"},
64 { LaTeX::GLO, ".glo"},
65 { LaTeX::IDX, ".idx"},
66 { LaTeX::IND, ".ind"},
67 { LaTeX::LOF, ".lof"},
68 { LaTeX::LOA, ".loa"},
69 { LaTeX::LOG, ".log"},
70 { LaTeX::LOT, ".lot"},
71 { LaTeX::TOC, ".toc"},
72 { LaTeX::LTX, ".ltx"},
81 void TeXErrors::insertError(int line, string const & error_desc,
82 string const & error_text)
84 Error newerr(line, error_desc, error_text);
85 errors.push_back(newerr);
92 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
93 : cmd(latex), file(f), path(p)
96 file_count = sizeof(all_files) / sizeof(texfile_struct);
98 depfile = file + ".dep";
102 void LaTeX::deleteFilesOnError() const
104 // currently just a dummy function.
106 // What files do we have to delete?
108 // This will at least make latex do all the runs
109 ::unlink(depfile.c_str());
111 // but the reason for the error might be in a generated file...
113 string ofname = OnlyFilename(file);
116 string bbl = ChangeExtension(ofname, ".bbl");
117 ::unlink(bbl.c_str());
120 string ind = ChangeExtension(ofname, ".ind");
121 ::unlink(ind.c_str());
123 // Also remove the aux file
124 string aux = ChangeExtension(ofname, ".aux");
125 ::unlink(aux.c_str());
129 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
130 // We know that this function will only be run if the lyx buffer
131 // has been changed. We also know that a newly written .tex file
132 // is always different from the previous one because of the date
133 // in it. However it seems safe to run latex (at least) on time each
134 // time the .tex file changes.
136 int scanres = LaTeX::NO_ERRORS;
137 unsigned int count = 0; // number of times run
138 num_errors = 0; // just to make sure.
139 const unsigned int MAX_RUN = 6;
140 DepTable head; // empty head
141 bool rerun = false; // rerun requested
143 // The class LaTeX does not know the temp path.
144 bufferlist.updateIncludedTeXfiles(GetCWD());
146 // Never write the depfile if an error was encountered.
149 // first check if the file dependencies exist:
150 // ->If it does exist
151 // check if any of the files mentioned in it have
152 // changed (done using a checksum).
154 // run latex once and
155 // remake the dependency file
156 // -> if not changed:
157 // just return there is nothing to do for us.
158 // ->if it doesn't exist
160 // run latex once (we need to run latex once anyway) and
161 // remake the dependency file.
163 FileInfo fi(depfile);
164 bool run_bibtex = false;
166 // Read the dep file:
168 // Update the checksums
171 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
172 if (head.sumchange()) {
174 lyxerr[Debug::DEPEND]
175 << "Dependency file has changed" << endl;
177 << "Run #" << count << endl;
178 minib->Set(string(_("LaTeX run number ")) + tostr(count));
181 scanres = scanLogFile(terr);
182 if (scanres & LaTeX::ERRORS) {
183 deleteFilesOnError();
184 return scanres; // return on error
187 run_bibtex = scanAux(head);
189 lyxerr[Debug::DEPEND]
190 << "Bibtex demands rerun" << endl;
192 lyxerr[Debug::DEPEND] << "return no_change" << endl;
193 return LaTeX::NO_CHANGE;
197 lyxerr[Debug::DEPEND]
198 << "Dependency file does not exist" << endl;
201 << "Run #" << count << endl;
202 head.insert(file, true);
203 minib->Set(string(_("LaTeX run number ")) + tostr(count));
206 scanres = scanLogFile(terr);
207 if (scanres & LaTeX::ERRORS) {
208 deleteFilesOnError();
209 return scanres; // return on error
214 // update the dependencies.
215 deplog(head); // reads the latex log
216 deptex(head); // checks for latex files
220 // At this point we must run external programs if needed.
221 // makeindex will be run if a .idx file changed or was generated.
222 // And if there were undefined citations or changes in references
223 // the .aux file is checked for signs of bibtex. Bibtex is then run
227 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
229 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
230 minib->Set(_("Running MakeIndex."));
232 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
236 if (scanres & LaTeX::UNDEF_CIT
237 || scanres & LaTeX::RERUN
239 // Here we must scan the .aux file and look for
240 // "\bibdata" and/or "\bibstyle". If one of those
241 // tags is found -> run bibtex and set rerun = true;
243 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
244 minib->Set(_("Running BibTeX."));
246 rerun = runBibTeX(OnlyFilename(ChangeExtension(file, ".aux")),
251 // we know on this point that latex has been run once (or we just
252 // returned) and the question now is to decide if we need to run
253 // it any more. This is done by asking if any of the files in the
254 // dependency file has changed. (remember that the checksum for
255 // a given file is reported to have changed if it just was created)
256 // -> if changed or rerun == true:
257 // run latex once more and
258 // update the dependency structure
259 // -> if not changed:
260 // we does nothing at this point
262 if (rerun || head.sumchange()) {
265 lyxerr[Debug::DEPEND]
266 << "Dep. file has changed or rerun requested" << endl;
268 << "Run #" << count << endl;
269 minib->Set(string(_("LaTeX run number ")) + tostr(count));
272 scanres = scanLogFile(terr);
273 if (scanres & LaTeX::ERRORS) {
274 deleteFilesOnError();
275 return scanres; // return on error
278 // update the depedencies
279 deplog(head); // reads the latex log
282 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
286 // The inclusion of files generated by external programs like
287 // makeindex or bibtex might have done changes to pagenumbereing,
288 // etc. And because of this we must run the external programs
289 // again to make sure everything is redone correctly.
290 // Also there should be no need to run the external programs any
293 // run makeindex if the <file>.idx has changed or was generated.
294 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
296 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
297 minib->Set(_("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 & LaTeX::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;
319 minib->Set(string(_("LaTeX run number ")) + tostr(count));
322 scanres = scanLogFile(terr);
323 if (scanres & LaTeX::ERRORS) {
324 deleteFilesOnError();
325 return scanres; // return on error
332 // Write the dependencies to file.
334 lyxerr[Debug::LATEX] << "Done." << endl;
339 int LaTeX::operator()()
342 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
343 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
344 string tmp = cmd + ' ' + file + " > nul";
347 return one.startscript(Systemcalls::System, tmp);
351 bool LaTeX::runMakeIndex(string const & f)
353 lyxerr[Debug::LATEX] << "idx file has been made,"
354 " running makeindex on file "
357 // It should be possible to set the switches for makeindex
358 // sorting style and such. It would also be very convenient
359 // to be able to make style files from within LyX. This has
360 // to come for a later time. (0.13 perhaps?)
361 string tmp = "makeindex -c -q ";
364 one.startscript(Systemcalls::System, tmp);
369 bool LaTeX::scanAux(DepTable & dep)
371 // if any of the bib file has changed we don't have to
372 // check the .aux file.
373 if (dep.extchanged(".bib")
374 || dep.extchanged(".bst")) return true;
376 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
377 ifstream ifs(aux.c_str());
379 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
380 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
381 while (getline(ifs, token)) {
382 if (reg1.exact_match(token)) {
383 LRegex::SubMatches sub = reg1.exec(token);
384 string data = LSubstring(token, sub[1].first,
388 b = data.find_first_of(',', 0);
390 if (b == string::npos)
393 l = data.substr( 0, b - 0);
394 data.erase(0, b + 1);
398 ChangeExtension(l, "bib"), "bib");
399 if (!full_l.empty()) {
400 if (!dep.exist(full_l))
403 } while (b != string::npos);
404 } else if (reg2.exact_match(token)) {
405 LRegex::SubMatches sub = reg2.exec(token);
406 string style = LSubstring(token, sub[1].first,
408 // token is now the style file
409 // pass it to the helper
412 ChangeExtension(style, "bst"),
414 if (!full_l.empty()) {
415 if (!dep.exist(full_l))
424 bool LaTeX::runBibTeX(string const & f, DepTable & dep)
426 // Since a run of Bibtex mandates more latex runs it is ok to
427 // remove all ".bib" and ".bst" files, it is also required to
428 // discover style and database changes.
429 dep.remove_files_with_extension(".bib");
430 dep.remove_files_with_extension(".bst");
431 ifstream ifs(f.c_str());
433 bool using_bibtex = false;
434 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
435 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
436 while (getline(ifs, token)) {
437 if (reg1.exact_match(token)) {
439 LRegex::SubMatches const & sub = reg1.exec(token);
440 string data = LSubstring(token, sub[1].first,
442 // data is now all the bib files separated by ','
443 // get them one by one and pass them to the helper
446 b = data.find_first_of(',', 0);
448 if (b == string::npos)
451 l = data.substr(0, b - 0);
452 data.erase(0, b + 1);
456 ChangeExtension(l, "bib"),
458 lyxerr[Debug::LATEX] << "Bibtex database: `"
459 << full_l << "'" << endl;
460 if (!full_l.empty()) {
461 // add full_l to the dep file.
462 dep.insert(full_l, true);
464 } while (b != string::npos);
465 } else if (reg2.exact_match(token)) {
467 LRegex::SubMatches const & sub = reg2.exec(token);
468 string style = LSubstring(token, sub[1].first,
470 // token is now the style file
471 // pass it to the helper
474 ChangeExtension(style, "bst"),
476 lyxerr[Debug::LATEX] << "Bibtex style: `"
477 << full_l << "'" << endl;
478 if (!full_l.empty()) {
479 // add full_l to the dep file.
480 dep.insert(full_l, true);
486 string tmp = "bibtex ";
487 tmp += OnlyFilename(ChangeExtension(file, string()));
489 one.startscript(Systemcalls::System, tmp);
492 // bibtex was not run.
497 int LaTeX::scanLogFile(TeXErrors & terr)
501 int retval = NO_ERRORS;
502 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
503 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
504 ifstream ifs(tmp.c_str());
507 while (getline(ifs, token)) {
508 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
513 if (prefixIs(token, "LaTeX Warning:")) {
514 // Here shall we handle different
516 retval |= LATEX_WARNING;
517 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
518 if (contains(token, "Rerun to get cross-references")) {
521 << "We should rerun." << endl;
522 } else if (contains(token, "Citation")
523 && contains(token, "on page")
524 && contains(token, "undefined")) {
527 } else if (prefixIs(token, "Package")) {
529 retval |= PACKAGE_WARNING;
530 if (contains(token, "natbib Warning:")) {
532 if (contains(token, "Citation")
533 && contains(token, "on page")
534 && contains(token, "undefined")) {
537 } else if (contains(token, "Rerun LaTeX.")) {
538 // at least longtable.sty might use this.
541 } else if (prefixIs(token, "! ")) {
542 // Ok, we have something that looks like a TeX Error
543 // but what do we really have.
545 // Just get the error description:
546 string desc(token, 2);
547 if (contains(token, "LaTeX Error:"))
548 retval |= LATEX_ERROR;
553 if (!getline(ifs, tmp))
557 } while (!prefixIs(tmp, "l."));
558 if (prefixIs(tmp, "l.")) {
559 // we have a latex error
561 // get the line number:
563 sscanf(tmp.c_str(), "l.%d", &line);
564 // get the rest of the message:
565 string errstr(tmp, tmp.find(' '));
568 while (!contains(errstr, "l.")
570 && !prefixIs(tmp, "! ")
571 && !contains(tmp, "(job aborted")) {
577 << "line: " << line << '\n'
578 << "Desc: " << desc << '\n'
579 << "Text: " << errstr << endl;
580 if (line == last_line)
586 if (line_count <= 5) {
587 terr.insertError(line, desc, errstr);
592 // information messages, TeX warnings and other
593 // warnings we have not caught earlier.
594 if (prefixIs(token, "Overfull ")) {
595 retval |= TEX_WARNING;
596 } else if (prefixIs(token, "Underfull ")) {
597 retval |= TEX_WARNING;
598 } else if (contains(token, "Rerun to get citations")) {
599 // Natbib seems to use this.
601 } else if (contains(token, "No pages of output")) {
602 // A dvi file was not created
604 } else if (contains(token, "That makes 100 errors")) {
605 // More than 100 errors were reprted
606 retval |= TOO_MANY_ERRORS;
610 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
615 void LaTeX::deplog(DepTable & head)
617 // This function reads the LaTeX log file end extracts all the external
618 // files used by the LaTeX run. The files are then entered into the
621 string logfile = OnlyFilename(ChangeExtension(file, ".log"));
623 LRegex reg1(")* *\\(([^ ]+).*");
624 LRegex reg2("File: ([^ ]+).*");
626 ifstream ifs(logfile.c_str());
628 // Ok, the scanning of files here is not sufficient.
629 // Sometimes files are named by "File: xxx" only
630 // So I think we should use some regexps to find files instead.
631 // "(\([^ ]+\)" should match the "(file " variant
632 // "File: \([^ ]+\)" should match the "File: file" variant
636 if (token.empty()) continue;
638 if (reg1.exact_match(token)) {
639 LRegex::SubMatches const & sub = reg1.exec(token);
640 foundfile = LSubstring(token, sub[1].first,
642 } else if (reg2.exact_match(token)) {
643 LRegex::SubMatches const & sub = reg2.exec(token);
644 foundfile = LSubstring(token, sub[1].first,
650 lyxerr[Debug::DEPEND] << "Found file: "
651 << foundfile << endl;
653 // Ok now we found a file.
654 // Now we should make sure that this is a file that we can
655 // access through the normal paths.
656 // We will not try any fance search methods to
659 // (1) foundfile is an
660 // absolute path and should
662 if (AbsolutePath(foundfile)) {
663 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
664 << foundfile << endl;
665 // On inital insert we want to do the update at once
666 // since this file can not be a file generated by
668 head.insert(foundfile, true);
672 // (2) foundfile is in the tmpdir
673 // insert it into head
674 if (FileInfo(OnlyFilename(foundfile)).exist()) {
675 if (suffixIs(foundfile, ".aux")) {
676 lyxerr[Debug::DEPEND]
678 << OnlyFilename(foundfile)
679 << " in the dep file"
681 } else if (suffixIs(foundfile, ".tex")) {
682 // This is a tex file generated by LyX
683 // and latex is not likely to change this
685 lyxerr[Debug::DEPEND]
686 << "Tmpdir TeX file: "
687 << OnlyFilename(foundfile)
689 head.insert(foundfile, true);
691 lyxerr[Debug::DEPEND]
693 << OnlyFilename(foundfile)
695 head.insert(OnlyFilename(foundfile));
699 lyxerr[Debug::DEPEND]
700 << "Not a file or we are unable to find it."
706 void LaTeX::deptex(DepTable & head)
708 int except = AUX|LOG|DVI|BBL|IND|GLO;
711 for (int i = 0; i < file_count; ++i) {
712 if (!(all_files[i].file & except)) {
713 tmp = OnlyFilename(ChangeExtension(file,
714 all_files[i].extension));
715 lyxerr[Debug::DEPEND] << "deptex: " << tmp << endl;
716 if (fi.newFile(tmp).exist())