1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
5 * Copyright 1995 Matthias Ettrich
6 * Copyright 1995-1999 The LyX Team.
8 * This file is Copyright 1996-1999
11 * ======================================================
17 #pragma implementation
20 #include "support/filetools.h"
22 #include "support/FileInfo.h"
24 #include "support/lyxlib.h"
25 #include "support/syscall.h"
26 #include "support/syscontr.h"
27 #include "support/path.h"
28 #include "bufferlist.h"
29 #include "minibuffer.h"
34 // TODO: in no particular order
35 // - get rid of the extern BufferList and the call to
36 // BufferList::updateIncludedTeXfiles, this should either
37 // be done before calling LaTeX::funcs or in a completely
39 // - the bibtex command options should be supported.
40 // - the makeindex style files should be taken care of with
41 // the dependency mechanism.
42 // - makeindex commandline options should be supported
43 // - somewhere support viewing of bibtex and makeindex log files.
44 // - we should perhaps also scan the bibtex log file
45 // - we should perhaps also scan the bibtex log file
47 extern BufferList bufferlist;
49 struct texfile_struct {
50 LaTeX::TEX_FILES file;
51 char const *extension;
55 const texfile_struct all_files[] = {
56 { LaTeX::AUX, ".aux"},
57 { LaTeX::BBL, ".bbl"},
58 { LaTeX::DVI, ".dvi"},
59 { LaTeX::GLO, ".glo"},
60 { LaTeX::IDX, ".idx"},
61 { LaTeX::IND, ".ind"},
62 { LaTeX::LOF, ".lof"},
63 { LaTeX::LOA, ".loa"},
64 { LaTeX::LOG, ".log"},
65 { LaTeX::LOT, ".lot"},
66 { LaTeX::TOC, ".toc"},
67 { LaTeX::LTX, ".ltx"},
76 void TeXErrors::insertError(int line, string const & error_desc,
77 string const & error_text)
79 Error newerr(line, error_desc, error_text);
80 errors.push_back(newerr);
87 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
88 : cmd(latex), file(f), path(p)
91 file_count = sizeof(all_files) / sizeof(texfile_struct);
93 depfile = file + ".dep";
97 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
98 // We know that this function will only be run if the lyx buffer
99 // has been changed. We also know that a newly written .tex file
100 // is always different from the previous one because of the date
101 // in it. However it seems safe to run latex (at least) on time each
102 // time the .tex file changes.
104 int scanres = LaTeX::NO_ERRORS;
105 unsigned int count = 0; // number of times run
106 num_errors = 0; // just to make sure.
107 const unsigned int MAX_RUN = 6;
108 DepTable head; // empty head
109 bool rerun = false; // rerun requested
111 // The class LaTeX does not know the temp path.
112 bufferlist.updateIncludedTeXfiles(GetCWD());
114 // Never write the depfile if an error was encountered.
117 // first check if the file dependencies exist:
118 // ->If it does exist
119 // check if any of the files mentioned in it have
120 // changed (done using a checksum).
122 // run latex once and
123 // remake the dependency file
124 // -> if not changed:
125 // just return there is nothing to do for us.
126 // ->if it doesn't exist
128 // run latex once (we need to run latex once anyway) and
129 // remake the dependency file.
131 FileInfo fi(depfile);
132 bool run_bibtex = false;
134 // Read the dep file:
136 // Update the checksums
139 lyxerr[Debug::LATEX] << "Dependency file exists" << endl;
140 if (head.sumchange()) {
142 if (head.extchanged(".bib")
143 || head.extchanged(".bst")) run_bibtex = true;
145 << "Dependency file has changed\n"
146 << "Run #" << count << endl;
147 minib->Set(string(_("LaTeX run number ")) + tostr(count));
150 scanres = scanLogFile(terr);
151 if (scanres & LaTeX::ERRORS) return scanres; // return on error
153 lyxerr[Debug::LATEX] << "return no_change" << endl;
154 return LaTeX::NO_CHANGE;
158 lyxerr[Debug::LATEX] << "Dependency file does not exist\n"
159 << "Run #" << count << endl;
160 head.insert(file, true);
161 minib->Set(string(_("LaTeX run number ")) + tostr(count));
164 scanres = scanLogFile(terr);
165 if (scanres & LaTeX::ERRORS) return scanres; // return on error
168 // update the dependencies.
169 deplog(head); // reads the latex log
170 deptex(head); // checks for latex files
174 // At this point we must run external programs if needed.
175 // makeindex will be run if a .idx file changed or was generated.
176 // And if there were undefined citations or changes in references
177 // the .aux file is checked for signs of bibtex. Bibtex is then run
181 if (head.haschanged(ChangeExtension(file, ".idx", true))) {
183 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
184 minib->Set(_("Running MakeIndex."));
186 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
190 if (scanres & LaTeX::UNDEF_CIT
191 || scanres & LaTeX::RERUN
193 // Here we must scan the .aux file and look for
194 // "\bibdata" and/or "\bibstyle". If one of those
195 // tags is found -> run bibtex and set rerun = true;
197 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
198 minib->Set(_("Running BibTeX."));
200 rerun = runBibTeX(ChangeExtension(file, ".aux", true), head);
204 // we know on this point that latex has been run once (or we just
205 // returned) and the question now is to decide if we need to run
206 // it any more. This is done by asking if any of the files in the
207 // dependency file has changed. (remember that the checksum for
208 // a given file is reported to have changed if it just was created)
209 // -> if changed or rerun == true:
210 // run latex once more and
211 // update the dependency structure
212 // -> if not changed:
213 // we does nothing at this point
215 if (rerun || head.sumchange()) {
219 << "Dep. file has changed or rerun requested\n"
220 << "Run #" << count << endl;
221 minib->Set(string(_("LaTeX run number ")) + tostr(count));
224 scanres = scanLogFile(terr);
225 if (scanres & LaTeX::ERRORS) return scanres; // return on error
226 // update the depedencies
227 deplog(head); // reads the latex log
230 lyxerr[Debug::LATEX] << "Dep. file has NOT changed" << endl;
234 // The inclusion of files generated by external programs like
235 // makeindex or bibtex might have done changes to pagenumbereing,
236 // etc. And because of this we must run the external programs
237 // again to make sure everything is redone correctly.
238 // Also there should be no need to run the external programs any
241 // run makeindex if the <file>.idx has changed or was generated.
242 if (head.haschanged(ChangeExtension(file, ".idx", true))) {
244 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
245 minib->Set(_("Running MakeIndex."));
247 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
251 // we will only run latex more if the log file asks for it.
252 // or if the sumchange() is true.
253 // -> rerun asked for:
255 // remake the dependency file
256 // goto 2 or return if max runs are reached.
257 // -> rerun not asked for:
258 // just return (fall out of bottom of func)
260 while ((head.sumchange() || rerun || (scanres & LaTeX::RERUN))
261 && count < MAX_RUN) {
262 // Yes rerun until message goes away, or until
263 // MAX_RUNS are reached.
266 lyxerr[Debug::LATEX] << "Run #" << count << endl;
267 minib->Set(string(_("LaTeX run number ")) + tostr(count));
270 scanres = scanLogFile(terr);
271 if (scanres & LaTeX::ERRORS) return scanres; // return on error
276 // Write the dependencies to file.
278 lyxerr[Debug::LATEX] << "Done." << endl;
283 int LaTeX::operator()()
286 string tmp = cmd + ' ' + file + " > /dev/null";
287 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
288 string tmp = cmd + ' ' + file + " > nul";
291 return one.startscript(Systemcalls::System, tmp);
295 bool LaTeX::runMakeIndex(string const &file)
297 lyxerr[Debug::LATEX] << "idx file has been made,"
298 " running makeindex on file "
301 // It should be possible to set the switches for makeindex
302 // sorting style and such. It would also be very convenient
303 // to be able to make style files from within LyX. This has
304 // to come for a later time. (0.13 perhaps?)
305 string tmp = "makeindex -c -q ";
308 one.startscript(Systemcalls::System, tmp);
313 typedef pair<int, string> cmdret;
314 static cmdret do_popen(string const & cmd)
316 // One question is if we should use popen or
317 // create our own popen based on fork, exec, pipe
318 // of course the best would be to have a
319 // pstream (process stream), with the
320 // variants ipstream, opstream and
321 FILE * inf = popen(cmd.c_str(), "r");
325 ret += static_cast<char>(c);
328 int pret = pclose(inf);
329 return make_pair(pret, ret);
333 static string findtexfile(string const & fil, string const & format)
335 // If fil is a file with absolute path we just return it
336 if (AbsolutePath(fil)) return fil;
338 // Check in the current dir.
339 if (FileInfo(OnlyFilename(fil)).exist())
340 return OnlyFilename(fil);
342 // No we try to find it using kpsewhich.
343 string kpsecmd = "kpsewhich --format= " + format + " " + fil;
344 cmdret c = do_popen(kpsecmd);
346 lyxerr << "kpse status = " << c.first << "\n"
347 << "kpse result = `" << strip(c.second, '\n') << "'" << endl;
348 return c.first == 0 ? strip(c.second, '\n') : string();
352 bool LaTeX::runBibTeX(string const & file, DepTable & dep)
354 ifstream ifs(file.c_str());
356 bool using_bibtex = false;
357 while (getline(ifs, token)) {
358 if (contains(token, "\\bibdata{")) {
360 string::size_type a = token.find("\\bibdata{") + 9;
361 string::size_type b = token.find_first_of("}", a);
362 string data = token.substr(a, b - a);
363 // data is now all the bib files separated by ','
364 // get them one by one and pass them to the helper
366 b = data.find_first_of(',', 0);
368 if (b == string::npos)
371 l = data.substr(0, b - 0);
372 data.erase(0, b + 1);
376 ChangeExtension(l, "bib", false),
379 << full_l << "'" << endl;
380 if (!full_l.empty()) {
381 // add full_l to the dep file.
382 dep.insert(full_l, true);
384 } while (b != string::npos);
385 } else if (contains(token, "\\bibstyle{")) {
387 string::size_type a = token.find("\\bibstyle{") + 10;
388 string::size_type b = token.find_first_of("}", a);
389 string style = token.substr(a, b - a);
390 // token is now the style file
391 // pass it to the helper
394 ChangeExtension(style, "bst", false),
396 lyxerr << "style = `"
397 << full_l << "'" << endl;
398 if (!full_l.empty()) {
399 // add full_l to the dep file.
400 dep.insert(full_l, true);
406 string tmp = "bibtex ";
407 tmp += ChangeExtension(file, string(), true);
409 one.startscript(Systemcalls::System, tmp);
412 // bibtex was not run.
417 int LaTeX::scanLogFile(TeXErrors & terr)
419 int retval = NO_ERRORS;
420 string tmp = ChangeExtension(file, ".log", true);
421 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
422 ifstream ifs(tmp.c_str());
425 while (getline(ifs, token)) {
426 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
431 if (prefixIs(token, "LaTeX Warning:")) {
432 // Here shall we handle different
434 retval |= LATEX_WARNING;
435 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
436 if (contains(token, "Rerun to get cross-references")) {
439 << "We should rerun." << endl;
440 } else if (contains(token, "Citation")
441 && contains(token, "on page")
442 && contains(token, "undefined")) {
445 } else if (prefixIs(token, "Package")) {
447 retval |= PACKAGE_WARNING;
448 if (contains(token, "natbib Warning:")) {
450 if (contains(token, "Citation")
451 && contains(token, "on page")
452 && contains(token, "undefined")) {
455 } else if (contains(token, "Rerun LaTeX.")) {
456 // at least longtable.sty might use this.
459 } else if (prefixIs(token, "! ")) {
460 // Ok, we have something that looks like a TeX Error
461 // but what do we really have.
463 // Just get the error description:
464 string desc(token, 2);
465 if (contains(token, "LaTeX Error:"))
466 retval |= LATEX_ERROR;
470 if (prefixIs(tmp, "l.")) {
471 // we have a latex error
473 // get the line number:
475 sscanf(tmp.c_str(), "l.%d", &line);
476 // get the rest of the message:
477 string errstr(tmp, tmp.find(' '));
480 while (!contains(errstr, "l.")
482 && !prefixIs(tmp, "! ")
483 && !contains(tmp, "(job aborted")) {
489 << "line: " << line << '\n'
490 << "Desc: " << desc << '\n'
491 << "Text: " << errstr << endl;
492 terr.insertError(line, desc, errstr);
496 // information messages, TeX warnings and other
497 // warnings we have not caught earlier.
498 if (prefixIs(token, "Overfull ")) {
499 retval |= TEX_WARNING;
500 } else if (prefixIs(token, "Underfull ")) {
501 retval |= TEX_WARNING;
502 } else if (contains(token, "Rerun to get citations")) {
503 // Natbib seems to use this.
505 } else if (contains(token, "No pages of output")) {
506 // A dvi file was not created
508 } else if (contains(token, "That makes 100 errors")) {
509 // More than 100 errors were reprted
510 retval |= TOO_MANY_ERRORS;
514 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
519 void LaTeX::deplog(DepTable & head)
521 // This function reads the LaTeX log file end extracts all the external
522 // files used by the LaTeX run. The files are then entered into the
525 string logfile = ChangeExtension(file, ".log", true);
527 ifstream ifs(logfile.c_str());
529 // Now we read chars until we find a '('
536 // We now have c == '(', we now read the the sequence of
537 // chars until reaching EOL, ' ' or ')' and put that
541 if (c == '\n' || c == ' ' || c == ')')
545 lyxerr[Debug::LATEX] << "Found file: "
546 << foundfile << endl;
548 // Ok now we found a file.
549 // Now we should make sure that
550 // this is a file that we can
551 // access through the normal
553 // (1) foundfile is an
554 // absolute path and should
556 if (AbsolutePath(foundfile)) {
557 lyxerr[Debug::LATEX] << "AbsolutePath file: "
558 << foundfile << endl;
559 // On inital insert we want to do the update at once
560 // since this file can not be a file generated by
562 head.insert(foundfile, true);
566 // (2) foundfile is in the tmpdir
567 // insert it into head
568 if (FileInfo(OnlyFilename(foundfile)).exist()) {
569 if (suffixIs(foundfile, ".aux")) {
570 lyxerr[Debug::LATEX] << "We don't want "
571 << OnlyFilename(foundfile)
572 << " in the dep file"
574 } else if (suffixIs(foundfile, ".tex")) {
575 // This is a tex file generated by LyX
576 // and latex is not likely to change this
578 lyxerr[Debug::LATEX] << "Tmpdir TeX file: "
579 << OnlyFilename(foundfile)
581 head.insert(foundfile, true);
583 lyxerr[Debug::LATEX] << "In tmpdir file:"
584 << OnlyFilename(foundfile)
586 head.insert(OnlyFilename(foundfile));
591 << "Not a file or we are unable to find it."
597 void LaTeX::deptex(DepTable & head)
599 int except = AUX|LOG|DVI|BBL|IND|GLO;
602 for (int i = 0; i < file_count; ++i) {
603 if (!(all_files[i].file & except)) {
604 tmp = ChangeExtension(file,
605 all_files[i].extension,
607 lyxerr[Debug::LATEX] << "deptex: " << tmp << endl;
608 if (fi.newFile(tmp).exist())