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...
114 string bbl = ChangeExtension(file, ".bbl", true);
115 ::unlink(bbl.c_str());
118 string ind = ChangeExtension(file, ".ind", true);
119 ::unlink(ind.c_str());
121 // Also remove the aux file
122 string aux = ChangeExtension(file, ".aux", true);
123 ::unlink(aux.c_str());
127 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
128 // We know that this function will only be run if the lyx buffer
129 // has been changed. We also know that a newly written .tex file
130 // is always different from the previous one because of the date
131 // in it. However it seems safe to run latex (at least) on time each
132 // time the .tex file changes.
134 int scanres = LaTeX::NO_ERRORS;
135 unsigned int count = 0; // number of times run
136 num_errors = 0; // just to make sure.
137 const unsigned int MAX_RUN = 6;
138 DepTable head; // empty head
139 bool rerun = false; // rerun requested
141 // The class LaTeX does not know the temp path.
142 bufferlist.updateIncludedTeXfiles(GetCWD());
144 // Never write the depfile if an error was encountered.
147 // first check if the file dependencies exist:
148 // ->If it does exist
149 // check if any of the files mentioned in it have
150 // changed (done using a checksum).
152 // run latex once and
153 // remake the dependency file
154 // -> if not changed:
155 // just return there is nothing to do for us.
156 // ->if it doesn't exist
158 // run latex once (we need to run latex once anyway) and
159 // remake the dependency file.
161 FileInfo fi(depfile);
162 bool run_bibtex = false;
164 // Read the dep file:
166 // Update the checksums
169 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
170 if (head.sumchange()) {
172 lyxerr[Debug::DEPEND]
173 << "Dependency file has changed" << endl;
175 << "Run #" << count << endl;
176 minib->Set(string(_("LaTeX run number ")) + tostr(count));
179 scanres = scanLogFile(terr);
180 if (scanres & LaTeX::ERRORS) {
181 deleteFilesOnError();
182 return scanres; // return on error
185 run_bibtex = scanAux(head);
187 lyxerr[Debug::DEPEND]
188 << "Bibtex demands rerun" << endl;
190 lyxerr[Debug::DEPEND] << "return no_change" << endl;
191 return LaTeX::NO_CHANGE;
195 lyxerr[Debug::DEPEND]
196 << "Dependency file does not exist" << endl;
199 << "Run #" << count << endl;
200 head.insert(file, true);
201 minib->Set(string(_("LaTeX run number ")) + tostr(count));
204 scanres = scanLogFile(terr);
205 if (scanres & LaTeX::ERRORS) {
206 deleteFilesOnError();
207 return scanres; // return on error
212 // update the dependencies.
213 deplog(head); // reads the latex log
214 deptex(head); // checks for latex files
218 // At this point we must run external programs if needed.
219 // makeindex will be run if a .idx file changed or was generated.
220 // And if there were undefined citations or changes in references
221 // the .aux file is checked for signs of bibtex. Bibtex is then run
225 if (head.haschanged(ChangeExtension(file, ".idx", true))) {
227 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
228 minib->Set(_("Running MakeIndex."));
230 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
234 if (scanres & LaTeX::UNDEF_CIT
235 || scanres & LaTeX::RERUN
237 // Here we must scan the .aux file and look for
238 // "\bibdata" and/or "\bibstyle". If one of those
239 // tags is found -> run bibtex and set rerun = true;
241 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
242 minib->Set(_("Running BibTeX."));
244 rerun = runBibTeX(ChangeExtension(file, ".aux", true), head);
248 // we know on this point that latex has been run once (or we just
249 // returned) and the question now is to decide if we need to run
250 // it any more. This is done by asking if any of the files in the
251 // dependency file has changed. (remember that the checksum for
252 // a given file is reported to have changed if it just was created)
253 // -> if changed or rerun == true:
254 // run latex once more and
255 // update the dependency structure
256 // -> if not changed:
257 // we does nothing at this point
259 if (rerun || head.sumchange()) {
262 lyxerr[Debug::DEPEND]
263 << "Dep. file has changed or rerun requested" << endl;
265 << "Run #" << count << endl;
266 minib->Set(string(_("LaTeX run number ")) + tostr(count));
269 scanres = scanLogFile(terr);
270 if (scanres & LaTeX::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(ChangeExtension(file, ".idx", true))) {
293 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
294 minib->Set(_("Running MakeIndex."));
296 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
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 & LaTeX::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;
316 minib->Set(string(_("LaTeX run number ")) + tostr(count));
319 scanres = scanLogFile(terr);
320 if (scanres & LaTeX::ERRORS) {
321 deleteFilesOnError();
322 return scanres; // return on error
329 // Write the dependencies to file.
331 lyxerr[Debug::LATEX] << "Done." << endl;
336 int LaTeX::operator()()
339 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
340 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
341 string tmp = cmd + ' ' + file + " > nul";
344 return one.startscript(Systemcalls::System, tmp);
348 bool LaTeX::runMakeIndex(string const & f)
350 lyxerr[Debug::LATEX] << "idx file has been made,"
351 " running makeindex on file "
354 // It should be possible to set the switches for makeindex
355 // sorting style and such. It would also be very convenient
356 // to be able to make style files from within LyX. This has
357 // to come for a later time. (0.13 perhaps?)
358 string tmp = "makeindex -c -q ";
361 one.startscript(Systemcalls::System, tmp);
366 bool LaTeX::scanAux(DepTable & dep)
368 // if any of the bib file has changed we don't have to
369 // check the .aux file.
370 if (dep.extchanged(".bib")
371 || dep.extchanged(".bst")) return true;
373 string aux = ChangeExtension(file, ".aux", true);
374 ifstream ifs(aux.c_str());
376 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
377 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
378 while (getline(ifs, token)) {
379 if (reg1.exact_match(token)) {
380 LRegex::SubMatches sub = reg1.exec(token);
381 string data = LSubstring(token, sub[1].first,
385 b = data.find_first_of(',', 0);
387 if (b == string::npos)
390 l = data.substr( 0, b - 0);
391 data.erase(0, b + 1);
395 ChangeExtension(l, "bib", false), "bib");
396 if (!full_l.empty()) {
397 if (!dep.exist(full_l))
400 } while (b != string::npos);
401 } else if (reg2.exact_match(token)) {
402 LRegex::SubMatches sub = reg2.exec(token);
403 string style = LSubstring(token, sub[1].first,
405 // token is now the style file
406 // pass it to the helper
409 ChangeExtension(style, "bst", false),
411 if (!full_l.empty()) {
412 if (!dep.exist(full_l))
421 bool LaTeX::runBibTeX(string const & f, DepTable & dep)
423 // Since a run of Bibtex mandates more latex runs it is ok to
424 // remove all ".bib" and ".bst" files, it is also required to
425 // discover style and database changes.
426 dep.remove_files_with_extension(".bib");
427 dep.remove_files_with_extension(".bst");
428 ifstream ifs(f.c_str());
430 bool using_bibtex = false;
431 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
432 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
433 while (getline(ifs, token)) {
434 if (reg1.exact_match(token)) {
436 LRegex::SubMatches const & sub = reg1.exec(token);
437 string data = LSubstring(token, sub[1].first,
439 // data is now all the bib files separated by ','
440 // get them one by one and pass them to the helper
443 b = data.find_first_of(',', 0);
445 if (b == string::npos)
448 l = data.substr(0, b - 0);
449 data.erase(0, b + 1);
453 ChangeExtension(l, "bib", false),
455 lyxerr[Debug::LATEX] << "Bibtex database: `"
456 << full_l << "'" << endl;
457 if (!full_l.empty()) {
458 // add full_l to the dep file.
459 dep.insert(full_l, true);
461 } while (b != string::npos);
462 } else if (reg2.exact_match(token)) {
464 LRegex::SubMatches const & sub = reg2.exec(token);
465 string style = LSubstring(token, sub[1].first,
467 // token is now the style file
468 // pass it to the helper
471 ChangeExtension(style, "bst", false),
473 lyxerr[Debug::LATEX] << "Bibtex style: `"
474 << full_l << "'" << endl;
475 if (!full_l.empty()) {
476 // add full_l to the dep file.
477 dep.insert(full_l, true);
483 string tmp = "bibtex ";
484 tmp += ChangeExtension(file, string(), true);
486 one.startscript(Systemcalls::System, tmp);
489 // bibtex was not run.
494 int LaTeX::scanLogFile(TeXErrors & terr)
498 int retval = NO_ERRORS;
499 string tmp = ChangeExtension(file, ".log", true);
500 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
501 ifstream ifs(tmp.c_str());
504 while (getline(ifs, token)) {
505 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
510 if (prefixIs(token, "LaTeX Warning:")) {
511 // Here shall we handle different
513 retval |= LATEX_WARNING;
514 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
515 if (contains(token, "Rerun to get cross-references")) {
518 << "We should rerun." << endl;
519 } else if (contains(token, "Citation")
520 && contains(token, "on page")
521 && contains(token, "undefined")) {
524 } else if (prefixIs(token, "Package")) {
526 retval |= PACKAGE_WARNING;
527 if (contains(token, "natbib Warning:")) {
529 if (contains(token, "Citation")
530 && contains(token, "on page")
531 && contains(token, "undefined")) {
534 } else if (contains(token, "Rerun LaTeX.")) {
535 // at least longtable.sty might use this.
538 } else if (prefixIs(token, "! ")) {
539 // Ok, we have something that looks like a TeX Error
540 // but what do we really have.
542 // Just get the error description:
543 string desc(token, 2);
544 if (contains(token, "LaTeX Error:"))
545 retval |= LATEX_ERROR;
550 if (!getline(ifs, tmp))
554 } while (!prefixIs(tmp, "l."));
555 if (prefixIs(tmp, "l.")) {
556 // we have a latex error
558 // get the line number:
560 sscanf(tmp.c_str(), "l.%d", &line);
561 // get the rest of the message:
562 string errstr(tmp, tmp.find(' '));
565 while (!contains(errstr, "l.")
567 && !prefixIs(tmp, "! ")
568 && !contains(tmp, "(job aborted")) {
574 << "line: " << line << '\n'
575 << "Desc: " << desc << '\n'
576 << "Text: " << errstr << endl;
577 if (line == last_line)
583 if (line_count <= 5) {
584 terr.insertError(line, desc, errstr);
589 // information messages, TeX warnings and other
590 // warnings we have not caught earlier.
591 if (prefixIs(token, "Overfull ")) {
592 retval |= TEX_WARNING;
593 } else if (prefixIs(token, "Underfull ")) {
594 retval |= TEX_WARNING;
595 } else if (contains(token, "Rerun to get citations")) {
596 // Natbib seems to use this.
598 } else if (contains(token, "No pages of output")) {
599 // A dvi file was not created
601 } else if (contains(token, "That makes 100 errors")) {
602 // More than 100 errors were reprted
603 retval |= TOO_MANY_ERRORS;
607 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
612 void LaTeX::deplog(DepTable & head)
614 // This function reads the LaTeX log file end extracts all the external
615 // files used by the LaTeX run. The files are then entered into the
618 string logfile = ChangeExtension(file, ".log", true);
620 ifstream ifs(logfile.c_str());
622 // Now we read chars until we find a '('
629 // We now have c == '(', we now read the the sequence of
630 // chars until reaching EOL, ' ' or ')' and put that
634 if (c == '\n' || c == ' ' || c == ')')
638 lyxerr[Debug::DEPEND] << "Found file: "
639 << foundfile << endl;
641 // Ok now we found a file.
642 // Now we should make sure that
643 // this is a file that we can
644 // access through the normal
646 // (1) foundfile is an
647 // absolute path and should
649 if (AbsolutePath(foundfile)) {
650 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
651 << foundfile << endl;
652 // On inital insert we want to do the update at once
653 // since this file can not be a file generated by
655 head.insert(foundfile, true);
659 // (2) foundfile is in the tmpdir
660 // insert it into head
661 if (FileInfo(OnlyFilename(foundfile)).exist()) {
662 if (suffixIs(foundfile, ".aux")) {
663 lyxerr[Debug::DEPEND] << "We don't want "
664 << OnlyFilename(foundfile)
665 << " in the dep file"
667 } else if (suffixIs(foundfile, ".tex")) {
668 // This is a tex file generated by LyX
669 // and latex is not likely to change this
671 lyxerr[Debug::DEPEND] << "Tmpdir TeX file: "
672 << OnlyFilename(foundfile)
674 head.insert(foundfile, true);
676 lyxerr[Debug::DEPEND] << "In tmpdir file:"
677 << OnlyFilename(foundfile)
679 head.insert(OnlyFilename(foundfile));
683 lyxerr[Debug::DEPEND]
684 << "Not a file or we are unable to find it."
690 void LaTeX::deptex(DepTable & head)
692 int except = AUX|LOG|DVI|BBL|IND|GLO;
695 for (int i = 0; i < file_count; ++i) {
696 if (!(all_files[i].file & except)) {
697 tmp = ChangeExtension(file,
698 all_files[i].extension,
700 lyxerr[Debug::DEPEND] << "deptex: " << tmp << endl;
701 if (fi.newFile(tmp).exist())