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 "bufferlist.h"
26 #include "support/filetools.h"
27 #include "support/FileInfo.h"
28 #include "support/LRegex.h"
29 #include "support/LSubstring.h"
30 #include "support/lstrings.h"
31 #include "support/lyxlib.h"
32 #include "support/systemcall.h"
33 #include "support/os.h"
34 #include "support/path.h"
35 #include <cstdio> // sscanf
43 // TODO: in no particular order
44 // - get rid of the extern BufferList and the call to
45 // BufferList::updateIncludedTeXfiles, this should either
46 // be done before calling LaTeX::funcs or in a completely
48 // - the bibtex command options should be supported.
49 // - the makeindex style files should be taken care of with
50 // the dependency mechanism.
51 // - makeindex commandline options should be supported
52 // - somewhere support viewing of bibtex and makeindex log files.
53 // - we should perhaps also scan the bibtex log file
54 // - we should perhaps also scan the bibtex log file
56 extern BufferList bufferlist;
62 void TeXErrors::insertError(int line, string const & error_desc,
63 string const & error_text)
65 Error newerr(line, error_desc, error_text);
66 errors.push_back(newerr);
73 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
74 : cmd(latex), file(f), path(p)
77 depfile = file + ".dep";
78 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
80 output_file = ChangeExtension(file,".pdf");
82 output_file = ChangeExtension(file,".dvi");
87 void LaTeX::deleteFilesOnError() const
89 // currently just a dummy function.
91 // What files do we have to delete?
93 // This will at least make latex do all the runs
96 // but the reason for the error might be in a generated file...
98 string ofname = OnlyFilename(file);
101 string bbl = ChangeExtension(ofname, ".bbl");
105 string ind = ChangeExtension(ofname, ".ind");
108 // Also remove the aux file
109 string aux = ChangeExtension(ofname, ".aux");
114 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
115 // We know that this function will only be run if the lyx buffer
116 // has been changed. We also know that a newly written .tex file
117 // is always different from the previous one because of the date
118 // in it. However it seems safe to run latex (at least) on time each
119 // time the .tex file changes.
121 int scanres = NO_ERRORS;
122 unsigned int count = 0; // number of times run
123 num_errors = 0; // just to make sure.
124 const unsigned int MAX_RUN = 6;
125 DepTable head; // empty head
126 bool rerun = false; // rerun requested
128 // The class LaTeX does not know the temp path.
129 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
131 // Never write the depfile if an error was encountered.
134 // first check if the file dependencies exist:
135 // ->If it does exist
136 // check if any of the files mentioned in it have
137 // changed (done using a checksum).
139 // run latex once and
140 // remake the dependency file
141 // -> if not changed:
142 // just return there is nothing to do for us.
143 // ->if it doesn't exist
145 // run latex once (we need to run latex once anyway) and
146 // remake the dependency file.
149 FileInfo fi(depfile);
150 bool had_depfile = fi.exist();
151 bool run_bibtex = false;
152 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
155 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
156 // Read the dep file:
158 // Update the checksums
160 // Can't just check if anything has changed because it might have aborted
161 // on error last time... in which cas we need to re-run latex
162 // and collect the error messages (even if they are the same).
163 if (!FileInfo(output_file).exist()) {
164 lyxerr[Debug::DEPEND]
165 << "re-running LaTeX because output file doesn't exist." << endl;
166 } else if (!head.sumchange()) {
167 lyxerr[Debug::DEPEND] << "return no_change" << endl;
170 lyxerr[Debug::DEPEND]
171 << "Dependency file has changed" << endl;
174 if (head.extchanged(".bib") || head.extchanged(".bst"))
177 lyxerr[Debug::DEPEND]
178 << "Dependency file does not exist" << endl;
180 /// We scan the aux file even when had_depfile = false,
181 /// because we can run pdflatex on the file after running latex on it,
182 /// in which case we will not need to run bibtex again.
183 vector<Aux_Info> bibtex_info_old;
185 bibtex_info_old = scanAuxFiles(aux_file);
188 lyxerr[Debug::LATEX] << "Run #" << count << endl;
191 str << _("LaTeX run number") << ' ' << count;
192 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
196 scanres = scanLogFile(terr);
197 if (scanres & ERROR_RERUN) {
198 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
200 scanres = scanLogFile(terr);
203 if (scanres & ERRORS) {
204 deleteFilesOnError();
205 return scanres; // return on error
208 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
209 if (!run_bibtex && bibtex_info_old != bibtex_info)
212 // update the dependencies.
213 deplog(head); // reads the latex log
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(OnlyFilename(ChangeExtension(file, ".idx")))) {
226 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
228 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
231 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
235 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
236 if (scanres & UNDEF_CIT || run_bibtex) {
237 // Here we must scan the .aux file and look for
238 // "\bibdata" and/or "\bibstyle". If one of those
239 // tags is found -> run bibtex and set rerun = true;
241 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
243 lfun->dispatch(LFUN_MESSAGE, _("Running BibTeX."));
246 updateBibtexDependencies(head, bibtex_info);
247 rerun |= runBibTeX(bibtex_info);
248 } else if (!had_depfile) {
249 /// If we run pdflatex on the file after running latex on it,
250 /// then we do not need to run bibtex, but we do need to
251 /// insert the .bib and .bst files into the .dep-pdf file.
252 updateBibtexDependencies(head, bibtex_info);
256 // we know on this point that latex has been run once (or we just
257 // returned) and the question now is to decide if we need to run
258 // it any more. This is done by asking if any of the files in the
259 // dependency file has changed. (remember that the checksum for
260 // a given file is reported to have changed if it just was created)
261 // -> if changed or rerun == true:
262 // run latex once more and
263 // update the dependency structure
264 // -> if not changed:
265 // we does nothing at this point
267 if (rerun || head.sumchange()) {
270 lyxerr[Debug::DEPEND]
271 << "Dep. file has changed or rerun requested" << endl;
273 << "Run #" << count << endl;
276 str << _("LaTeX run number") << ' ' << count;
277 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
281 scanres = scanLogFile(terr);
282 if (scanres & ERRORS) {
283 deleteFilesOnError();
284 return scanres; // return on error
287 // update the depedencies
288 deplog(head); // reads the latex log
291 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
295 // The inclusion of files generated by external programs like
296 // makeindex or bibtex might have done changes to pagenumbereing,
297 // etc. And because of this we must run the external programs
298 // again to make sure everything is redone correctly.
299 // Also there should be no need to run the external programs any
302 // run makeindex if the <file>.idx has changed or was generated.
303 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
305 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
307 lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
310 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
314 // we will only run latex more if the log file asks for it.
315 // or if the sumchange() is true.
316 // -> rerun asked for:
318 // remake the dependency file
319 // goto 2 or return if max runs are reached.
320 // -> rerun not asked for:
321 // just return (fall out of bottom of func)
323 while ((head.sumchange() || rerun || (scanres & RERUN))
324 && count < MAX_RUN) {
325 // Yes rerun until message goes away, or until
326 // MAX_RUNS are reached.
329 lyxerr[Debug::LATEX] << "Run #" << count << endl;
332 str << _("LaTeX run number") << ' ' << count;
333 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
337 scanres = scanLogFile(terr);
338 if (scanres & ERRORS) {
339 deleteFilesOnError();
340 return scanres; // return on error
347 // Write the dependencies to file.
349 lyxerr[Debug::LATEX] << "Done." << endl;
354 int LaTeX::operator()()
357 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
358 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
359 string tmp = cmd + ' ' + file + " > nul";
362 return one.startscript(Systemcall::Wait, tmp);
366 bool LaTeX::runMakeIndex(string const & f)
368 lyxerr[Debug::LATEX] << "idx file has been made,"
369 " running makeindex on file "
372 // It should be possible to set the switches for makeindex
373 // sorting style and such. It would also be very convenient
374 // to be able to make style files from within LyX. This has
375 // to come for a later time. (0.13 perhaps?)
376 string tmp = "makeindex -c -q ";
379 one.startscript(Systemcall::Wait, tmp);
384 vector<Aux_Info> const
385 LaTeX::scanAuxFiles(string const & file)
387 vector<Aux_Info> result;
389 result.push_back(scanAuxFile(file));
391 for (int i = 1; i < 1000; ++i) {
392 string file2 = ChangeExtension(file, "") + "." + tostr(i)
397 result.push_back(scanAuxFile(file2));
403 Aux_Info const LaTeX::scanAuxFile(string const & file)
406 result.aux_file = file;
407 scanAuxFile(file, result);
412 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
414 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
416 ifstream ifs(file.c_str());
418 LRegex reg1("\\\\citation\\{([^}]+)\\}");
419 LRegex reg2("\\\\bibdata\\{([^}]+)\\}");
420 LRegex reg3("\\\\bibstyle\\{([^}]+)\\}");
421 LRegex reg4("\\\\@input\\{([^}]+)\\}");
423 while (getline(ifs, token)) {
424 token = strip(token, '\r');
425 if (reg1.exact_match(token)) {
426 LRegex::SubMatches const & sub = reg1.exec(token);
427 string data = LSubstring(token, sub[1].first,
429 while (!data.empty()) {
431 data = split(data, citation, ',');
432 lyxerr[Debug::LATEX] << "Citation: "
434 aux_info.citations.insert(citation);
436 } else if (reg2.exact_match(token)) {
437 LRegex::SubMatches const & sub = reg2.exec(token);
438 string data = LSubstring(token, sub[1].first,
440 // data is now all the bib files separated by ','
441 // get them one by one and pass them to the helper
442 while (!data.empty()) {
444 data = split(data, database, ',');
445 database = ChangeExtension(database, "bib");
446 lyxerr[Debug::LATEX] << "Bibtex database: `"
447 << database << "'" << endl;
448 aux_info.databases.insert(database);
450 } else if (reg3.exact_match(token)) {
451 LRegex::SubMatches const & sub = reg3.exec(token);
452 string style = LSubstring(token, sub[1].first,
454 // token is now the style file
455 // pass it to the helper
456 style = ChangeExtension(style, "bst");
457 lyxerr[Debug::LATEX] << "Bibtex style: `"
458 << style << "'" << endl;
459 aux_info.styles.insert(style);
460 } else if (reg4.exact_match(token)) {
461 LRegex::SubMatches const & sub = reg4.exec(token);
462 string file2 = LSubstring(token, sub[1].first,
464 scanAuxFile(file2, aux_info);
470 void LaTeX::updateBibtexDependencies(DepTable & dep,
471 vector<Aux_Info> const & bibtex_info)
473 // Since a run of Bibtex mandates more latex runs it is ok to
474 // remove all ".bib" and ".bst" files.
475 dep.remove_files_with_extension(".bib");
476 dep.remove_files_with_extension(".bst");
477 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
479 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
480 it != bibtex_info.end(); ++it) {
481 for (set<string>::const_iterator it2 = it->databases.begin();
482 it2 != it->databases.end(); ++it2) {
483 string file = findtexfile(*it2, "bib");
485 dep.insert(file, true);
488 for (set<string>::const_iterator it2 = it->styles.begin();
489 it2 != it->styles.end(); ++it2) {
490 string file = findtexfile(*it2, "bst");
492 dep.insert(file, true);
498 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
501 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
502 it != bibtex_info.end(); ++it) {
503 if (it->databases.empty())
507 string tmp = "bibtex ";
508 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
510 one.startscript(Systemcall::Wait, tmp);
512 // Return whether bibtex was run
517 int LaTeX::scanLogFile(TeXErrors & terr)
521 int retval = NO_ERRORS;
522 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
523 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
524 ifstream ifs(tmp.c_str());
527 while (getline(ifs, token)) {
528 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
533 if (prefixIs(token, "LaTeX Warning:")) {
534 // Here shall we handle different
536 retval |= LATEX_WARNING;
537 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
538 if (contains(token, "Rerun to get cross-references")) {
541 << "We should rerun." << endl;
542 } else if (contains(token, "Citation")
543 && contains(token, "on page")
544 && contains(token, "undefined")) {
547 } else if (prefixIs(token, "Package")) {
549 retval |= PACKAGE_WARNING;
550 if (contains(token, "natbib Warning:")) {
552 if (contains(token, "Citation")
553 && contains(token, "on page")
554 && contains(token, "undefined")) {
557 } else if (contains(token, "run BibTeX")) {
559 } else if (contains(token, "Rerun LaTeX") ||
560 contains(token, "Rerun to get")) {
561 // at least longtable.sty and bibtopic.sty
564 << "We should rerun." << endl;
567 } else if (prefixIs(token, "(")) {
568 if (contains(token, "Rerun LaTeX") ||
569 contains(token, "Rerun to get")) {
572 << "We should rerun." << endl;
575 } else if (prefixIs(token, "! ")) {
576 // Ok, we have something that looks like a TeX Error
577 // but what do we really have.
579 // Just get the error description:
580 string desc(token, 2);
581 if (contains(token, "LaTeX Error:"))
582 retval |= LATEX_ERROR;
587 if (!getline(ifs, tmp))
591 } while (!prefixIs(tmp, "l."));
592 if (prefixIs(tmp, "l.")) {
593 // we have a latex error
595 if (contains(desc, "Package babel Error: You haven't defined the language"))
596 retval |= ERROR_RERUN;
597 // get the line number:
599 sscanf(tmp.c_str(), "l.%d", &line);
600 // get the rest of the message:
601 string errstr(tmp, tmp.find(' '));
604 while (!contains(errstr, "l.")
606 && !prefixIs(tmp, "! ")
607 && !contains(tmp, "(job aborted")) {
613 << "line: " << line << '\n'
614 << "Desc: " << desc << '\n'
615 << "Text: " << errstr << endl;
616 if (line == last_line)
622 if (line_count <= 5) {
623 terr.insertError(line, desc, errstr);
628 // information messages, TeX warnings and other
629 // warnings we have not caught earlier.
630 if (prefixIs(token, "Overfull ")) {
631 retval |= TEX_WARNING;
632 } else if (prefixIs(token, "Underfull ")) {
633 retval |= TEX_WARNING;
634 } else if (contains(token, "Rerun to get citations")) {
635 // Natbib seems to use this.
637 } else if (contains(token, "No pages of output")) {
638 // A dvi file was not created
640 } else if (contains(token, "That makes 100 errors")) {
641 // More than 100 errors were reprted
642 retval |= TOO_MANY_ERRORS;
646 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
651 void LaTeX::deplog(DepTable & head)
653 // This function reads the LaTeX log file end extracts all the external
654 // files used by the LaTeX run. The files are then entered into the
657 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
659 LRegex reg1("\\)* *\\(([^ )]+).*");
660 LRegex reg2("File: ([^ ]+).*");
661 LRegex reg3("No file ([^ ]+)\\..*");
662 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
663 // If an index should be created, MikTex does not write a line like
664 // \openout# = 'sample,idx'.
665 // but intstead only a line like this into the log:
666 // Writing index file sample.idx
667 LRegex reg5("Writing index file ([^ ]+).*");
668 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
670 ifstream ifs(logfile.c_str());
672 // Ok, the scanning of files here is not sufficient.
673 // Sometimes files are named by "File: xxx" only
674 // So I think we should use some regexps to find files instead.
675 // "(\([^ ]+\)" should match the "(file " variant
676 // "File: \([^ ]+\)" should match the "File: file" variant
680 token = strip(token, '\r');
681 if (token.empty()) continue;
683 if (reg1.exact_match(token)) {
684 LRegex::SubMatches const & sub = reg1.exec(token);
685 foundfile = LSubstring(token, sub[1].first,
687 } else if (reg2.exact_match(token)) {
688 LRegex::SubMatches const & sub = reg2.exec(token);
689 foundfile = LSubstring(token, sub[1].first,
691 } else if (reg3.exact_match(token)) {
692 LRegex::SubMatches const & sub = reg3.exec(token);
693 foundfile = LSubstring(token, sub[1].first,
695 } else if (reg4.exact_match(token)) {
696 LRegex::SubMatches const & sub = reg4.exec(token);
697 foundfile = LSubstring(token, sub[1].first,
699 } else if (reg5.exact_match(token)) {
700 LRegex::SubMatches const & sub = reg5.exec(token);
701 foundfile = LSubstring(token, sub[1].first,
707 // convert from native os path to unix path
708 foundfile = os::internal_path(foundfile);
710 lyxerr[Debug::DEPEND] << "Found file: "
711 << foundfile << endl;
713 // Ok now we found a file.
714 // Now we should make sure that this is a file that we can
715 // access through the normal paths.
716 // We will not try any fancy search methods to
719 // (1) foundfile is an
720 // absolute path and should
722 if (AbsolutePath(foundfile)) {
723 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
724 << foundfile << endl;
725 // On initial insert we want to do the update at once
726 // since this file can not be a file generated by
728 if (FileInfo(foundfile).exist())
729 head.insert(foundfile, true);
732 // (2) foundfile is in the tmpdir
733 // insert it into head
734 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
735 if (unwanted.exact_match(foundfile)) {
736 lyxerr[Debug::DEPEND]
738 << OnlyFilename(foundfile)
739 << " in the dep file"
741 } else if (suffixIs(foundfile, ".tex")) {
742 // This is a tex file generated by LyX
743 // and latex is not likely to change this
745 lyxerr[Debug::DEPEND]
746 << "Tmpdir TeX file: "
747 << OnlyFilename(foundfile)
749 head.insert(foundfile, true);
751 lyxerr[Debug::DEPEND]
753 << OnlyFilename(foundfile)
755 head.insert(OnlyFilename(foundfile));
758 lyxerr[Debug::DEPEND]
759 << "Not a file or we are unable to find it."
763 // Make sure that the main .tex file is in the dependancy file.
764 head.insert(OnlyFilename(file), true);