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 "support/filetools.h"
23 #include "support/FileInfo.h"
25 #include "support/lyxlib.h"
26 #include "support/syscall.h"
27 #include "support/syscontr.h"
28 #include "support/path.h"
29 #include "support/LRegex.h"
30 #include "support/LSubstring.h"
31 #include "support/lstrings.h"
32 #include "bufferlist.h"
34 #include "lyx_gui_misc.h"
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 ?
83 void LaTeX::deleteFilesOnError() const
85 // currently just a dummy function.
87 // What files do we have to delete?
89 // This will at least make latex do all the runs
92 // but the reason for the error might be in a generated file...
94 string ofname = OnlyFilename(file);
97 string bbl = ChangeExtension(ofname, ".bbl");
101 string ind = ChangeExtension(ofname, ".ind");
104 // Also remove the aux file
105 string aux = ChangeExtension(ofname, ".aux");
110 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
111 // We know that this function will only be run if the lyx buffer
112 // has been changed. We also know that a newly written .tex file
113 // is always different from the previous one because of the date
114 // in it. However it seems safe to run latex (at least) on time each
115 // time the .tex file changes.
117 int scanres = NO_ERRORS;
118 unsigned int count = 0; // number of times run
119 num_errors = 0; // just to make sure.
120 const unsigned int MAX_RUN = 6;
121 DepTable head; // empty head
122 bool rerun = false; // rerun requested
124 // The class LaTeX does not know the temp path.
125 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
127 // Never write the depfile if an error was encountered.
130 // first check if the file dependencies exist:
131 // ->If it does exist
132 // check if any of the files mentioned in it have
133 // changed (done using a checksum).
135 // run latex once and
136 // remake the dependency file
137 // -> if not changed:
138 // just return there is nothing to do for us.
139 // ->if it doesn't exist
141 // run latex once (we need to run latex once anyway) and
142 // remake the dependency file.
145 FileInfo fi(depfile);
146 bool had_depfile = fi.exist();
147 bool run_bibtex = false;
148 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
151 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
152 // Read the dep file:
154 // Update the checksums
156 if (!head.sumchange()) {
157 lyxerr[Debug::DEPEND] << "return no_change" << endl;
160 lyxerr[Debug::DEPEND]
161 << "Dependency file has changed" << endl;
163 if (head.extchanged(".bib") || head.extchanged(".bst"))
166 lyxerr[Debug::DEPEND]
167 << "Dependency file does not exist" << endl;
169 /// We scan the aux file even when had_depfile = false,
170 /// because we can run pdflatex on the file after running latex on it,
171 /// in which case we will not need to run bibtex again.
172 vector<Aux_Info> bibtex_info_old;
174 bibtex_info_old = scanAuxFiles(aux_file);
177 lyxerr[Debug::LATEX] << "Run #" << count << endl;
180 str << _("LaTeX run number") << ' ' << count;
181 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
185 scanres = scanLogFile(terr);
186 if (scanres & ERROR_RERUN) {
187 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
189 scanres = scanLogFile(terr);
192 if (scanres & ERRORS) {
193 deleteFilesOnError();
194 return scanres; // return on error
197 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
198 if (!run_bibtex && bibtex_info_old != bibtex_info)
201 // update the dependencies.
202 deplog(head); // reads the latex log
206 // At this point we must run external programs if needed.
207 // makeindex will be run if a .idx file changed or was generated.
208 // And if there were undefined citations or changes in references
209 // the .aux file is checked for signs of bibtex. Bibtex is then run
213 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
215 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
216 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
217 // WriteStatus(minib, _("Running MakeIndex."));
218 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
222 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
223 if (scanres & UNDEF_CIT || run_bibtex) {
224 // Here we must scan the .aux file and look for
225 // "\bibdata" and/or "\bibstyle". If one of those
226 // tags is found -> run bibtex and set rerun = true;
228 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
229 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running BibTeX."));
230 //WriteStatus(minib, _("Running BibTeX."));
231 updateBibtexDependencies(head, bibtex_info);
232 rerun |= runBibTeX(bibtex_info);
233 } else if (!had_depfile)
234 /// If we run pdflatex on the file after running latex on it,
235 /// then we do not need to run bibtex, but we do need to
236 /// insert the .bib and .bst files into the .dep-pdf file.
237 updateBibtexDependencies(head, bibtex_info);
240 // we know on this point that latex has been run once (or we just
241 // returned) and the question now is to decide if we need to run
242 // it any more. This is done by asking if any of the files in the
243 // dependency file has changed. (remember that the checksum for
244 // a given file is reported to have changed if it just was created)
245 // -> if changed or rerun == true:
246 // run latex once more and
247 // update the dependency structure
248 // -> if not changed:
249 // we does nothing at this point
251 if (rerun || head.sumchange()) {
254 lyxerr[Debug::DEPEND]
255 << "Dep. file has changed or rerun requested" << endl;
257 << "Run #" << count << endl;
260 str << _("LaTeX run number") << ' ' << count;
261 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
264 // WriteStatus(minib,
265 // string(_("LaTeX run number ")) + tostr(count));
267 scanres = scanLogFile(terr);
268 if (scanres & ERRORS) {
269 deleteFilesOnError();
270 return scanres; // return on error
273 // update the depedencies
274 deplog(head); // reads the latex log
277 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
281 // The inclusion of files generated by external programs like
282 // makeindex or bibtex might have done changes to pagenumbereing,
283 // etc. And because of this we must run the external programs
284 // again to make sure everything is redone correctly.
285 // Also there should be no need to run the external programs any
288 // run makeindex if the <file>.idx has changed or was generated.
289 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
291 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
292 if (lfun) lfun->dispatch(LFUN_MESSAGE, _("Running MakeIndex."));
293 //WriteStatus(minib, _("Running MakeIndex."));
294 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
298 // we will only run latex more if the log file asks for it.
299 // or if the sumchange() is true.
300 // -> rerun asked for:
302 // remake the dependency file
303 // goto 2 or return if max runs are reached.
304 // -> rerun not asked for:
305 // just return (fall out of bottom of func)
307 while ((head.sumchange() || rerun || (scanres & RERUN))
308 && count < MAX_RUN) {
309 // Yes rerun until message goes away, or until
310 // MAX_RUNS are reached.
313 lyxerr[Debug::LATEX] << "Run #" << count << endl;
316 str << _("LaTeX run number") << ' ' << count;
317 lfun->dispatch(LFUN_MESSAGE, str.str().c_str());
321 scanres = scanLogFile(terr);
322 if (scanres & ERRORS) {
323 deleteFilesOnError();
324 return scanres; // return on error
331 // Write the dependencies to file.
333 lyxerr[Debug::LATEX] << "Done." << endl;
338 int LaTeX::operator()()
341 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
342 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
343 string tmp = cmd + ' ' + file + " > nul";
346 return one.startscript(Systemcalls::System, tmp);
350 bool LaTeX::runMakeIndex(string const & f)
352 lyxerr[Debug::LATEX] << "idx file has been made,"
353 " running makeindex on file "
356 // It should be possible to set the switches for makeindex
357 // sorting style and such. It would also be very convenient
358 // to be able to make style files from within LyX. This has
359 // to come for a later time. (0.13 perhaps?)
360 string tmp = "makeindex -c -q ";
363 one.startscript(Systemcalls::System, tmp);
368 vector<Aux_Info> const
369 LaTeX::scanAuxFiles(string const & file)
371 vector<Aux_Info> result;
373 result.push_back(scanAuxFile(file));
375 for (int i = 1; i < 1000; ++i) {
376 string file2 = ChangeExtension(file, "") + "." + tostr(i)
381 result.push_back(scanAuxFile(file2));
387 Aux_Info const LaTeX::scanAuxFile(string const & file)
390 result.aux_file = file;
391 scanAuxFile(file, result);
396 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
398 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
400 ifstream ifs(file.c_str());
402 LRegex reg1("\\\\citation\\{([^}]+)\\}");
403 LRegex reg2("\\\\bibdata\\{([^}]+)\\}");
404 LRegex reg3("\\\\bibstyle\\{([^}]+)\\}");
405 LRegex reg4("\\\\@input\\{([^}]+)\\}");
407 while (getline(ifs, token)) {
408 token = strip(token, '\r');
409 if (reg1.exact_match(token)) {
410 LRegex::SubMatches const & sub = reg1.exec(token);
411 string data = LSubstring(token, sub[1].first,
413 while (!data.empty()) {
415 data = split(data, citation, ',');
416 lyxerr[Debug::LATEX] << "Citation: "
418 aux_info.citations.insert(citation);
420 } else if (reg2.exact_match(token)) {
421 LRegex::SubMatches const & sub = reg2.exec(token);
422 string data = LSubstring(token, sub[1].first,
424 // data is now all the bib files separated by ','
425 // get them one by one and pass them to the helper
426 while (!data.empty()) {
428 data = split(data, database, ',');
429 database = ChangeExtension(database, "bib");
430 lyxerr[Debug::LATEX] << "Bibtex database: `"
431 << database << "'" << endl;
432 aux_info.databases.insert(database);
434 } else if (reg3.exact_match(token)) {
435 LRegex::SubMatches const & sub = reg3.exec(token);
436 string style = LSubstring(token, sub[1].first,
438 // token is now the style file
439 // pass it to the helper
440 style = ChangeExtension(style, "bst");
441 lyxerr[Debug::LATEX] << "Bibtex style: `"
442 << style << "'" << endl;
443 aux_info.styles.insert(style);
444 } else if (reg4.exact_match(token)) {
445 LRegex::SubMatches const & sub = reg4.exec(token);
446 string file2 = LSubstring(token, sub[1].first,
448 scanAuxFile(file2, aux_info);
454 void LaTeX::updateBibtexDependencies(DepTable & dep,
455 vector<Aux_Info> const & bibtex_info)
457 // Since a run of Bibtex mandates more latex runs it is ok to
458 // remove all ".bib" and ".bst" files.
459 dep.remove_files_with_extension(".bib");
460 dep.remove_files_with_extension(".bst");
461 string aux = OnlyFilename(ChangeExtension(file, ".aux"));
463 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
464 it != bibtex_info.end(); ++it) {
465 for (set<string>::const_iterator it2 = it->databases.begin();
466 it2 != it->databases.end(); ++it2) {
467 string file = findtexfile(*it2, "bib");
469 dep.insert(file, true);
472 for (set<string>::const_iterator it2 = it->styles.begin();
473 it2 != it->styles.end(); ++it2) {
474 string file = findtexfile(*it2, "bst");
476 dep.insert(file, true);
482 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
485 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
486 it != bibtex_info.end(); ++it) {
487 if (it->databases.empty())
491 string tmp = "bibtex ";
492 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
494 one.startscript(Systemcalls::System, tmp);
496 // Return whether bibtex was run
501 int LaTeX::scanLogFile(TeXErrors & terr)
505 int retval = NO_ERRORS;
506 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
507 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
508 ifstream ifs(tmp.c_str());
511 while (getline(ifs, token)) {
512 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
517 if (prefixIs(token, "LaTeX Warning:")) {
518 // Here shall we handle different
520 retval |= LATEX_WARNING;
521 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
522 if (contains(token, "Rerun to get cross-references")) {
525 << "We should rerun." << endl;
526 } else if (contains(token, "Citation")
527 && contains(token, "on page")
528 && contains(token, "undefined")) {
531 } else if (prefixIs(token, "Package")) {
533 retval |= PACKAGE_WARNING;
534 if (contains(token, "natbib Warning:")) {
536 if (contains(token, "Citation")
537 && contains(token, "on page")
538 && contains(token, "undefined")) {
541 } else if (contains(token, "run BibTeX")) {
543 } else if (contains(token, "Rerun LaTeX") ||
544 contains(token, "Rerun to get")) {
545 // at least longtable.sty and bibtopic.sty
548 << "We should rerun." << endl;
551 } else if (prefixIs(token, "(")) {
552 if (contains(token, "Rerun LaTeX") ||
553 contains(token, "Rerun to get")) {
556 << "We should rerun." << endl;
559 } else if (prefixIs(token, "! ")) {
560 // Ok, we have something that looks like a TeX Error
561 // but what do we really have.
563 // Just get the error description:
564 string desc(token, 2);
565 if (contains(token, "LaTeX Error:"))
566 retval |= LATEX_ERROR;
571 if (!getline(ifs, tmp))
575 } while (!prefixIs(tmp, "l."));
576 if (prefixIs(tmp, "l.")) {
577 // we have a latex error
579 if (contains(desc, "Package babel Error: You haven't defined the language"))
580 retval |= ERROR_RERUN;
581 // get the line number:
583 sscanf(tmp.c_str(), "l.%d", &line);
584 // get the rest of the message:
585 string errstr(tmp, tmp.find(' '));
588 while (!contains(errstr, "l.")
590 && !prefixIs(tmp, "! ")
591 && !contains(tmp, "(job aborted")) {
597 << "line: " << line << '\n'
598 << "Desc: " << desc << '\n'
599 << "Text: " << errstr << endl;
600 if (line == last_line)
606 if (line_count <= 5) {
607 terr.insertError(line, desc, errstr);
612 // information messages, TeX warnings and other
613 // warnings we have not caught earlier.
614 if (prefixIs(token, "Overfull ")) {
615 retval |= TEX_WARNING;
616 } else if (prefixIs(token, "Underfull ")) {
617 retval |= TEX_WARNING;
618 } else if (contains(token, "Rerun to get citations")) {
619 // Natbib seems to use this.
621 } else if (contains(token, "No pages of output")) {
622 // A dvi file was not created
624 } else if (contains(token, "That makes 100 errors")) {
625 // More than 100 errors were reprted
626 retval |= TOO_MANY_ERRORS;
630 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
635 void LaTeX::deplog(DepTable & head)
637 // This function reads the LaTeX log file end extracts all the external
638 // files used by the LaTeX run. The files are then entered into the
641 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
643 LRegex reg1("\\)* *\\(([^ )]+).*");
644 LRegex reg2("File: ([^ ]+).*");
645 LRegex reg3("No file ([^ ]+)\\..*");
646 LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
647 LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
649 ifstream ifs(logfile.c_str());
651 // Ok, the scanning of files here is not sufficient.
652 // Sometimes files are named by "File: xxx" only
653 // So I think we should use some regexps to find files instead.
654 // "(\([^ ]+\)" should match the "(file " variant
655 // "File: \([^ ]+\)" should match the "File: file" variant
659 token = strip(token, '\r');
660 if (token.empty()) continue;
662 if (reg1.exact_match(token)) {
663 LRegex::SubMatches const & sub = reg1.exec(token);
664 foundfile = LSubstring(token, sub[1].first,
666 } else if (reg2.exact_match(token)) {
667 LRegex::SubMatches const & sub = reg2.exec(token);
668 foundfile = LSubstring(token, sub[1].first,
670 } else if (reg3.exact_match(token)) {
671 LRegex::SubMatches const & sub = reg3.exec(token);
672 foundfile = LSubstring(token, sub[1].first,
674 } else if (reg4.exact_match(token)) {
675 LRegex::SubMatches const & sub = reg4.exec(token);
676 foundfile = LSubstring(token, sub[1].first,
682 lyxerr[Debug::DEPEND] << "Found file: "
683 << foundfile << endl;
685 // Ok now we found a file.
686 // Now we should make sure that this is a file that we can
687 // access through the normal paths.
688 // We will not try any fancy search methods to
691 // (1) foundfile is an
692 // absolute path and should
694 if (AbsolutePath(foundfile)) {
695 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
696 << foundfile << endl;
697 // On initial insert we want to do the update at once
698 // since this file can not be a file generated by
700 if (FileInfo(foundfile).exist())
701 head.insert(foundfile, true);
704 // (2) foundfile is in the tmpdir
705 // insert it into head
706 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
707 if (unwanted.exact_match(foundfile)) {
708 lyxerr[Debug::DEPEND]
710 << OnlyFilename(foundfile)
711 << " in the dep file"
713 } else if (suffixIs(foundfile, ".tex")) {
714 // This is a tex file generated by LyX
715 // and latex is not likely to change this
717 lyxerr[Debug::DEPEND]
718 << "Tmpdir TeX file: "
719 << OnlyFilename(foundfile)
721 head.insert(foundfile, true);
723 lyxerr[Debug::DEPEND]
725 << OnlyFilename(foundfile)
727 head.insert(OnlyFilename(foundfile));
730 lyxerr[Debug::DEPEND]
731 << "Not a file or we are unable to find it."
735 // Make sure that the main .tex file is in the dependancy file.
736 head.insert(OnlyFilename(file), true);