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::TOC, ".cot"}, // Hebrew TOC
73 { LaTeX::LTX, ".ltx"},
82 void TeXErrors::insertError(int line, string const & error_desc,
83 string const & error_text)
85 Error newerr(line, error_desc, error_text);
86 errors.push_back(newerr);
93 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
94 : cmd(latex), file(f), path(p)
97 file_count = sizeof(all_files) / sizeof(texfile_struct);
99 depfile = file + ".dep";
103 void LaTeX::deleteFilesOnError() const
105 // currently just a dummy function.
107 // What files do we have to delete?
109 // This will at least make latex do all the runs
110 ::unlink(depfile.c_str());
112 // but the reason for the error might be in a generated file...
114 string ofname = OnlyFilename(file);
117 string bbl = ChangeExtension(ofname, ".bbl");
118 ::unlink(bbl.c_str());
121 string ind = ChangeExtension(ofname, ".ind");
122 ::unlink(ind.c_str());
124 // Also remove the aux file
125 string aux = ChangeExtension(ofname, ".aux");
126 ::unlink(aux.c_str());
130 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
131 // We know that this function will only be run if the lyx buffer
132 // has been changed. We also know that a newly written .tex file
133 // is always different from the previous one because of the date
134 // in it. However it seems safe to run latex (at least) on time each
135 // time the .tex file changes.
137 int scanres = LaTeX::NO_ERRORS;
138 unsigned int count = 0; // number of times run
139 num_errors = 0; // just to make sure.
140 const unsigned int MAX_RUN = 6;
141 DepTable head; // empty head
142 bool rerun = false; // rerun requested
144 // The class LaTeX does not know the temp path.
145 bufferlist.updateIncludedTeXfiles(GetCWD());
147 // Never write the depfile if an error was encountered.
150 // first check if the file dependencies exist:
151 // ->If it does exist
152 // check if any of the files mentioned in it have
153 // changed (done using a checksum).
155 // run latex once and
156 // remake the dependency file
157 // -> if not changed:
158 // just return there is nothing to do for us.
159 // ->if it doesn't exist
161 // run latex once (we need to run latex once anyway) and
162 // remake the dependency file.
164 FileInfo fi(depfile);
165 bool run_bibtex = false;
167 // Read the dep file:
169 // Update the checksums
172 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
173 if (head.sumchange()) {
175 lyxerr[Debug::DEPEND]
176 << "Dependency file has changed" << endl;
178 << "Run #" << count << endl;
179 minib->Set(string(_("LaTeX run number ")) + tostr(count));
182 scanres = scanLogFile(terr);
183 if (scanres & LaTeX::ERRORS) {
184 deleteFilesOnError();
185 return scanres; // return on error
188 run_bibtex = scanAux(head);
190 lyxerr[Debug::DEPEND]
191 << "Bibtex demands rerun" << endl;
193 lyxerr[Debug::DEPEND] << "return no_change" << endl;
194 return LaTeX::NO_CHANGE;
198 lyxerr[Debug::DEPEND]
199 << "Dependency file does not exist" << endl;
202 << "Run #" << count << endl;
203 head.insert(file, true);
204 minib->Set(string(_("LaTeX run number ")) + tostr(count));
207 scanres = scanLogFile(terr);
208 if (scanres & LaTeX::ERRORS) {
209 deleteFilesOnError();
210 return scanres; // return on error
215 // update the dependencies.
216 deplog(head); // reads the latex log
217 deptex(head); // checks for latex files
221 // At this point we must run external programs if needed.
222 // makeindex will be run if a .idx file changed or was generated.
223 // And if there were undefined citations or changes in references
224 // the .aux file is checked for signs of bibtex. Bibtex is then run
228 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
230 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
231 minib->Set(_("Running MakeIndex."));
233 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
237 if (scanres & LaTeX::UNDEF_CIT
238 || scanres & LaTeX::RERUN
240 // Here we must scan the .aux file and look for
241 // "\bibdata" and/or "\bibstyle". If one of those
242 // tags is found -> run bibtex and set rerun = true;
244 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
245 minib->Set(_("Running BibTeX."));
247 rerun = runBibTeX(OnlyFilename(ChangeExtension(file, ".aux")),
252 // we know on this point that latex has been run once (or we just
253 // returned) and the question now is to decide if we need to run
254 // it any more. This is done by asking if any of the files in the
255 // dependency file has changed. (remember that the checksum for
256 // a given file is reported to have changed if it just was created)
257 // -> if changed or rerun == true:
258 // run latex once more and
259 // update the dependency structure
260 // -> if not changed:
261 // we does nothing at this point
263 if (rerun || head.sumchange()) {
266 lyxerr[Debug::DEPEND]
267 << "Dep. file has changed or rerun requested" << endl;
269 << "Run #" << count << endl;
270 minib->Set(string(_("LaTeX run number ")) + tostr(count));
273 scanres = scanLogFile(terr);
274 if (scanres & LaTeX::ERRORS) {
275 deleteFilesOnError();
276 return scanres; // return on error
279 // update the depedencies
280 deplog(head); // reads the latex log
283 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
287 // The inclusion of files generated by external programs like
288 // makeindex or bibtex might have done changes to pagenumbereing,
289 // etc. And because of this we must run the external programs
290 // again to make sure everything is redone correctly.
291 // Also there should be no need to run the external programs any
294 // run makeindex if the <file>.idx has changed or was generated.
295 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
297 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
298 minib->Set(_("Running MakeIndex."));
300 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
304 // we will only run latex more if the log file asks for it.
305 // or if the sumchange() is true.
306 // -> rerun asked for:
308 // remake the dependency file
309 // goto 2 or return if max runs are reached.
310 // -> rerun not asked for:
311 // just return (fall out of bottom of func)
313 while ((head.sumchange() || rerun || (scanres & LaTeX::RERUN))
314 && count < MAX_RUN) {
315 // Yes rerun until message goes away, or until
316 // MAX_RUNS are reached.
319 lyxerr[Debug::LATEX] << "Run #" << count << endl;
320 minib->Set(string(_("LaTeX run number ")) + tostr(count));
323 scanres = scanLogFile(terr);
324 if (scanres & LaTeX::ERRORS) {
325 deleteFilesOnError();
326 return scanres; // return on error
333 // Write the dependencies to file.
335 lyxerr[Debug::LATEX] << "Done." << endl;
340 int LaTeX::operator()()
343 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
344 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
345 string tmp = cmd + ' ' + file + " > nul";
348 return one.startscript(Systemcalls::System, tmp);
352 bool LaTeX::runMakeIndex(string const & f)
354 lyxerr[Debug::LATEX] << "idx file has been made,"
355 " running makeindex on file "
358 // It should be possible to set the switches for makeindex
359 // sorting style and such. It would also be very convenient
360 // to be able to make style files from within LyX. This has
361 // to come for a later time. (0.13 perhaps?)
362 string tmp = "makeindex -c -q ";
365 one.startscript(Systemcalls::System, tmp);
370 bool LaTeX::scanAux(DepTable & dep)
372 // if any of the bib file has changed we don't have to
373 // check the .aux file.
374 if (dep.extchanged(".bib")
375 || dep.extchanged(".bst")) return true;
377 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
378 ifstream ifs(aux.c_str());
380 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
381 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
382 while (getline(ifs, token)) {
383 if (reg1.exact_match(token)) {
384 LRegex::SubMatches sub = reg1.exec(token);
385 string data = LSubstring(token, sub[1].first,
389 b = data.find_first_of(',', 0);
391 if (b == string::npos)
394 l = data.substr( 0, b - 0);
395 data.erase(0, b + 1);
399 ChangeExtension(l, "bib"), "bib");
400 if (!full_l.empty()) {
401 if (!dep.exist(full_l))
404 } while (b != string::npos);
405 } else if (reg2.exact_match(token)) {
406 LRegex::SubMatches sub = reg2.exec(token);
407 string style = LSubstring(token, sub[1].first,
409 // token is now the style file
410 // pass it to the helper
413 ChangeExtension(style, "bst"),
415 if (!full_l.empty()) {
416 if (!dep.exist(full_l))
425 bool LaTeX::runBibTeX(string const & f, DepTable & dep)
427 // Since a run of Bibtex mandates more latex runs it is ok to
428 // remove all ".bib" and ".bst" files, it is also required to
429 // discover style and database changes.
430 dep.remove_files_with_extension(".bib");
431 dep.remove_files_with_extension(".bst");
432 ifstream ifs(f.c_str());
434 bool using_bibtex = false;
435 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
436 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
437 while (getline(ifs, token)) {
438 if (reg1.exact_match(token)) {
440 LRegex::SubMatches const & sub = reg1.exec(token);
441 string data = LSubstring(token, sub[1].first,
443 // data is now all the bib files separated by ','
444 // get them one by one and pass them to the helper
447 b = data.find_first_of(',', 0);
449 if (b == string::npos)
452 l = data.substr(0, b - 0);
453 data.erase(0, b + 1);
457 ChangeExtension(l, "bib"),
459 lyxerr[Debug::LATEX] << "Bibtex database: `"
460 << full_l << "'" << endl;
461 if (!full_l.empty()) {
462 // add full_l to the dep file.
463 dep.insert(full_l, true);
465 } while (b != string::npos);
466 } else if (reg2.exact_match(token)) {
468 LRegex::SubMatches const & sub = reg2.exec(token);
469 string style = LSubstring(token, sub[1].first,
471 // token is now the style file
472 // pass it to the helper
475 ChangeExtension(style, "bst"),
477 lyxerr[Debug::LATEX] << "Bibtex style: `"
478 << full_l << "'" << endl;
479 if (!full_l.empty()) {
480 // add full_l to the dep file.
481 dep.insert(full_l, true);
487 string tmp = "bibtex ";
488 tmp += OnlyFilename(ChangeExtension(file, string()));
490 one.startscript(Systemcalls::System, tmp);
493 // bibtex was not run.
498 int LaTeX::scanLogFile(TeXErrors & terr)
502 int retval = NO_ERRORS;
503 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
504 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
505 ifstream ifs(tmp.c_str());
508 while (getline(ifs, token)) {
509 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
514 if (prefixIs(token, "LaTeX Warning:")) {
515 // Here shall we handle different
517 retval |= LATEX_WARNING;
518 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
519 if (contains(token, "Rerun to get cross-references")) {
522 << "We should rerun." << endl;
523 } else if (contains(token, "Citation")
524 && contains(token, "on page")
525 && contains(token, "undefined")) {
528 } else if (prefixIs(token, "Package")) {
530 retval |= PACKAGE_WARNING;
531 if (contains(token, "natbib Warning:")) {
533 if (contains(token, "Citation")
534 && contains(token, "on page")
535 && contains(token, "undefined")) {
538 } else if (contains(token, "Rerun LaTeX.")) {
539 // at least longtable.sty might use this.
542 } else if (prefixIs(token, "! ")) {
543 // Ok, we have something that looks like a TeX Error
544 // but what do we really have.
546 // Just get the error description:
547 string desc(token, 2);
548 if (contains(token, "LaTeX Error:"))
549 retval |= LATEX_ERROR;
554 if (!getline(ifs, tmp))
558 } while (!prefixIs(tmp, "l."));
559 if (prefixIs(tmp, "l.")) {
560 // we have a latex error
562 // get the line number:
564 sscanf(tmp.c_str(), "l.%d", &line);
565 // get the rest of the message:
566 string errstr(tmp, tmp.find(' '));
569 while (!contains(errstr, "l.")
571 && !prefixIs(tmp, "! ")
572 && !contains(tmp, "(job aborted")) {
578 << "line: " << line << '\n'
579 << "Desc: " << desc << '\n'
580 << "Text: " << errstr << endl;
581 if (line == last_line)
587 if (line_count <= 5) {
588 terr.insertError(line, desc, errstr);
593 // information messages, TeX warnings and other
594 // warnings we have not caught earlier.
595 if (prefixIs(token, "Overfull ")) {
596 retval |= TEX_WARNING;
597 } else if (prefixIs(token, "Underfull ")) {
598 retval |= TEX_WARNING;
599 } else if (contains(token, "Rerun to get citations")) {
600 // Natbib seems to use this.
602 } else if (contains(token, "No pages of output")) {
603 // A dvi file was not created
605 } else if (contains(token, "That makes 100 errors")) {
606 // More than 100 errors were reprted
607 retval |= TOO_MANY_ERRORS;
611 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
616 void LaTeX::deplog(DepTable & head)
618 // This function reads the LaTeX log file end extracts all the external
619 // files used by the LaTeX run. The files are then entered into the
622 string logfile = OnlyFilename(ChangeExtension(file, ".log"));
624 LRegex reg1(")* *\\(([^ ]+).*");
625 LRegex reg2("File: ([^ ]+).*");
627 ifstream ifs(logfile.c_str());
629 // Ok, the scanning of files here is not sufficient.
630 // Sometimes files are named by "File: xxx" only
631 // So I think we should use some regexps to find files instead.
632 // "(\([^ ]+\)" should match the "(file " variant
633 // "File: \([^ ]+\)" should match the "File: file" variant
637 if (token.empty()) continue;
639 if (reg1.exact_match(token)) {
640 LRegex::SubMatches const & sub = reg1.exec(token);
641 foundfile = LSubstring(token, sub[1].first,
643 } else if (reg2.exact_match(token)) {
644 LRegex::SubMatches const & sub = reg2.exec(token);
645 foundfile = LSubstring(token, sub[1].first,
651 lyxerr[Debug::DEPEND] << "Found file: "
652 << foundfile << endl;
654 // Ok now we found a file.
655 // Now we should make sure that this is a file that we can
656 // access through the normal paths.
657 // We will not try any fance search methods to
660 // (1) foundfile is an
661 // absolute path and should
663 if (AbsolutePath(foundfile)) {
664 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
665 << foundfile << endl;
666 // On inital insert we want to do the update at once
667 // since this file can not be a file generated by
669 head.insert(foundfile, true);
673 // (2) foundfile is in the tmpdir
674 // insert it into head
675 if (FileInfo(OnlyFilename(foundfile)).exist()) {
676 if (suffixIs(foundfile, ".aux")) {
677 lyxerr[Debug::DEPEND] << "We don't want "
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] << "Tmpdir TeX file: "
686 << OnlyFilename(foundfile)
688 head.insert(foundfile, true);
690 lyxerr[Debug::DEPEND] << "In tmpdir file:"
691 << OnlyFilename(foundfile)
693 head.insert(OnlyFilename(foundfile));
697 lyxerr[Debug::DEPEND]
698 << "Not a file or we are unable to find it."
704 void LaTeX::deptex(DepTable & head)
706 int except = AUX|LOG|DVI|BBL|IND|GLO;
709 for (int i = 0; i < file_count; ++i) {
710 if (!(all_files[i].file & except)) {
711 tmp = OnlyFilename(ChangeExtension(file,
712 all_files[i].extension));
713 lyxerr[Debug::DEPEND] << "deptex: " << tmp << endl;
714 if (fi.newFile(tmp).exist())