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>
35 #include "BoostFormat.h"
38 #include <cstdio> // sscanf
40 #ifndef CXX_GLOBAL_CSTD
50 using boost::regex_match;
52 #ifndef USE_INCLUDED_STRING
58 // TODO: in no particular order
59 // - get rid of the extern BufferList and the call to
60 // BufferList::updateIncludedTeXfiles, this should either
61 // be done before calling LaTeX::funcs or in a completely
63 // - the bibtex command options should be supported.
64 // - the makeindex style files should be taken care of with
65 // the dependency mechanism.
66 // - makeindex commandline options should be supported
67 // - somewhere support viewing of bibtex and makeindex log files.
68 // - we should perhaps also scan the bibtex log file
69 // - we should perhaps also scan the bibtex log file
71 extern BufferList bufferlist;
75 void showRunMessage(LyXFunc * lf, unsigned int count)
79 str << boost::format(_("Waiting for LaTeX run number %1$d")) % count;
81 str << _("Waiting for LaTeX run number ") << count;
83 lf->dispatch(FuncRequest(LFUN_MESSAGE, STRCONV(str.str())));
92 void TeXErrors::insertError(int line, string const & error_desc,
93 string const & error_text)
95 Error newerr(line, error_desc, error_text);
96 errors.push_back(newerr);
103 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
104 : cmd(latex), file(f), path(p)
107 depfile = file + ".dep";
108 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
110 output_file = ChangeExtension(file,".pdf");
112 output_file = ChangeExtension(file,".dvi");
117 void LaTeX::deleteFilesOnError() const
119 // currently just a dummy function.
121 // What files do we have to delete?
123 // This will at least make latex do all the runs
124 lyx::unlink(depfile);
126 // but the reason for the error might be in a generated file...
128 string const ofname = OnlyFilename(file);
131 string const bbl = ChangeExtension(ofname, ".bbl");
135 string const ind = ChangeExtension(ofname, ".ind");
138 // Also remove the aux file
139 string const aux = ChangeExtension(ofname, ".aux");
144 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
145 // We know that this function will only be run if the lyx buffer
146 // has been changed. We also know that a newly written .tex file
147 // is always different from the previous one because of the date
148 // in it. However it seems safe to run latex (at least) on time each
149 // time the .tex file changes.
151 int scanres = NO_ERRORS;
152 unsigned int count = 0; // number of times run
153 num_errors = 0; // just to make sure.
154 unsigned int const MAX_RUN = 6;
155 DepTable head; // empty head
156 bool rerun = false; // rerun requested
158 // The class LaTeX does not know the temp path.
159 bufferlist.updateIncludedTeXfiles(lyx::getcwd());
161 // Never write the depfile if an error was encountered.
164 // first check if the file dependencies exist:
165 // ->If it does exist
166 // check if any of the files mentioned in it have
167 // changed (done using a checksum).
169 // run latex once and
170 // remake the dependency file
171 // -> if not changed:
172 // just return there is nothing to do for us.
173 // ->if it doesn't exist
175 // run latex once (we need to run latex once anyway) and
176 // remake the dependency file.
179 FileInfo fi(depfile);
180 bool had_depfile = fi.exist();
181 bool run_bibtex = false;
182 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
185 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
186 // Read the dep file:
188 // Update the checksums
190 // Can't just check if anything has changed because it might have aborted
191 // on error last time... in which cas we need to re-run latex
192 // and collect the error messages (even if they are the same).
193 if (!FileInfo(output_file).exist()) {
194 lyxerr[Debug::DEPEND]
195 << "re-running LaTeX because output file doesn't exist." << endl;
196 } else if (!head.sumchange()) {
197 lyxerr[Debug::DEPEND] << "return no_change" << endl;
200 lyxerr[Debug::DEPEND]
201 << "Dependency file has changed" << endl;
204 if (head.extchanged(".bib") || head.extchanged(".bst"))
207 lyxerr[Debug::DEPEND]
208 << "Dependency file does not exist" << endl;
210 /// We scan the aux file even when had_depfile = false,
211 /// because we can run pdflatex on the file after running latex on it,
212 /// in which case we will not need to run bibtex again.
213 vector<Aux_Info> bibtex_info_old;
215 bibtex_info_old = scanAuxFiles(aux_file);
218 lyxerr[Debug::LATEX] << "Run #" << count << endl;
220 showRunMessage(lfun, count);
224 scanres = scanLogFile(terr);
225 if (scanres & ERROR_RERUN) {
226 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
228 scanres = scanLogFile(terr);
231 if (scanres & ERRORS) {
232 deleteFilesOnError();
233 return scanres; // return on error
236 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
237 if (!run_bibtex && bibtex_info_old != bibtex_info)
240 // update the dependencies.
241 deplog(head); // reads the latex log
245 // At this point we must run external programs if needed.
246 // makeindex will be run if a .idx file changed or was generated.
247 // And if there were undefined citations or changes in references
248 // the .aux file is checked for signs of bibtex. Bibtex is then run
252 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
254 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
256 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
259 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
263 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
264 if (scanres & UNDEF_CIT || run_bibtex) {
265 // Here we must scan the .aux file and look for
266 // "\bibdata" and/or "\bibstyle". If one of those
267 // tags is found -> run bibtex and set rerun = true;
269 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
271 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
274 updateBibtexDependencies(head, bibtex_info);
275 rerun |= runBibTeX(bibtex_info);
276 } else if (!had_depfile) {
277 /// If we run pdflatex on the file after running latex on it,
278 /// then we do not need to run bibtex, but we do need to
279 /// insert the .bib and .bst files into the .dep-pdf file.
280 updateBibtexDependencies(head, bibtex_info);
284 // we know on this point that latex has been run once (or we just
285 // returned) and the question now is to decide if we need to run
286 // it any more. This is done by asking if any of the files in the
287 // dependency file has changed. (remember that the checksum for
288 // a given file is reported to have changed if it just was created)
289 // -> if changed or rerun == true:
290 // run latex once more and
291 // update the dependency structure
292 // -> if not changed:
293 // we does nothing at this point
295 if (rerun || head.sumchange()) {
298 lyxerr[Debug::DEPEND]
299 << "Dep. file has changed or rerun requested" << endl;
301 << "Run #" << count << endl;
303 showRunMessage(lfun, count);
307 scanres = scanLogFile(terr);
308 if (scanres & ERRORS) {
309 deleteFilesOnError();
310 return scanres; // return on error
313 // update the depedencies
314 deplog(head); // reads the latex log
317 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
321 // The inclusion of files generated by external programs like
322 // makeindex or bibtex might have done changes to pagenumbereing,
323 // etc. And because of this we must run the external programs
324 // again to make sure everything is redone correctly.
325 // Also there should be no need to run the external programs any
328 // run makeindex if the <file>.idx has changed or was generated.
329 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
331 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
333 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
336 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
340 // we will only run latex more if the log file asks for it.
341 // or if the sumchange() is true.
342 // -> rerun asked for:
344 // remake the dependency file
345 // goto 2 or return if max runs are reached.
346 // -> rerun not asked for:
347 // just return (fall out of bottom of func)
349 while ((head.sumchange() || rerun || (scanres & RERUN))
350 && count < MAX_RUN) {
351 // Yes rerun until message goes away, or until
352 // MAX_RUNS are reached.
355 lyxerr[Debug::LATEX] << "Run #" << count << endl;
357 showRunMessage(lfun, count);
361 scanres = scanLogFile(terr);
362 if (scanres & ERRORS) {
363 deleteFilesOnError();
364 return scanres; // return on error
371 // Write the dependencies to file.
373 lyxerr[Debug::LATEX] << "Done." << endl;
378 int LaTeX::operator()()
381 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
382 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
383 string tmp = cmd + ' ' + file + " > nul";
386 return one.startscript(Systemcall::Wait, tmp);
390 bool LaTeX::runMakeIndex(string const & f)
392 lyxerr[Debug::LATEX] << "idx file has been made,"
393 " running makeindex on file "
396 // It should be possible to set the switches for makeindex
397 // sorting style and such. It would also be very convenient
398 // to be able to make style files from within LyX. This has
399 // to come for a later time.
400 string tmp = "makeindex -c -q ";
403 one.startscript(Systemcall::Wait, tmp);
408 vector<Aux_Info> const
409 LaTeX::scanAuxFiles(string const & file)
411 vector<Aux_Info> result;
413 result.push_back(scanAuxFile(file));
415 for (int i = 1; i < 1000; ++i) {
416 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
421 result.push_back(scanAuxFile(file2));
427 Aux_Info const LaTeX::scanAuxFile(string const & file)
430 result.aux_file = file;
431 scanAuxFile(file, result);
436 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
438 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
440 ifstream ifs(file.c_str());
442 regex reg1("\\\\citation\\{([^}]+)\\}");
443 regex reg2("\\\\bibdata\\{([^}]+)\\}");
444 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
445 regex reg4("\\\\@input\\{([^}]+)\\}");
447 while (getline(ifs, token)) {
448 token = rtrim(token, "\r");
449 #ifndef USE_INCLUDED_STRING
454 if (regex_match(STRCONV(token), sub, reg1)) {
455 string data = STRCONV(sub.str(1));
456 while (!data.empty()) {
458 data = split(data, citation, ',');
459 lyxerr[Debug::LATEX] << "Citation: "
461 aux_info.citations.insert(citation);
463 } else if (regex_match(STRCONV(token), sub, reg2)) {
464 string data = sub.STRCONV(str(1));
465 // data is now all the bib files separated by ','
466 // get them one by one and pass them to the helper
467 while (!data.empty()) {
469 data = split(data, database, ',');
470 database = ChangeExtension(database, "bib");
471 lyxerr[Debug::LATEX] << "BibTeX database: `"
472 << database << '\'' << endl;
473 aux_info.databases.insert(database);
475 } else if (regex_match(STRCONV(token), sub, reg3)) {
476 string style = STRCONV(sub.str(1));
477 // token is now the style file
478 // pass it to the helper
479 style = ChangeExtension(style, "bst");
480 lyxerr[Debug::LATEX] << "BibTeX style: `"
481 << style << '\'' << endl;
482 aux_info.styles.insert(style);
483 } else if (regex_match(STRCONV(token), sub, reg4)) {
484 string const file2 = STRCONV(sub.str(1));
485 scanAuxFile(file2, aux_info);
491 void LaTeX::updateBibtexDependencies(DepTable & dep,
492 vector<Aux_Info> const & bibtex_info)
494 // Since a run of Bibtex mandates more latex runs it is ok to
495 // remove all ".bib" and ".bst" files.
496 dep.remove_files_with_extension(".bib");
497 dep.remove_files_with_extension(".bst");
498 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
500 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
501 it != bibtex_info.end(); ++it) {
502 for (set<string>::const_iterator it2 = it->databases.begin();
503 it2 != it->databases.end(); ++it2) {
504 string file = findtexfile(*it2, "bib");
506 dep.insert(file, true);
509 for (set<string>::const_iterator it2 = it->styles.begin();
510 it2 != it->styles.end(); ++it2) {
511 string file = findtexfile(*it2, "bst");
513 dep.insert(file, true);
519 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
522 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
523 it != bibtex_info.end(); ++it) {
524 if (it->databases.empty())
528 string tmp = "bibtex ";
529 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
531 one.startscript(Systemcall::Wait, tmp);
533 // Return whether bibtex was run
538 int LaTeX::scanLogFile(TeXErrors & terr)
542 int retval = NO_ERRORS;
543 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
544 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
545 ifstream ifs(tmp.c_str());
548 while (getline(ifs, token)) {
549 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
554 if (prefixIs(token, "LaTeX Warning:")) {
555 // Here shall we handle different
557 retval |= LATEX_WARNING;
558 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
559 if (contains(token, "Rerun to get cross-references")) {
562 << "We should rerun." << endl;
563 } else if (contains(token, "Citation")
564 && contains(token, "on page")
565 && contains(token, "undefined")) {
568 } else if (prefixIs(token, "Package")) {
570 retval |= PACKAGE_WARNING;
571 if (contains(token, "natbib Warning:")) {
573 if (contains(token, "Citation")
574 && contains(token, "on page")
575 && contains(token, "undefined")) {
578 } else if (contains(token, "run BibTeX")) {
580 } else if (contains(token, "Rerun LaTeX") ||
581 contains(token, "Rerun to get")) {
582 // at least longtable.sty and bibtopic.sty
585 << "We should rerun." << endl;
588 } else if (token[0] == '(') {
589 if (contains(token, "Rerun LaTeX") ||
590 contains(token, "Rerun to get")) {
593 << "We should rerun." << endl;
596 } else if (prefixIs(token, "! ")) {
597 // Ok, we have something that looks like a TeX Error
598 // but what do we really have.
600 // Just get the error description:
601 string desc(token, 2);
602 if (contains(token, "LaTeX Error:"))
603 retval |= LATEX_ERROR;
608 if (!getline(ifs, tmp))
612 } while (!prefixIs(tmp, "l."));
613 if (prefixIs(tmp, "l.")) {
614 // we have a latex error
616 if (contains(desc, "Package babel Error: You haven't defined the language"))
617 retval |= ERROR_RERUN;
618 // get the line number:
620 sscanf(tmp.c_str(), "l.%d", &line);
621 // get the rest of the message:
622 string errstr(tmp, tmp.find(' '));
625 while (!contains(errstr, "l.")
627 && !prefixIs(tmp, "! ")
628 && !contains(tmp, "(job aborted")) {
634 << "line: " << line << '\n'
635 << "Desc: " << desc << '\n'
636 << "Text: " << errstr << endl;
637 if (line == last_line)
643 if (line_count <= 5) {
644 terr.insertError(line, desc, errstr);
649 // information messages, TeX warnings and other
650 // warnings we have not caught earlier.
651 if (prefixIs(token, "Overfull ")) {
652 retval |= TEX_WARNING;
653 } else if (prefixIs(token, "Underfull ")) {
654 retval |= TEX_WARNING;
655 } else if (contains(token, "Rerun to get citations")) {
656 // Natbib seems to use this.
658 } else if (contains(token, "No pages of output")) {
659 // A dvi file was not created
661 } else if (contains(token, "That makes 100 errors")) {
662 // More than 100 errors were reprted
663 retval |= TOO_MANY_ERRORS;
667 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
672 void LaTeX::deplog(DepTable & head)
674 // This function reads the LaTeX log file end extracts all the external
675 // files used by the LaTeX run. The files are then entered into the
678 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
680 regex reg1("\\)* *\\(([^ )]+).*");
681 regex reg2("File: ([^ ]+).*");
682 regex reg3("No file ([^ ]+)\\..*");
683 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
684 // If an index should be created, MikTex does not write a line like
685 // \openout# = 'sample,idx'.
686 // but intstead only a line like this into the log:
687 // Writing index file sample.idx
688 regex reg5("Writing index file ([^ ]+).*");
689 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
691 ifstream ifs(logfile.c_str());
693 // Ok, the scanning of files here is not sufficient.
694 // Sometimes files are named by "File: xxx" only
695 // So I think we should use some regexps to find files instead.
696 // "(\([^ ]+\)" should match the "(file " variant
697 // "File: \([^ ]+\)" should match the "File: file" variant
701 token = rtrim(token, "\r");
702 if (token.empty()) continue;
704 #ifndef USE_INCLUDED_STRING
709 if (regex_match(STRCONV(token), sub, reg1)) {
710 foundfile = STRCONV(sub.str(1));
711 } else if (regex_match(STRCONV(token), sub, reg2)) {
712 foundfile = STRCONV(sub.str(1));
713 } else if (regex_match(STRCONV(token), sub, reg3)) {
714 foundfile = STRCONV(sub.str(1));
715 } else if (regex_match(STRCONV(token), sub, reg4)) {
716 foundfile = STRCONV(sub.str(1));
717 } else if (regex_match(STRCONV(token), sub, reg5)) {
718 foundfile = STRCONV(sub.str(1));
723 // convert from native os path to unix path
724 foundfile = os::internal_path(foundfile);
726 lyxerr[Debug::DEPEND] << "Found file: "
727 << foundfile << endl;
729 // Ok now we found a file.
730 // Now we should make sure that this is a file that we can
731 // access through the normal paths.
732 // We will not try any fancy search methods to
735 // (1) foundfile is an
736 // absolute path and should
738 if (AbsolutePath(foundfile)) {
739 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
740 << foundfile << endl;
741 // On initial insert we want to do the update at once
742 // since this file can not be a file generated by
744 if (FileInfo(foundfile).exist())
745 head.insert(foundfile, true);
748 // (2) foundfile is in the tmpdir
749 // insert it into head
750 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
751 if (regex_match(STRCONV(foundfile), unwanted)) {
752 lyxerr[Debug::DEPEND]
754 << OnlyFilename(foundfile)
755 << " in the dep file"
757 } else if (suffixIs(foundfile, ".tex")) {
758 // This is a tex file generated by LyX
759 // and latex is not likely to change this
761 lyxerr[Debug::DEPEND]
762 << "Tmpdir TeX file: "
763 << OnlyFilename(foundfile)
765 head.insert(foundfile, true);
767 lyxerr[Debug::DEPEND]
769 << OnlyFilename(foundfile)
771 head.insert(OnlyFilename(foundfile));
774 lyxerr[Debug::DEPEND]
775 << "Not a file or we are unable to find it."
779 // Make sure that the main .tex file is in the dependancy file.
780 head.insert(OnlyFilename(file), true);