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"
32 // TODO: in no particular order
33 // - get rid of the extern BufferList and the call to
34 // BufferList::updateIncludedTeXfiles, this should either
35 // be done before calling LaTeX::funcs or in a completely
37 // - the bibtex command options should be supported.
38 // - the makeindex style files should be taken care of with
39 // the dependency mechanism.
40 // - makeindex commandline options should be supported
41 // - somewhere support viewing of bibtex and makeindex log files.
42 // - we should perhaps also scan the bibtex log file
43 // - we should perhaps also scan the bibtex log file
45 extern BufferList bufferlist;
47 struct texfile_struct {
48 LaTeX::TEX_FILES file;
49 char const *extension;
53 const texfile_struct all_files[] = {
54 { LaTeX::AUX, ".aux"},
55 { LaTeX::BBL, ".bbl"},
56 { LaTeX::DVI, ".dvi"},
57 { LaTeX::GLO, ".glo"},
58 { LaTeX::IDX, ".idx"},
59 { LaTeX::IND, ".ind"},
60 { LaTeX::LOF, ".lof"},
61 { LaTeX::LOA, ".loa"},
62 { LaTeX::LOG, ".log"},
63 { LaTeX::LOT, ".lot"},
64 { LaTeX::TOC, ".toc"},
65 { LaTeX::LTX, ".ltx"},
74 void TeXErrors::insertError(int line, string const & error_desc,
75 string const & error_text)
77 Error newerr(line, error_desc, error_text);
78 errors.push_back(newerr);
85 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
86 : cmd(latex), file(f), path(p)
89 file_count = sizeof(all_files) / sizeof(texfile_struct);
91 depfile = file + ".dep";
95 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
96 // We know that this function will only be run if the lyx buffer
97 // has been changed. We also know that a newly written .tex file
98 // is always different from the previous one because of the date
99 // in it. However it seems safe to run latex (at least) on time each
100 // time the .tex file changes.
102 int scanres = LaTeX::NO_ERRORS;
103 unsigned int count = 0; // number of times run
104 num_errors = 0; // just to make sure.
105 const unsigned int MAX_RUN = 6;
106 DepTable head; // empty head
107 bool rerun = false; // rerun requested
109 // The class LaTeX does not know the temp path.
110 bufferlist.updateIncludedTeXfiles(GetCWD());
112 // Never write the depfile if an error was encountered.
115 // first check if the file dependencies exist:
116 // ->If it does exist
117 // check if any of the files mentioned in it have
118 // changed (done using a checksum).
120 // run latex once and
121 // remake the dependency file
122 // -> if not changed:
123 // just return there is nothing to do for us.
124 // ->if it doesn't exist
126 // run latex once (we need to run latex once anyway) and
127 // remake the dependency file.
129 FileInfo fi(depfile);
130 bool run_bibtex = false;
132 // Read the dep file:
134 // Update the checksums
137 lyxerr[Debug::LATEX] << "Dependency file exists" << endl;
138 if (head.sumchange()) {
140 if (head.extchanged(".bib")
141 || head.extchanged(".bst")) run_bibtex = true;
143 << "Dependency file has changed\n"
144 << "Run #" << count << endl;
145 minib->Set(string(_("LaTeX run number ")) + tostr(count));
148 scanres = scanLogFile(terr);
149 if (scanres & LaTeX::ERRORS) return scanres; // return on error
151 lyxerr[Debug::LATEX] << "return no_change" << endl;
152 return LaTeX::NO_CHANGE;
156 lyxerr[Debug::LATEX] << "Dependency file does not exist\n"
157 << "Run #" << count << endl;
158 head.insert(file, true);
159 minib->Set(string(_("LaTeX run number ")) + tostr(count));
162 scanres = scanLogFile(terr);
163 if (scanres & LaTeX::ERRORS) return scanres; // return on error
166 // update the dependencies.
167 deplog(head); // reads the latex log
168 deptex(head); // checks for latex files
172 // At this point we must run external programs if needed.
173 // makeindex will be run if a .idx file changed or was generated.
174 // And if there were undefined citations or changes in references
175 // the .aux file is checked for signs of bibtex. Bibtex is then run
179 if (head.haschanged(ChangeExtension(file, ".idx", true))) {
181 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
182 minib->Set(_("Running MakeIndex."));
184 rerun=runMakeIndex(ChangeExtension(file,".idx",true));
188 if (scanres & LaTeX::UNDEF_CIT
189 || scanres & LaTeX::RERUN
191 // Here we must scan the .aux file and look for
192 // "\bibdata" and/or "\bibstyle". If one of those
193 // tags is found -> run bibtex and set rerun = true;
195 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
196 minib->Set(_("Running BibTeX."));
198 rerun = runBibTeX(ChangeExtension(file, ".aux", true), head);
202 // we know on this point that latex has been run once (or we just
203 // returned) and the question now is to decide if we need to run
204 // it any more. This is done by asking if any of the files in the
205 // dependency file has changed. (remember that the checksum for
206 // a given file is reported to have changed if it just was created)
207 // -> if changed or rerun == true:
208 // run latex once more and
209 // update the dependency structure
210 // -> if not changed:
211 // we does nothing at this point
213 if (rerun || head.sumchange()) {
217 << "Dep. file has changed or rerun requested\n"
218 << "Run #" << count << endl;
219 minib->Set(string(_("LaTeX run number ")) + tostr(count));
222 scanres = scanLogFile(terr);
223 if (scanres & LaTeX::ERRORS) return scanres; // return on error
224 // update the depedencies
225 deplog(head); // reads the latex log
228 lyxerr[Debug::LATEX] << "Dep. file has NOT changed" << endl;
232 // The inclusion of files generated by external programs like
233 // makeindex or bibtex might have done changes to pagenumbereing,
234 // etc. And because of this we must run the external programs
235 // again to make sure everything is redone correctly.
236 // Also there should be no need to run the external programs any
239 // run makeindex if the <file>.idx has changed or was generated.
240 if (head.haschanged(ChangeExtension(file, ".idx", true))) {
242 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
243 minib->Set(_("Running MakeIndex."));
245 rerun = runMakeIndex(ChangeExtension(file, ".idx", true));
249 // we will only run latex more if the log file asks for it.
250 // or if the sumchange() is true.
251 // -> rerun asked for:
253 // remake the dependency file
254 // goto 2 or return if max runs are reached.
255 // -> rerun not asked for:
256 // just return (fall out of bottom of func)
258 while ((head.sumchange() || rerun || (scanres & LaTeX::RERUN))
259 && count < MAX_RUN) {
260 // Yes rerun until message goes away, or until
261 // MAX_RUNS are reached.
264 lyxerr[Debug::LATEX] << "Run #" << count << endl;
265 minib->Set(string(_("LaTeX run number ")) + tostr(count));
268 scanres = scanLogFile(terr);
269 if (scanres & LaTeX::ERRORS) return scanres; // return on error
274 // Write the dependencies to file.
276 lyxerr[Debug::LATEX] << "Done." << endl;
281 int LaTeX::operator()()
284 string tmp = cmd + ' ' + file + " > /dev/null";
285 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
286 string tmp = cmd + ' ' + file + " > nul";
289 return one.startscript(Systemcalls::System, tmp);
293 bool LaTeX::runMakeIndex(string const &file)
295 lyxerr[Debug::LATEX] << "idx file has been made,"
296 " running makeindex on file "
299 // It should be possible to set the switches for makeindex
300 // sorting style and such. It would also be very convenient
301 // to be able to make style files from within LyX. This has
302 // to come for a later time. (0.13 perhaps?)
303 string tmp = "makeindex -c -q ";
306 one.startscript(Systemcalls::System, tmp);
311 typedef pair<int, string> cmdret;
312 static cmdret do_popen(string const & cmd)
314 // One question is if we should use popen or
315 // create our own popen based on fork,exec,pipe
316 // of course the best would be to have a
317 // pstream (process stream), with the
318 // variants ipstream, opstream and
319 FILE * inf = popen(cmd.c_str(), "r");
323 ret += static_cast<char>(c);
326 int pret = pclose(inf);
327 return make_pair(pret, ret);
331 static string findtexfile(string const & fil, string const & format)
333 // If fil is a file with absolute path we just return it
334 if (AbsolutePath(fil)) return fil;
336 // Check in the current dir.
337 if (FileInfo(OnlyFilename(fil)).exist())
338 return OnlyFilename(fil);
340 // No we try to find it using kpsewhich.
341 string kpsecmd = "kpsewhich --format=" + format + " " + fil;
342 cmdret c = do_popen(kpsecmd);
344 lyxerr << "kpse status = " << c.first << "\n"
345 << "kpse result = `" << strip(c.second, '\n') << "'" << endl;
346 return c.first == 0 ? strip(c.second, '\n') : string();
350 bool LaTeX::runBibTeX(string const & file, DepTable & dep)
352 ifstream ifs(file.c_str());
354 bool using_bibtex = false;
355 while (getline(ifs, token)) {
356 if (contains(token, "\\bibdata{")) {
358 string::size_type a = token.find("\\bibdata{") + 9;
359 string::size_type b = token.find_first_of("}", a);
360 string data = token.substr(a, b - a);
361 // data is now all the bib files separated by ','
362 // get them one by one and pass them to the helper
364 b = data.find_first_of(',', 0);
366 if (b == string::npos)
369 l = data.substr(0, b - 0);
370 data.erase(0, b + 1);
374 ChangeExtension(l,"bib",false),
377 << full_l << "'" << endl;
378 if (!full_l.empty()) {
379 // add full_l to the dep file.
380 dep.insert(full_l, true);
382 } while (b != string::npos);
383 } else if (contains(token, "\\bibstyle{")) {
385 string::size_type a = token.find("\\bibstyle{") + 10;
386 string::size_type b = token.find_first_of("}", a);
387 string style = token.substr(a, b - a);
388 // token is now the style file
389 // pass it to the helper
392 ChangeExtension(style, "bst", false),
394 lyxerr << "style = `"
395 << full_l << "'" << endl;
396 if (!full_l.empty()) {
397 // add full_l to the dep file.
398 dep.insert(full_l, true);
404 string tmp= "bibtex ";
405 tmp += ChangeExtension(file, string(), true);
407 one.startscript(Systemcalls::System, tmp);
410 // bibtex was not run.
415 int LaTeX::scanLogFile(TeXErrors & terr)
417 int retval = NO_ERRORS;
418 string tmp = ChangeExtension(file, ".log", true);
419 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
420 ifstream ifs(tmp.c_str());
423 while (getline(ifs, token)) {
424 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
429 if (prefixIs(token, "LaTeX Warning:")) {
430 // Here shall we handle different
432 retval |= LATEX_WARNING;
433 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
434 if (contains(token, "Rerun to get cross-references")) {
437 << "We should rerun." << endl;
438 } else if (contains(token, "Citation")
439 && contains(token, "on page")
440 && contains(token, "undefined")) {
443 } else if (prefixIs(token, "Package")) {
445 retval |= PACKAGE_WARNING;
446 if (contains(token, "natbib Warning:")) {
448 if (contains(token, "Citation")
449 && contains(token, "on page")
450 && contains(token, "undefined")) {
453 } else if (contains(token, "Rerun LaTeX.")) {
454 // at least longtable.sty might use this.
457 } else if (prefixIs(token, "! ")) {
458 // Ok, we have something that looks like a TeX Error
459 // but what do we really have.
461 // Just get the error description:
462 string desc(token, 2);
463 if (contains(token, "LaTeX Error:"))
464 retval |= LATEX_ERROR;
468 if (prefixIs(tmp, "l.")) {
469 // we have a latex error
471 // get the line number:
473 sscanf(tmp.c_str(), "l.%d", &line);
474 // get the rest of the message:
475 string errstr(tmp, tmp.find(' '));
478 while (!contains(errstr, "l.")
480 && !prefixIs(tmp, "! ")
481 && !contains(tmp, "(job aborted")) {
487 << "line: " << line << '\n'
488 << "Desc: " << desc << '\n'
489 << "Text: " << errstr << endl;
490 terr.insertError(line, desc, errstr);
494 // information messages, TeX warnings and other
495 // warnings we have not caught earlier.
496 if (prefixIs(token, "Overfull ")) {
497 retval |= TEX_WARNING;
498 } else if (prefixIs(token, "Underfull ")) {
499 retval |= TEX_WARNING;
500 } else if (contains(token, "Rerun to get citations")) {
501 // Natbib seems to use this.
503 } else if (contains(token, "No pages of output")) {
504 // A dvi file was not created
506 } else if (contains(token, "That makes 100 errors")) {
507 // More than 100 errors were reprted
508 retval |= TOO_MANY_ERRORS;
512 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
517 void LaTeX::deplog(DepTable & head)
519 // This function reads the LaTeX log file end extracts all the external
520 // files used by the LaTeX run. The files are then entered into the
523 string logfile = ChangeExtension(file, ".log", true);
525 ifstream ifs(logfile.c_str());
527 // Now we read chars until we find a '('
534 // We now have c == '(', we now read the the sequence of
535 // chars until reaching EOL, ' ' or ')' and put that
539 if (c == '\n' || c == ' ' || c == ')')
543 lyxerr[Debug::LATEX] << "Found file: "
544 << foundfile << endl;
546 // Ok now we found a file.
547 // Now we should make sure that
548 // this is a file that we can
549 // access through the normal
551 // (1) foundfile is an
552 // absolute path and should
554 if (AbsolutePath(foundfile)) {
555 lyxerr[Debug::LATEX] << "AbsolutePath file: "
556 << foundfile << endl;
557 // On inital insert we want to do the update at once
558 // since this file can not be a file generated by
560 head.insert(foundfile, true);
564 // (2) foundfile is in the tmpdir
565 // insert it into head
566 if (FileInfo(OnlyFilename(foundfile)).exist()) {
567 if (suffixIs(foundfile, ".aux")) {
568 lyxerr[Debug::LATEX] << "We don't want "
569 << OnlyFilename(foundfile)
570 << " in the dep file"
572 } else if (suffixIs(foundfile, ".tex")) {
573 // This is a tex file generated by LyX
574 // and latex is not likely to change this
576 lyxerr[Debug::LATEX] << "Tmpdir TeX file: "
577 << OnlyFilename(foundfile)
579 head.insert(foundfile, true);
581 lyxerr[Debug::LATEX] << "In tmpdir file:"
582 << OnlyFilename(foundfile)
584 head.insert(OnlyFilename(foundfile));
589 << "Not a file or we are unable to find it."
595 void LaTeX::deptex(DepTable & head)
597 int except = AUX|LOG|DVI|BBL|IND|GLO;
600 for (int i = 0; i < file_count; ++i) {
601 if (!(all_files[i].file & except)) {
602 tmp = ChangeExtension(file,
603 all_files[i].extension,
605 lyxerr[Debug::LATEX] << "deptex: " << tmp << endl;
606 if (fi.newFile(tmp).exist())