1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
5 * Copyright 1995 Matthias Ettrich
6 * Copyright 1995-2001 The LyX Team.
8 * This file is Copyright 1996-2001
11 * ======================================================
17 #pragma implementation
22 #include "support/filetools.h"
23 #include "support/os.h"
24 #include "support/FileInfo.h"
26 #include "support/lyxlib.h"
27 #include "support/syscall.h"
28 #include "support/syscontr.h"
29 #include "support/path.h"
30 #include "support/LRegex.h"
31 #include "support/LSubstring.h"
32 #include "support/lstrings.h"
33 #include "bufferlist.h"
35 #include "lyx_gui_misc.h"
44 // TODO: in no particular order
45 // - get rid of the extern BufferList and the call to
46 // BufferList::updateIncludedTeXfiles, this should either
47 // be done before calling LaTeX::funcs or in a completely
49 // - the bibtex command options should be supported.
50 // - the makeindex style files should be taken care of with
51 // the dependency mechanism.
52 // - makeindex commandline options should be supported
53 // - somewhere support viewing of bibtex and makeindex log files.
54 // - we should perhaps also scan the bibtex log file
55 // - we should perhaps also scan the bibtex log file
57 extern BufferList bufferlist;
63 void TeXErrors::insertError(int line, string const & error_desc,
64 string const & error_text)
66 Error newerr(line, error_desc, error_text);
67 errors.push_back(newerr);
74 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
75 : cmd(latex), file(f), path(p)
78 depfile = file + ".dep";
79 if (prefixIs(cmd, "pdf")) // Do we use pdflatex ?
84 void LaTeX::deleteFilesOnError() const
86 // currently just a dummy function.
88 // What files do we have to delete?
90 // This will at least make latex do all the runs
93 // but the reason for the error might be in a generated file...
95 string ofname = OnlyFilename(file);
98 string bbl = ChangeExtension(ofname, ".bbl");
102 string ind = ChangeExtension(ofname, ".ind");
105 // Also remove the aux file
106 string aux = ChangeExtension(ofname, ".aux");
111 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
112 // We know that this function will only be run if the lyx buffer
113 // has been changed. We also know that a newly written .tex file
114 // is always different from the previous one because of the date
115 // in it. However it seems safe to run latex (at least) on time each
116 // time the .tex file changes.
118 int scanres = NO_ERRORS;
119 unsigned int count = 0; // number of times run
120 num_errors = 0; // just to make sure.
121 const unsigned int MAX_RUN = 6;
122 DepTable head; // empty head
123 bool rerun = false; // rerun requested
125 // The class LaTeX does not know the temp path.
126 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
128 // Never write the depfile if an error was encountered.
131 // first check if the file dependencies exist:
132 // ->If it does exist
133 // check if any of the files mentioned in it have
134 // changed (done using a checksum).
136 // run latex once and
137 // remake the dependency file
138 // -> if not changed:
139 // just return there is nothing to do for us.
140 // ->if it doesn't exist
142 // run latex once (we need to run latex once anyway) and
143 // remake the dependency file.
146 FileInfo fi(depfile);
147 bool had_depfile = fi.exist();
148 bool run_bibtex = false;
149 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
152 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
153 // Read the dep file:
155 // Update the checksums
157 if (!head.sumchange()) {
158 lyxerr[Debug::DEPEND] << "return no_change" << endl;
161 lyxerr[Debug::DEPEND]
162 << "Dependency file has changed" << endl;
164 if (head.extchanged(".bib") || head.extchanged(".bst"))
167 lyxerr[Debug::DEPEND]
168 << "Dependency file does not exist" << endl;
170 /// We scan the aux file even when had_depfile = false,
171 /// because we can run pdflatex on the file after running latex on it,
172 /// in which case we will not need to run bibtex again.
173 vector<Aux_Info> bibtex_info_old;
175 bibtex_info_old = scanAuxFiles(aux_file);
178 lyxerr[Debug::LATEX] << "Run #" << count << endl;
181 str << _("LaTeX run number") << ' ' << count;
182 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
186 scanres = scanLogFile(terr);
187 if (scanres & ERROR_RERUN) {
188 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
190 scanres = scanLogFile(terr);
193 if (scanres & ERRORS) {
194 deleteFilesOnError();
195 return scanres; // return on error
198 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
199 if (!run_bibtex && bibtex_info_old != bibtex_info)
202 // update the dependencies.
203 deplog(head); // reads the latex log
207 // At this point we must run external programs if needed.
208 // makeindex will be run if a .idx file changed or was generated.
209 // And if there were undefined citations or changes in references
210 // the .aux file is checked for signs of bibtex. Bibtex is then run
214 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
216 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
218 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
221 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
225 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
226 if (scanres & UNDEF_CIT || run_bibtex) {
227 // Here we must scan the .aux file and look for
228 // "\bibdata" and/or "\bibstyle". If one of those
229 // tags is found -> run bibtex and set rerun = true;
231 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
233 lfun->dispatch(LFUN_MESSAGE, _("Running BibTeX."));
236 updateBibtexDependencies(head, bibtex_info);
237 rerun |= runBibTeX(bibtex_info);
238 } else if (!had_depfile) {
239 /// If we run pdflatex on the file after running latex on it,
240 /// then we do not need to run bibtex, but we do need to
241 /// insert the .bib and .bst files into the .dep-pdf file.
242 updateBibtexDependencies(head, bibtex_info);
246 // we know on this point that latex has been run once (or we just
247 // returned) and the question now is to decide if we need to run
248 // it any more. This is done by asking if any of the files in the
249 // dependency file has changed. (remember that the checksum for
250 // a given file is reported to have changed if it just was created)
251 // -> if changed or rerun == true:
252 // run latex once more and
253 // update the dependency structure
254 // -> if not changed:
255 // we does nothing at this point
257 if (rerun || head.sumchange()) {
260 lyxerr[Debug::DEPEND]
261 << "Dep. file has changed or rerun requested" << endl;
263 << "Run #" << count << endl;
266 str << _("LaTeX run number") << ' ' << count;
267 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
271 scanres = scanLogFile(terr);
272 if (scanres & ERRORS) {
273 deleteFilesOnError();
274 return scanres; // return on error
277 // update the depedencies
278 deplog(head); // reads the latex log
281 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
285 // The inclusion of files generated by external programs like
286 // makeindex or bibtex might have done changes to pagenumbereing,
287 // etc. And because of this we must run the external programs
288 // again to make sure everything is redone correctly.
289 // Also there should be no need to run the external programs any
292 // run makeindex if the <file>.idx has changed or was generated.
293 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
295 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
297 lfun->dispatch(LFUN_MESSAGE, _("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 & 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;
322 str << _("LaTeX run number") << ' ' << count;
323 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
327 scanres = scanLogFile(terr);
328 if (scanres & ERRORS) {
329 deleteFilesOnError();
330 return scanres; // return on error
337 // Write the dependencies to file.
339 lyxerr[Debug::LATEX] << "Done." << endl;
344 int LaTeX::operator()()
347 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
348 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
349 string tmp = cmd + ' ' + file + " > nul";
352 return one.startscript(Systemcalls::System, tmp);
356 bool LaTeX::runMakeIndex(string const & f)
358 lyxerr[Debug::LATEX] << "idx file has been made,"
359 " running makeindex on file "
362 // It should be possible to set the switches for makeindex
363 // sorting style and such. It would also be very convenient
364 // to be able to make style files from within LyX. This has
365 // to come for a later time. (0.13 perhaps?)
366 string tmp = "makeindex -c -q ";
369 one.startscript(Systemcalls::System, tmp);
374 vector<Aux_Info> const
375 LaTeX::scanAuxFiles(string const & file)
377 vector<Aux_Info> result;
379 result.push_back(scanAuxFile(file));
381 for (int i = 1; i < 1000; ++i) {
382 string file2 = ChangeExtension(file, "") + "." + tostr(i)
387 result.push_back(scanAuxFile(file2));
393 Aux_Info const LaTeX::scanAuxFile(string const & file)
396 result.aux_file = file;
397 scanAuxFile(file, result);
402 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
404 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
406 ifstream ifs(file.c_str());
408 LRegex reg1("\\\\citation\\{([^}]+)\\}");
409 LRegex reg2("\\\\bibdata\\{([^}]+)\\}");
410 LRegex reg3("\\\\bibstyle\\{([^}]+)\\}");
411 LRegex reg4("\\\\@input\\{([^}]+)\\}");
413 while (getline(ifs, token)) {
414 token = strip(token, '\r');
415 if (reg1.exact_match(token)) {
416 LRegex::SubMatches const & sub = reg1.exec(token);
417 string data = LSubstring(token, sub[1].first,
419 while (!data.empty()) {
421 data = split(data, citation, ',');
422 lyxerr[Debug::LATEX] << "Citation: "
424 aux_info.citations.insert(citation);
426 } else if (reg2.exact_match(token)) {
427 LRegex::SubMatches const & sub = reg2.exec(token);
428 string data = LSubstring(token, sub[1].first,
430 // data is now all the bib files separated by ','
431 // get them one by one and pass them to the helper
432 while (!data.empty()) {
434 data = split(data, database, ',');
435 database = ChangeExtension(database, "bib");
436 lyxerr[Debug::LATEX] << "Bibtex database: `"
437 << database << "'" << endl;
438 aux_info.databases.insert(database);
440 } else if (reg3.exact_match(token)) {
441 LRegex::SubMatches const & sub = reg3.exec(token);
442 string style = LSubstring(token, sub[1].first,
444 // token is now the style file
445 // pass it to the helper
446 style = ChangeExtension(style, "bst");
447 lyxerr[Debug::LATEX] << "Bibtex style: `"
448 << style << "'" << endl;
449 aux_info.styles.insert(style);
450 } else if (reg4.exact_match(token)) {
451 LRegex::SubMatches const & sub = reg4.exec(token);
452 string file2 = LSubstring(token, sub[1].first,
454 scanAuxFile(file2, aux_info);
460 void LaTeX::updateBibtexDependencies(DepTable & dep,
461 vector<Aux_Info> const & bibtex_info)
463 // Since a run of Bibtex mandates more latex runs it is ok to
464 // remove all ".bib" and ".bst" files.
465 dep.remove_files_with_extension(".bib");
466 dep.remove_files_with_extension(".bst");
467 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
469 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
470 it != bibtex_info.end(); ++it) {
471 for (set<string>::const_iterator it2 = it->databases.begin();
472 it2 != it->databases.end(); ++it2) {
473 string file = findtexfile(*it2, "bib");
475 dep.insert(file, true);
478 for (set<string>::const_iterator it2 = it->styles.begin();
479 it2 != it->styles.end(); ++it2) {
480 string file = findtexfile(*it2, "bst");
482 dep.insert(file, true);
488 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
491 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
492 it != bibtex_info.end(); ++it) {
493 if (it->databases.empty())
497 string tmp = "bibtex ";
498 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
500 one.startscript(Systemcalls::System, tmp);
502 // Return whether bibtex was run
507 int LaTeX::scanLogFile(TeXErrors & terr)
511 int retval = NO_ERRORS;
512 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
513 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
514 ifstream ifs(tmp.c_str());
517 while (getline(ifs, token)) {
518 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
523 if (prefixIs(token, "LaTeX Warning:")) {
524 // Here shall we handle different
526 retval |= LATEX_WARNING;
527 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
528 if (contains(token, "Rerun to get cross-references")) {
531 << "We should rerun." << endl;
532 } else if (contains(token, "Citation")
533 && contains(token, "on page")
534 && contains(token, "undefined")) {
537 } else if (prefixIs(token, "Package")) {
539 retval |= PACKAGE_WARNING;
540 if (contains(token, "natbib Warning:")) {
542 if (contains(token, "Citation")
543 && contains(token, "on page")
544 && contains(token, "undefined")) {
547 } else if (contains(token, "run BibTeX")) {
549 } else if (contains(token, "Rerun LaTeX") ||
550 contains(token, "Rerun to get")) {
551 // at least longtable.sty and bibtopic.sty
554 << "We should rerun." << endl;
557 } else if (prefixIs(token, "(")) {
558 if (contains(token, "Rerun LaTeX") ||
559 contains(token, "Rerun to get")) {
562 << "We should rerun." << endl;
565 } else if (prefixIs(token, "! ")) {
566 // Ok, we have something that looks like a TeX Error
567 // but what do we really have.
569 // Just get the error description:
570 string desc(token, 2);
571 if (contains(token, "LaTeX Error:"))
572 retval |= LATEX_ERROR;
577 if (!getline(ifs, tmp))
581 } while (!prefixIs(tmp, "l."));
582 if (prefixIs(tmp, "l.")) {
583 // we have a latex error
585 if (contains(desc, "Package babel Error: You haven't defined the language"))
586 retval |= ERROR_RERUN;
587 // get the line number:
589 sscanf(tmp.c_str(), "l.%d", &line);
590 // get the rest of the message:
591 string errstr(tmp, tmp.find(' '));
594 while (!contains(errstr, "l.")
596 && !prefixIs(tmp, "! ")
597 && !contains(tmp, "(job aborted")) {
603 << "line: " << line << '\n'
604 << "Desc: " << desc << '\n'
605 << "Text: " << errstr << endl;
606 if (line == last_line)
612 if (line_count <= 5) {
613 terr.insertError(line, desc, errstr);
618 // information messages, TeX warnings and other
619 // warnings we have not caught earlier.
620 if (prefixIs(token, "Overfull ")) {
621 retval |= TEX_WARNING;
622 } else if (prefixIs(token, "Underfull ")) {
623 retval |= TEX_WARNING;
624 } else if (contains(token, "Rerun to get citations")) {
625 // Natbib seems to use this.
627 } else if (contains(token, "No pages of output")) {
628 // A dvi file was not created
630 } else if (contains(token, "That makes 100 errors")) {
631 // More than 100 errors were reprted
632 retval |= TOO_MANY_ERRORS;
636 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
641 void LaTeX::deplog(DepTable & head)
643 // This function reads the LaTeX log file end extracts all the external
644 // files used by the LaTeX run. The files are then entered into the
647 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
649 LRegex reg1("\\)* *\\(([^ )]+).*");
650 LRegex reg2("File: ([^ ]+).*");
651 LRegex reg3("No file ([^ ]+)\\..*");
652 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
653 // If an index should be created, MikTex does not write a line like
654 // \openout# = 'sample,idx'.
655 // but intstead only a line like this into the log:
656 // Writing index file sample.idx
657 LRegex reg5("Writing index file ([^ ]+).*");
658 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
660 ifstream ifs(logfile.c_str());
662 // Ok, the scanning of files here is not sufficient.
663 // Sometimes files are named by "File: xxx" only
664 // So I think we should use some regexps to find files instead.
665 // "(\([^ ]+\)" should match the "(file " variant
666 // "File: \([^ ]+\)" should match the "File: file" variant
670 token = strip(token, '\r');
671 if (token.empty()) continue;
673 if (reg1.exact_match(token)) {
674 LRegex::SubMatches const & sub = reg1.exec(token);
675 foundfile = LSubstring(token, sub[1].first,
677 } else if (reg2.exact_match(token)) {
678 LRegex::SubMatches const & sub = reg2.exec(token);
679 foundfile = LSubstring(token, sub[1].first,
681 } else if (reg3.exact_match(token)) {
682 LRegex::SubMatches const & sub = reg3.exec(token);
683 foundfile = LSubstring(token, sub[1].first,
685 } else if (reg4.exact_match(token)) {
686 LRegex::SubMatches const & sub = reg4.exec(token);
687 foundfile = LSubstring(token, sub[1].first,
689 } else if (reg5.exact_match(token)) {
690 LRegex::SubMatches const & sub = reg5.exec(token);
691 foundfile = LSubstring(token, sub[1].first,
697 // convert from native os path to unix path
698 foundfile = os::internal_path(foundfile);
700 lyxerr[Debug::DEPEND] << "Found file: "
701 << foundfile << endl;
703 // Ok now we found a file.
704 // Now we should make sure that this is a file that we can
705 // access through the normal paths.
706 // We will not try any fancy search methods to
709 // (1) foundfile is an
710 // absolute path and should
712 if (AbsolutePath(foundfile)) {
713 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
714 << foundfile << endl;
715 // On initial insert we want to do the update at once
716 // since this file can not be a file generated by
718 if (FileInfo(foundfile).exist())
719 head.insert(foundfile, true);
722 // (2) foundfile is in the tmpdir
723 // insert it into head
724 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
725 if (unwanted.exact_match(foundfile)) {
726 lyxerr[Debug::DEPEND]
728 << OnlyFilename(foundfile)
729 << " in the dep file"
731 } else if (suffixIs(foundfile, ".tex")) {
732 // This is a tex file generated by LyX
733 // and latex is not likely to change this
735 lyxerr[Debug::DEPEND]
736 << "Tmpdir TeX file: "
737 << OnlyFilename(foundfile)
739 head.insert(foundfile, true);
741 lyxerr[Debug::DEPEND]
743 << OnlyFilename(foundfile)
745 head.insert(OnlyFilename(foundfile));
748 lyxerr[Debug::DEPEND]
749 << "Not a file or we are unable to find it."
753 // Make sure that the main .tex file is in the dependancy file.
754 head.insert(OnlyFilename(file), true);