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
21 #include "bufferlist.h"
25 #include "funcrequest.h"
26 #include "support/filetools.h"
27 #include "support/FileInfo.h"
28 #include "support/lstrings.h"
29 #include "support/lyxlib.h"
30 #include "support/systemcall.h"
31 #include "support/os.h"
32 #include "support/path.h"
34 #include <boost/regex.hpp>
37 #include <cstdio> // sscanf
39 #ifndef CXX_GLOBAL_CSTD
49 using boost::regex_match;
52 // TODO: in no particular order
53 // - get rid of the extern BufferList and the call to
54 // BufferList::updateIncludedTeXfiles, this should either
55 // be done before calling LaTeX::funcs or in a completely
57 // - the bibtex command options should be supported.
58 // - the makeindex style files should be taken care of with
59 // the dependency mechanism.
60 // - makeindex commandline options should be supported
61 // - somewhere support viewing of bibtex and makeindex log files.
62 // - we should perhaps also scan the bibtex log file
63 // - we should perhaps also scan the bibtex log file
65 extern BufferList bufferlist;
71 void TeXErrors::insertError(int line, string const & error_desc,
72 string const & error_text)
74 Error newerr(line, error_desc, error_text);
75 errors.push_back(newerr);
82 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
83 : cmd(latex), file(f), path(p)
86 depfile = file + ".dep";
87 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
89 output_file = ChangeExtension(file,".pdf");
91 output_file = ChangeExtension(file,".dvi");
96 void LaTeX::deleteFilesOnError() const
98 // currently just a dummy function.
100 // What files do we have to delete?
102 // This will at least make latex do all the runs
103 lyx::unlink(depfile);
105 // but the reason for the error might be in a generated file...
107 string ofname = OnlyFilename(file);
110 string bbl = ChangeExtension(ofname, ".bbl");
114 string ind = ChangeExtension(ofname, ".ind");
117 // Also remove the aux file
118 string aux = ChangeExtension(ofname, ".aux");
123 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
124 // We know that this function will only be run if the lyx buffer
125 // has been changed. We also know that a newly written .tex file
126 // is always different from the previous one because of the date
127 // in it. However it seems safe to run latex (at least) on time each
128 // time the .tex file changes.
130 int scanres = NO_ERRORS;
131 unsigned int count = 0; // number of times run
132 num_errors = 0; // just to make sure.
133 const unsigned int MAX_RUN = 6;
134 DepTable head; // empty head
135 bool rerun = false; // rerun requested
137 // The class LaTeX does not know the temp path.
138 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
140 // Never write the depfile if an error was encountered.
143 // first check if the file dependencies exist:
144 // ->If it does exist
145 // check if any of the files mentioned in it have
146 // changed (done using a checksum).
148 // run latex once and
149 // remake the dependency file
150 // -> if not changed:
151 // just return there is nothing to do for us.
152 // ->if it doesn't exist
154 // run latex once (we need to run latex once anyway) and
155 // remake the dependency file.
158 FileInfo fi(depfile);
159 bool had_depfile = fi.exist();
160 bool run_bibtex = false;
161 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
164 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
165 // Read the dep file:
167 // Update the checksums
169 // Can't just check if anything has changed because it might have aborted
170 // on error last time... in which cas we need to re-run latex
171 // and collect the error messages (even if they are the same).
172 if (!FileInfo(output_file).exist()) {
173 lyxerr[Debug::DEPEND]
174 << "re-running LaTeX because output file doesn't exist." << endl;
175 } else if (!head.sumchange()) {
176 lyxerr[Debug::DEPEND] << "return no_change" << endl;
179 lyxerr[Debug::DEPEND]
180 << "Dependency file has changed" << endl;
183 if (head.extchanged(".bib") || head.extchanged(".bst"))
186 lyxerr[Debug::DEPEND]
187 << "Dependency file does not exist" << endl;
189 /// We scan the aux file even when had_depfile = false,
190 /// because we can run pdflatex on the file after running latex on it,
191 /// in which case we will not need to run bibtex again.
192 vector<Aux_Info> bibtex_info_old;
194 bibtex_info_old = scanAuxFiles(aux_file);
197 lyxerr[Debug::LATEX] << "Run #" << count << endl;
200 str << _("LaTeX run number") << ' ' << count;
201 lfun->dispatch(FuncRequest(LFUN_MESSAGE, str.str().c_str()));
205 scanres = scanLogFile(terr);
206 if (scanres & ERROR_RERUN) {
207 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
209 scanres = scanLogFile(terr);
212 if (scanres & ERRORS) {
213 deleteFilesOnError();
214 return scanres; // return on error
217 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
218 if (!run_bibtex && bibtex_info_old != bibtex_info)
221 // update the dependencies.
222 deplog(head); // reads the latex log
226 // At this point we must run external programs if needed.
227 // makeindex will be run if a .idx file changed or was generated.
228 // And if there were undefined citations or changes in references
229 // the .aux file is checked for signs of bibtex. Bibtex is then run
233 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
235 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
237 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
240 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
244 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
245 if (scanres & UNDEF_CIT || run_bibtex) {
246 // Here we must scan the .aux file and look for
247 // "\bibdata" and/or "\bibstyle". If one of those
248 // tags is found -> run bibtex and set rerun = true;
250 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
252 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
255 updateBibtexDependencies(head, bibtex_info);
256 rerun |= runBibTeX(bibtex_info);
257 } else if (!had_depfile) {
258 /// If we run pdflatex on the file after running latex on it,
259 /// then we do not need to run bibtex, but we do need to
260 /// insert the .bib and .bst files into the .dep-pdf file.
261 updateBibtexDependencies(head, bibtex_info);
265 // we know on this point that latex has been run once (or we just
266 // returned) and the question now is to decide if we need to run
267 // it any more. This is done by asking if any of the files in the
268 // dependency file has changed. (remember that the checksum for
269 // a given file is reported to have changed if it just was created)
270 // -> if changed or rerun == true:
271 // run latex once more and
272 // update the dependency structure
273 // -> if not changed:
274 // we does nothing at this point
276 if (rerun || head.sumchange()) {
279 lyxerr[Debug::DEPEND]
280 << "Dep. file has changed or rerun requested" << endl;
282 << "Run #" << count << endl;
285 str << _("LaTeX run number") << ' ' << count;
286 // check lyxstring string stream and gcc 3.1 before fixing
287 lfun->dispatch(FuncRequest(LFUN_MESSAGE, str.str().c_str()));
291 scanres = scanLogFile(terr);
292 if (scanres & ERRORS) {
293 deleteFilesOnError();
294 return scanres; // return on error
297 // update the depedencies
298 deplog(head); // reads the latex log
301 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
305 // The inclusion of files generated by external programs like
306 // makeindex or bibtex might have done changes to pagenumbereing,
307 // etc. And because of this we must run the external programs
308 // again to make sure everything is redone correctly.
309 // Also there should be no need to run the external programs any
312 // run makeindex if the <file>.idx has changed or was generated.
313 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
315 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
317 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
320 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
324 // we will only run latex more if the log file asks for it.
325 // or if the sumchange() is true.
326 // -> rerun asked for:
328 // remake the dependency file
329 // goto 2 or return if max runs are reached.
330 // -> rerun not asked for:
331 // just return (fall out of bottom of func)
333 while ((head.sumchange() || rerun || (scanres & RERUN))
334 && count < MAX_RUN) {
335 // Yes rerun until message goes away, or until
336 // MAX_RUNS are reached.
339 lyxerr[Debug::LATEX] << "Run #" << count << endl;
342 str << _("LaTeX run number") << ' ' << count;
343 lfun->dispatch(FuncRequest(LFUN_MESSAGE, str.str().c_str()));
347 scanres = scanLogFile(terr);
348 if (scanres & ERRORS) {
349 deleteFilesOnError();
350 return scanres; // return on error
357 // Write the dependencies to file.
359 lyxerr[Debug::LATEX] << "Done." << endl;
364 int LaTeX::operator()()
367 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
368 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
369 string tmp = cmd + ' ' + file + " > nul";
372 return one.startscript(Systemcall::Wait, tmp);
376 bool LaTeX::runMakeIndex(string const & f)
378 lyxerr[Debug::LATEX] << "idx file has been made,"
379 " running makeindex on file "
382 // It should be possible to set the switches for makeindex
383 // sorting style and such. It would also be very convenient
384 // to be able to make style files from within LyX. This has
385 // to come for a later time.
386 string tmp = "makeindex -c -q ";
389 one.startscript(Systemcall::Wait, tmp);
394 vector<Aux_Info> const
395 LaTeX::scanAuxFiles(string const & file)
397 vector<Aux_Info> result;
399 result.push_back(scanAuxFile(file));
401 for (int i = 1; i < 1000; ++i) {
402 string file2 = ChangeExtension(file, "") + "." + tostr(i)
407 result.push_back(scanAuxFile(file2));
413 Aux_Info const LaTeX::scanAuxFile(string const & file)
416 result.aux_file = file;
417 scanAuxFile(file, result);
422 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
424 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
426 ifstream ifs(file.c_str());
428 regex reg1("\\\\citation\\{([^}]+)\\}");
429 regex reg2("\\\\bibdata\\{([^}]+)\\}");
430 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
431 regex reg4("\\\\@input\\{([^}]+)\\}");
433 while (getline(ifs, token)) {
434 token = rtrim(token, "\r");
436 if (regex_match(token, sub, reg1)) {
437 string data = sub.str(1);
438 while (!data.empty()) {
440 data = split(data, citation, ',');
441 lyxerr[Debug::LATEX] << "Citation: "
443 aux_info.citations.insert(citation);
445 } else if (regex_match(token, sub, reg2)) {
446 string data = sub.str(1);
447 // data is now all the bib files separated by ','
448 // get them one by one and pass them to the helper
449 while (!data.empty()) {
451 data = split(data, database, ',');
452 database = ChangeExtension(database, "bib");
453 lyxerr[Debug::LATEX] << "Bibtex database: `"
454 << database << "'" << endl;
455 aux_info.databases.insert(database);
457 } else if (regex_match(token, sub, reg3)) {
458 string style = sub.str(1);
459 // token is now the style file
460 // pass it to the helper
461 style = ChangeExtension(style, "bst");
462 lyxerr[Debug::LATEX] << "Bibtex style: `"
463 << style << "'" << endl;
464 aux_info.styles.insert(style);
465 } else if (regex_match(token, sub, reg4)) {
466 string file2 = sub.str(1);
467 scanAuxFile(file2, aux_info);
473 void LaTeX::updateBibtexDependencies(DepTable & dep,
474 vector<Aux_Info> const & bibtex_info)
476 // Since a run of Bibtex mandates more latex runs it is ok to
477 // remove all ".bib" and ".bst" files.
478 dep.remove_files_with_extension(".bib");
479 dep.remove_files_with_extension(".bst");
480 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
482 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
483 it != bibtex_info.end(); ++it) {
484 for (set<string>::const_iterator it2 = it->databases.begin();
485 it2 != it->databases.end(); ++it2) {
486 string file = findtexfile(*it2, "bib");
488 dep.insert(file, true);
491 for (set<string>::const_iterator it2 = it->styles.begin();
492 it2 != it->styles.end(); ++it2) {
493 string file = findtexfile(*it2, "bst");
495 dep.insert(file, true);
501 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
504 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
505 it != bibtex_info.end(); ++it) {
506 if (it->databases.empty())
510 string tmp = "bibtex ";
511 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
513 one.startscript(Systemcall::Wait, tmp);
515 // Return whether bibtex was run
520 int LaTeX::scanLogFile(TeXErrors & terr)
524 int retval = NO_ERRORS;
525 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
526 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
527 ifstream ifs(tmp.c_str());
530 while (getline(ifs, token)) {
531 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
536 if (prefixIs(token, "LaTeX Warning:")) {
537 // Here shall we handle different
539 retval |= LATEX_WARNING;
540 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
541 if (contains(token, "Rerun to get cross-references")) {
544 << "We should rerun." << endl;
545 } else if (contains(token, "Citation")
546 && contains(token, "on page")
547 && contains(token, "undefined")) {
550 } else if (prefixIs(token, "Package")) {
552 retval |= PACKAGE_WARNING;
553 if (contains(token, "natbib Warning:")) {
555 if (contains(token, "Citation")
556 && contains(token, "on page")
557 && contains(token, "undefined")) {
560 } else if (contains(token, "run BibTeX")) {
562 } else if (contains(token, "Rerun LaTeX") ||
563 contains(token, "Rerun to get")) {
564 // at least longtable.sty and bibtopic.sty
567 << "We should rerun." << endl;
570 } else if (prefixIs(token, "(")) {
571 if (contains(token, "Rerun LaTeX") ||
572 contains(token, "Rerun to get")) {
575 << "We should rerun." << endl;
578 } else if (prefixIs(token, "! ")) {
579 // Ok, we have something that looks like a TeX Error
580 // but what do we really have.
582 // Just get the error description:
583 string desc(token, 2);
584 if (contains(token, "LaTeX Error:"))
585 retval |= LATEX_ERROR;
590 if (!getline(ifs, tmp))
594 } while (!prefixIs(tmp, "l."));
595 if (prefixIs(tmp, "l.")) {
596 // we have a latex error
598 if (contains(desc, "Package babel Error: You haven't defined the language"))
599 retval |= ERROR_RERUN;
600 // get the line number:
602 sscanf(tmp.c_str(), "l.%d", &line);
603 // get the rest of the message:
604 string errstr(tmp, tmp.find(' '));
607 while (!contains(errstr, "l.")
609 && !prefixIs(tmp, "! ")
610 && !contains(tmp, "(job aborted")) {
616 << "line: " << line << '\n'
617 << "Desc: " << desc << '\n'
618 << "Text: " << errstr << endl;
619 if (line == last_line)
625 if (line_count <= 5) {
626 terr.insertError(line, desc, errstr);
631 // information messages, TeX warnings and other
632 // warnings we have not caught earlier.
633 if (prefixIs(token, "Overfull ")) {
634 retval |= TEX_WARNING;
635 } else if (prefixIs(token, "Underfull ")) {
636 retval |= TEX_WARNING;
637 } else if (contains(token, "Rerun to get citations")) {
638 // Natbib seems to use this.
640 } else if (contains(token, "No pages of output")) {
641 // A dvi file was not created
643 } else if (contains(token, "That makes 100 errors")) {
644 // More than 100 errors were reprted
645 retval |= TOO_MANY_ERRORS;
649 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
654 void LaTeX::deplog(DepTable & head)
656 // This function reads the LaTeX log file end extracts all the external
657 // files used by the LaTeX run. The files are then entered into the
660 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
662 regex reg1("\\)* *\\(([^ )]+).*");
663 regex reg2("File: ([^ ]+).*");
664 regex reg3("No file ([^ ]+)\\..*");
665 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
666 // If an index should be created, MikTex does not write a line like
667 // \openout# = 'sample,idx'.
668 // but intstead only a line like this into the log:
669 // Writing index file sample.idx
670 regex reg5("Writing index file ([^ ]+).*");
671 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
673 ifstream ifs(logfile.c_str());
675 // Ok, the scanning of files here is not sufficient.
676 // Sometimes files are named by "File: xxx" only
677 // So I think we should use some regexps to find files instead.
678 // "(\([^ ]+\)" should match the "(file " variant
679 // "File: \([^ ]+\)" should match the "File: file" variant
683 token = rtrim(token, "\r");
684 if (token.empty()) continue;
687 if (regex_match(token, sub, reg1)) {
688 foundfile = sub.str(1);
689 } else if (regex_match(token, sub, reg2)) {
690 foundfile = sub.str(1);
691 } else if (regex_match(token, sub, reg3)) {
692 foundfile = sub.str(1);
693 } else if (regex_match(token, sub, reg4)) {
694 foundfile = sub.str(1);
695 } else if (regex_match(token, sub, reg5)) {
696 foundfile = sub.str(1);
701 // convert from native os path to unix path
702 foundfile = os::internal_path(foundfile);
704 lyxerr[Debug::DEPEND] << "Found file: "
705 << foundfile << endl;
707 // Ok now we found a file.
708 // Now we should make sure that this is a file that we can
709 // access through the normal paths.
710 // We will not try any fancy search methods to
713 // (1) foundfile is an
714 // absolute path and should
716 if (AbsolutePath(foundfile)) {
717 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
718 << foundfile << endl;
719 // On initial insert we want to do the update at once
720 // since this file can not be a file generated by
722 if (FileInfo(foundfile).exist())
723 head.insert(foundfile, true);
726 // (2) foundfile is in the tmpdir
727 // insert it into head
728 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
729 if (regex_match(foundfile, unwanted)) {
730 lyxerr[Debug::DEPEND]
732 << OnlyFilename(foundfile)
733 << " in the dep file"
735 } else if (suffixIs(foundfile, ".tex")) {
736 // This is a tex file generated by LyX
737 // and latex is not likely to change this
739 lyxerr[Debug::DEPEND]
740 << "Tmpdir TeX file: "
741 << OnlyFilename(foundfile)
743 head.insert(foundfile, true);
745 lyxerr[Debug::DEPEND]
747 << OnlyFilename(foundfile)
749 head.insert(OnlyFilename(foundfile));
752 lyxerr[Debug::DEPEND]
753 << "Not a file or we are unable to find it."
757 // Make sure that the main .tex file is in the dependancy file.
758 head.insert(OnlyFilename(file), true);