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"
38 // TODO: in no particular order
39 // - get rid of the extern BufferList and the call to
40 // BufferList::updateIncludedTeXfiles, this should either
41 // be done before calling LaTeX::funcs or in a completely
43 // - the bibtex command options should be supported.
44 // - the makeindex style files should be taken care of with
45 // the dependency mechanism.
46 // - makeindex commandline options should be supported
47 // - somewhere support viewing of bibtex and makeindex log files.
48 // - we should perhaps also scan the bibtex log file
49 // - we should perhaps also scan the bibtex log file
51 extern BufferList bufferlist;
53 struct texfile_struct {
54 LaTeX::TEX_FILES file;
55 char const * extension;
59 const texfile_struct all_files[] = {
60 { LaTeX::AUX, ".aux"},
61 { LaTeX::BBL, ".bbl"},
62 { LaTeX::DVI, ".dvi"},
63 { LaTeX::GLO, ".glo"},
64 { LaTeX::IDX, ".idx"},
65 { LaTeX::IND, ".ind"},
66 { LaTeX::LOF, ".lof"},
67 { LaTeX::LOA, ".loa"},
68 { LaTeX::LOG, ".log"},
69 { LaTeX::LOT, ".lot"},
70 { LaTeX::TOC, ".toc"},
71 { LaTeX::LTX, ".ltx"},
80 void TeXErrors::insertError(int line, string const & error_desc,
81 string const & error_text)
83 Error newerr(line, error_desc, error_text);
84 errors.push_back(newerr);
91 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
92 : cmd(latex), file(f), path(p)
95 file_count = sizeof(all_files) / sizeof(texfile_struct);
97 depfile = file + ".dep";
101 void LaTeX::deleteFilesOnError() const
103 // currently just a dummy function.
105 // What files do we have to delete?
107 // This will at least make latex do all the runs
108 ::unlink(depfile.c_str());
110 // but the reason for the error might be in a generated file...
113 string bbl = ChangeExtension(file, ".bbl", true);
114 ::unlink(bbl.c_str());
117 string ind = ChangeExtension(file, ".ind", true);
118 ::unlink(ind.c_str());
120 // Also remove the aux file
121 string aux = ChangeExtension(file, ".aux", true);
122 ::unlink(aux.c_str());
126 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
127 // We know that this function will only be run if the lyx buffer
128 // has been changed. We also know that a newly written .tex file
129 // is always different from the previous one because of the date
130 // in it. However it seems safe to run latex (at least) on time each
131 // time the .tex file changes.
133 int scanres = LaTeX::NO_ERRORS;
134 unsigned int count = 0; // number of times run
135 num_errors = 0; // just to make sure.
136 const unsigned int MAX_RUN = 6;
137 DepTable head; // empty head
138 bool rerun = false; // rerun requested
140 // The class LaTeX does not know the temp path.
141 bufferlist.updateIncludedTeXfiles(GetCWD());
143 // Never write the depfile if an error was encountered.
146 // first check if the file dependencies exist:
147 // ->If it does exist
148 // check if any of the files mentioned in it have
149 // changed (done using a checksum).
151 // run latex once and
152 // remake the dependency file
153 // -> if not changed:
154 // just return there is nothing to do for us.
155 // ->if it doesn't exist
157 // run latex once (we need to run latex once anyway) and
158 // remake the dependency file.
160 FileInfo fi(depfile);
161 bool run_bibtex = false;
163 // Read the dep file:
165 // Update the checksums
168 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
169 if (head.sumchange()) {
171 lyxerr[Debug::DEPEND]
172 << "Dependency file has changed" << endl;
174 << "Run #" << count << endl;
175 minib->Set(string(_("LaTeX run number ")) + tostr(count));
178 scanres = scanLogFile(terr);
179 if (scanres & LaTeX::ERRORS) {
180 deleteFilesOnError();
181 return scanres; // return on error
184 run_bibtex = scanAux(head);
186 lyxerr[Debug::DEPEND]
187 << "Bibtex demands rerun" << endl;
189 lyxerr[Debug::DEPEND] << "return no_change" << endl;
190 return LaTeX::NO_CHANGE;
194 lyxerr[Debug::DEPEND]
195 << "Dependency file does not exist" << endl;
198 << "Run #" << count << endl;
199 head.insert(file, true);
200 minib->Set(string(_("LaTeX run number ")) + tostr(count));
203 scanres = scanLogFile(terr);
204 if (scanres & LaTeX::ERRORS) {
205 deleteFilesOnError();
206 return scanres; // return on error
211 // update the dependencies.
212 deplog(head); // reads the latex log
213 deptex(head); // checks for latex files
217 // At this point we must run external programs if needed.
218 // makeindex will be run if a .idx file changed or was generated.
219 // And if there were undefined citations or changes in references
220 // the .aux file is checked for signs of bibtex. Bibtex is then run
224 if (head.haschanged(ChangeExtension(file, ".idx", true))) {
226 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
227 minib->Set(_("Running MakeIndex."));
229 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
233 if (scanres & LaTeX::UNDEF_CIT
234 || scanres & LaTeX::RERUN
236 // Here we must scan the .aux file and look for
237 // "\bibdata" and/or "\bibstyle". If one of those
238 // tags is found -> run bibtex and set rerun = true;
240 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
241 minib->Set(_("Running BibTeX."));
243 rerun = runBibTeX(ChangeExtension(file, ".aux", true), head);
247 // we know on this point that latex has been run once (or we just
248 // returned) and the question now is to decide if we need to run
249 // it any more. This is done by asking if any of the files in the
250 // dependency file has changed. (remember that the checksum for
251 // a given file is reported to have changed if it just was created)
252 // -> if changed or rerun == true:
253 // run latex once more and
254 // update the dependency structure
255 // -> if not changed:
256 // we does nothing at this point
258 if (rerun || head.sumchange()) {
261 lyxerr[Debug::DEPEND]
262 << "Dep. file has changed or rerun requested" << endl;
264 << "Run #" << count << endl;
265 minib->Set(string(_("LaTeX run number ")) + tostr(count));
268 scanres = scanLogFile(terr);
269 if (scanres & LaTeX::ERRORS) {
270 deleteFilesOnError();
271 return scanres; // return on error
274 // update the depedencies
275 deplog(head); // reads the latex log
278 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
282 // The inclusion of files generated by external programs like
283 // makeindex or bibtex might have done changes to pagenumbereing,
284 // etc. And because of this we must run the external programs
285 // again to make sure everything is redone correctly.
286 // Also there should be no need to run the external programs any
289 // run makeindex if the <file>.idx has changed or was generated.
290 if (head.haschanged(ChangeExtension(file, ".idx", true))) {
292 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
293 minib->Set(_("Running MakeIndex."));
295 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
299 // we will only run latex more if the log file asks for it.
300 // or if the sumchange() is true.
301 // -> rerun asked for:
303 // remake the dependency file
304 // goto 2 or return if max runs are reached.
305 // -> rerun not asked for:
306 // just return (fall out of bottom of func)
308 while ((head.sumchange() || rerun || (scanres & LaTeX::RERUN))
309 && count < MAX_RUN) {
310 // Yes rerun until message goes away, or until
311 // MAX_RUNS are reached.
314 lyxerr[Debug::LATEX] << "Run #" << count << endl;
315 minib->Set(string(_("LaTeX run number ")) + tostr(count));
318 scanres = scanLogFile(terr);
319 if (scanres & LaTeX::ERRORS) {
320 deleteFilesOnError();
321 return scanres; // return on error
328 // Write the dependencies to file.
330 lyxerr[Debug::LATEX] << "Done." << endl;
335 int LaTeX::operator()()
338 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
339 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
340 string tmp = cmd + ' ' + file + " > nul";
343 return one.startscript(Systemcalls::System, tmp);
347 bool LaTeX::runMakeIndex(string const & f)
349 lyxerr[Debug::LATEX] << "idx file has been made,"
350 " running makeindex on file "
353 // It should be possible to set the switches for makeindex
354 // sorting style and such. It would also be very convenient
355 // to be able to make style files from within LyX. This has
356 // to come for a later time. (0.13 perhaps?)
357 string tmp = "makeindex -c -q ";
360 one.startscript(Systemcalls::System, tmp);
365 bool LaTeX::scanAux(DepTable & dep)
367 // if any of the bib file has changed we don't have to
368 // check the .aux file.
369 if (dep.extchanged(".bib")
370 || dep.extchanged(".bst")) return true;
372 string aux = ChangeExtension(file, ".aux", true);
373 ifstream ifs(aux.c_str());
375 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
376 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
377 while (getline(ifs, token)) {
378 if (reg1.exact_match(token)) {
379 LRegex::SubMatches sub = reg1.exec(token);
380 string data = LSubstring(token, sub[1].first,
384 b = data.find_first_of(',', 0);
386 if (b == string::npos)
389 l = data.substr( 0, b - 0);
390 data.erase(0, b + 1);
394 ChangeExtension(l, "bib", false), "bib");
395 if (!full_l.empty()) {
396 if (!dep.exist(full_l))
399 } while (b != string::npos);
400 } else if (reg2.exact_match(token)) {
401 LRegex::SubMatches sub = reg2.exec(token);
402 string style = LSubstring(token, sub[1].first,
404 // token is now the style file
405 // pass it to the helper
408 ChangeExtension(style, "bst", false),
410 if (!full_l.empty()) {
411 if (!dep.exist(full_l))
420 bool LaTeX::runBibTeX(string const & f, DepTable & dep)
422 // Since a run of Bibtex mandates more latex runs it is ok to
423 // remove all ".bib" and ".bst" files, it is also required to
424 // discover style and database changes.
425 dep.remove_files_with_extension(".bib");
426 dep.remove_files_with_extension(".bst");
427 ifstream ifs(f.c_str());
429 bool using_bibtex = false;
430 LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
431 LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
432 while (getline(ifs, token)) {
433 if (reg1.exact_match(token)) {
435 LRegex::SubMatches const & sub = reg1.exec(token);
436 string data = LSubstring(token, sub[1].first,
438 // data is now all the bib files separated by ','
439 // get them one by one and pass them to the helper
442 b = data.find_first_of(',', 0);
444 if (b == string::npos)
447 l = data.substr(0, b - 0);
448 data.erase(0, b + 1);
452 ChangeExtension(l, "bib", false),
454 lyxerr[Debug::LATEX] << "Bibtex database: `"
455 << full_l << "'" << endl;
456 if (!full_l.empty()) {
457 // add full_l to the dep file.
458 dep.insert(full_l, true);
460 } while (b != string::npos);
461 } else if (reg2.exact_match(token)) {
463 LRegex::SubMatches const & sub = reg2.exec(token);
464 string style = LSubstring(token, sub[1].first,
466 // token is now the style file
467 // pass it to the helper
470 ChangeExtension(style, "bst", false),
472 lyxerr[Debug::LATEX] << "Bibtex style: `"
473 << full_l << "'" << endl;
474 if (!full_l.empty()) {
475 // add full_l to the dep file.
476 dep.insert(full_l, true);
482 string tmp = "bibtex ";
483 tmp += ChangeExtension(file, string(), true);
485 one.startscript(Systemcalls::System, tmp);
488 // bibtex was not run.
493 int LaTeX::scanLogFile(TeXErrors & terr)
497 int retval = NO_ERRORS;
498 string tmp = ChangeExtension(file, ".log", true);
499 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
500 ifstream ifs(tmp.c_str());
503 while (getline(ifs, token)) {
504 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
509 if (prefixIs(token, "LaTeX Warning:")) {
510 // Here shall we handle different
512 retval |= LATEX_WARNING;
513 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
514 if (contains(token, "Rerun to get cross-references")) {
517 << "We should rerun." << endl;
518 } else if (contains(token, "Citation")
519 && contains(token, "on page")
520 && contains(token, "undefined")) {
523 } else if (prefixIs(token, "Package")) {
525 retval |= PACKAGE_WARNING;
526 if (contains(token, "natbib Warning:")) {
528 if (contains(token, "Citation")
529 && contains(token, "on page")
530 && contains(token, "undefined")) {
533 } else if (contains(token, "Rerun LaTeX.")) {
534 // at least longtable.sty might use this.
537 } else if (prefixIs(token, "! ")) {
538 // Ok, we have something that looks like a TeX Error
539 // but what do we really have.
541 // Just get the error description:
542 string desc(token, 2);
543 if (contains(token, "LaTeX Error:"))
544 retval |= LATEX_ERROR;
549 if (!getline(ifs, tmp))
553 } while (!prefixIs(tmp, "l."));
554 if (prefixIs(tmp, "l.")) {
555 // we have a latex error
557 // get the line number:
559 sscanf(tmp.c_str(), "l.%d", &line);
560 // get the rest of the message:
561 string errstr(tmp, tmp.find(' '));
564 while (!contains(errstr, "l.")
566 && !prefixIs(tmp, "! ")
567 && !contains(tmp, "(job aborted")) {
573 << "line: " << line << '\n'
574 << "Desc: " << desc << '\n'
575 << "Text: " << errstr << endl;
576 if (line == last_line)
582 if (line_count <= 5) {
583 terr.insertError(line, desc, errstr);
588 // information messages, TeX warnings and other
589 // warnings we have not caught earlier.
590 if (prefixIs(token, "Overfull ")) {
591 retval |= TEX_WARNING;
592 } else if (prefixIs(token, "Underfull ")) {
593 retval |= TEX_WARNING;
594 } else if (contains(token, "Rerun to get citations")) {
595 // Natbib seems to use this.
597 } else if (contains(token, "No pages of output")) {
598 // A dvi file was not created
600 } else if (contains(token, "That makes 100 errors")) {
601 // More than 100 errors were reprted
602 retval |= TOO_MANY_ERRORS;
606 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
611 void LaTeX::deplog(DepTable & head)
613 // This function reads the LaTeX log file end extracts all the external
614 // files used by the LaTeX run. The files are then entered into the
617 string logfile = ChangeExtension(file, ".log", true);
619 ifstream ifs(logfile.c_str());
621 // Now we read chars until we find a '('
628 // We now have c == '(', we now read the the sequence of
629 // chars until reaching EOL, ' ' or ')' and put that
633 if (c == '\n' || c == ' ' || c == ')')
637 lyxerr[Debug::DEPEND] << "Found file: "
638 << foundfile << endl;
640 // Ok now we found a file.
641 // Now we should make sure that
642 // this is a file that we can
643 // access through the normal
645 // (1) foundfile is an
646 // absolute path and should
648 if (AbsolutePath(foundfile)) {
649 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
650 << foundfile << endl;
651 // On inital insert we want to do the update at once
652 // since this file can not be a file generated by
654 head.insert(foundfile, true);
658 // (2) foundfile is in the tmpdir
659 // insert it into head
660 if (FileInfo(OnlyFilename(foundfile)).exist()) {
661 if (suffixIs(foundfile, ".aux")) {
662 lyxerr[Debug::DEPEND] << "We don't want "
663 << OnlyFilename(foundfile)
664 << " in the dep file"
666 } else if (suffixIs(foundfile, ".tex")) {
667 // This is a tex file generated by LyX
668 // and latex is not likely to change this
670 lyxerr[Debug::DEPEND] << "Tmpdir TeX file: "
671 << OnlyFilename(foundfile)
673 head.insert(foundfile, true);
675 lyxerr[Debug::DEPEND] << "In tmpdir file:"
676 << OnlyFilename(foundfile)
678 head.insert(OnlyFilename(foundfile));
682 lyxerr[Debug::DEPEND]
683 << "Not a file or we are unable to find it."
689 void LaTeX::deptex(DepTable & head)
691 int except = AUX|LOG|DVI|BBL|IND|GLO;
694 for (int i = 0; i < file_count; ++i) {
695 if (!(all_files[i].file & except)) {
696 tmp = ChangeExtension(file,
697 all_files[i].extension,
699 lyxerr[Debug::DEPEND] << "deptex: " << tmp << endl;
700 if (fi.newFile(tmp).exist())