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 #include "bufferlist.h"
21 #include "funcrequest.h"
22 #include "support/filetools.h"
23 #include "support/FileInfo.h"
24 #include "support/tostr.h"
25 #include "support/lstrings.h"
26 #include "support/lyxlib.h"
27 #include "support/systemcall.h"
28 #include "support/os.h"
29 #include "support/path.h"
31 #include <boost/regex.hpp>
34 #include <cstdio> // sscanf
36 using namespace lyx::support;
38 #ifndef CXX_GLOBAL_CSTD
48 using boost::regex_match;
50 #ifndef USE_INCLUDED_STRING
56 // TODO: in no particular order
57 // - get rid of the extern BufferList and the call to
58 // BufferList::updateIncludedTeXfiles, this should either
59 // be done before calling LaTeX::funcs or in a completely
61 // - the bibtex command options should be supported.
62 // - the makeindex style files should be taken care of with
63 // the dependency mechanism.
64 // - makeindex commandline options should be supported
65 // - somewhere support viewing of bibtex and makeindex log files.
66 // - we should perhaps also scan the bibtex log file
67 // - we should perhaps also scan the bibtex log file
69 extern BufferList bufferlist;
73 void showRunMessage(LyXFunc * lf, unsigned int count)
75 string str = bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
76 lf->dispatch(FuncRequest(LFUN_MESSAGE, str));
85 void TeXErrors::insertError(int line, string const & error_desc,
86 string const & error_text)
88 Error newerr(line, error_desc, error_text);
89 errors.push_back(newerr);
93 bool operator==(Aux_Info const & a, Aux_Info const & o)
95 return a.aux_file == o.aux_file &&
96 a.citations == o.citations &&
97 a.databases == o.databases &&
102 bool operator!=(Aux_Info const & a, Aux_Info const & o)
112 LaTeX::LaTeX(string const & latex, LatexRunParams const & rp,
113 string const & f, string const & p)
114 : cmd(latex), file(f), path(p), runparams(rp)
117 depfile = file + ".dep";
118 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
120 output_file = ChangeExtension(file,".pdf");
122 output_file = ChangeExtension(file,".dvi");
127 void LaTeX::deleteFilesOnError() const
129 // currently just a dummy function.
131 // What files do we have to delete?
133 // This will at least make latex do all the runs
136 // but the reason for the error might be in a generated file...
138 string const ofname = OnlyFilename(file);
141 string const bbl = ChangeExtension(ofname, ".bbl");
145 string const ind = ChangeExtension(ofname, ".ind");
148 // Also remove the aux file
149 string const aux = ChangeExtension(ofname, ".aux");
154 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
155 // We know that this function will only be run if the lyx buffer
156 // has been changed. We also know that a newly written .tex file
157 // is always different from the previous one because of the date
158 // in it. However it seems safe to run latex (at least) on time each
159 // time the .tex file changes.
161 int scanres = NO_ERRORS;
162 unsigned int count = 0; // number of times run
163 num_errors = 0; // just to make sure.
164 unsigned int const MAX_RUN = 6;
165 DepTable head; // empty head
166 bool rerun = false; // rerun requested
168 // The class LaTeX does not know the temp path.
169 bufferlist.updateIncludedTeXfiles(getcwd(), runparams);
171 // Never write the depfile if an error was encountered.
174 // first check if the file dependencies exist:
175 // ->If it does exist
176 // check if any of the files mentioned in it have
177 // changed (done using a checksum).
179 // run latex once and
180 // remake the dependency file
181 // -> if not changed:
182 // just return there is nothing to do for us.
183 // ->if it doesn't exist
185 // run latex once (we need to run latex once anyway) and
186 // remake the dependency file.
189 FileInfo fi(depfile);
190 bool had_depfile = fi.exist();
191 bool run_bibtex = false;
192 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
195 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
196 // Read the dep file:
197 had_depfile = head.read(depfile);
201 // Update the checksums
203 // Can't just check if anything has changed because it might have aborted
204 // on error last time... in which cas we need to re-run latex
205 // and collect the error messages (even if they are the same).
206 if (!FileInfo(output_file).exist()) {
207 lyxerr[Debug::DEPEND]
208 << "re-running LaTeX because output file doesn't exist." << endl;
209 } else if (!head.sumchange()) {
210 lyxerr[Debug::DEPEND] << "return no_change" << endl;
213 lyxerr[Debug::DEPEND]
214 << "Dependency file has changed" << endl;
217 if (head.extchanged(".bib") || head.extchanged(".bst"))
220 lyxerr[Debug::DEPEND]
221 << "Dependency file does not exist, or has wrong format" << endl;
223 /// We scan the aux file even when had_depfile = false,
224 /// because we can run pdflatex on the file after running latex on it,
225 /// in which case we will not need to run bibtex again.
226 vector<Aux_Info> bibtex_info_old;
228 bibtex_info_old = scanAuxFiles(aux_file);
231 lyxerr[Debug::LATEX] << "Run #" << count << endl;
233 showRunMessage(lfun, count);
237 scanres = scanLogFile(terr);
238 if (scanres & ERROR_RERUN) {
239 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
241 scanres = scanLogFile(terr);
244 if (scanres & ERRORS) {
245 deleteFilesOnError();
246 return scanres; // return on error
249 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
250 if (!run_bibtex && bibtex_info_old != bibtex_info)
253 // update the dependencies.
254 deplog(head); // reads the latex log
258 // At this point we must run external programs if needed.
259 // makeindex will be run if a .idx file changed or was generated.
260 // And if there were undefined citations or changes in references
261 // the .aux file is checked for signs of bibtex. Bibtex is then run
265 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
267 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
269 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
272 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
276 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
277 if (scanres & UNDEF_CIT || run_bibtex) {
278 // Here we must scan the .aux file and look for
279 // "\bibdata" and/or "\bibstyle". If one of those
280 // tags is found -> run bibtex and set rerun = true;
282 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
284 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
287 updateBibtexDependencies(head, bibtex_info);
288 rerun |= runBibTeX(bibtex_info);
289 } else if (!had_depfile) {
290 /// If we run pdflatex on the file after running latex on it,
291 /// then we do not need to run bibtex, but we do need to
292 /// insert the .bib and .bst files into the .dep-pdf file.
293 updateBibtexDependencies(head, bibtex_info);
297 // we know on this point that latex has been run once (or we just
298 // returned) and the question now is to decide if we need to run
299 // it any more. This is done by asking if any of the files in the
300 // dependency file has changed. (remember that the checksum for
301 // a given file is reported to have changed if it just was created)
302 // -> if changed or rerun == true:
303 // run latex once more and
304 // update the dependency structure
305 // -> if not changed:
306 // we does nothing at this point
308 if (rerun || head.sumchange()) {
311 lyxerr[Debug::DEPEND]
312 << "Dep. file has changed or rerun requested" << endl;
314 << "Run #" << count << endl;
316 showRunMessage(lfun, count);
320 scanres = scanLogFile(terr);
321 if (scanres & ERRORS) {
322 deleteFilesOnError();
323 return scanres; // return on error
326 // update the depedencies
327 deplog(head); // reads the latex log
330 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
334 // The inclusion of files generated by external programs like
335 // makeindex or bibtex might have done changes to pagenumbereing,
336 // etc. And because of this we must run the external programs
337 // again to make sure everything is redone correctly.
338 // Also there should be no need to run the external programs any
341 // run makeindex if the <file>.idx has changed or was generated.
342 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
344 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
346 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
349 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
353 // we will only run latex more if the log file asks for it.
354 // or if the sumchange() is true.
355 // -> rerun asked for:
357 // remake the dependency file
358 // goto 2 or return if max runs are reached.
359 // -> rerun not asked for:
360 // just return (fall out of bottom of func)
362 while ((head.sumchange() || rerun || (scanres & RERUN))
363 && count < MAX_RUN) {
364 // Yes rerun until message goes away, or until
365 // MAX_RUNS are reached.
368 lyxerr[Debug::LATEX] << "Run #" << count << endl;
370 showRunMessage(lfun, count);
374 scanres = scanLogFile(terr);
375 if (scanres & ERRORS) {
376 deleteFilesOnError();
377 return scanres; // return on error
384 // Write the dependencies to file.
386 lyxerr[Debug::LATEX] << "Done." << endl;
391 int LaTeX::startscript()
394 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
395 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
396 string tmp = cmd + ' ' + file + " > nul";
399 return one.startscript(Systemcall::Wait, tmp);
403 bool LaTeX::runMakeIndex(string const & f)
405 lyxerr[Debug::LATEX] << "idx file has been made,"
406 " running makeindex on file "
409 // It should be possible to set the switches for makeindex
410 // sorting style and such. It would also be very convenient
411 // to be able to make style files from within LyX. This has
412 // to come for a later time.
413 string tmp = "makeindex -c -q ";
416 one.startscript(Systemcall::Wait, tmp);
421 vector<Aux_Info> const
422 LaTeX::scanAuxFiles(string const & file)
424 vector<Aux_Info> result;
426 result.push_back(scanAuxFile(file));
428 for (int i = 1; i < 1000; ++i) {
429 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
434 result.push_back(scanAuxFile(file2));
440 Aux_Info const LaTeX::scanAuxFile(string const & file)
443 result.aux_file = file;
444 scanAuxFile(file, result);
449 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
451 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
453 ifstream ifs(file.c_str());
455 regex reg1("\\\\citation\\{([^}]+)\\}");
456 regex reg2("\\\\bibdata\\{([^}]+)\\}");
457 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
458 regex reg4("\\\\@input\\{([^}]+)\\}");
460 while (getline(ifs, token)) {
461 token = rtrim(token, "\r");
462 #ifndef USE_INCLUDED_STRING
467 if (regex_match(STRCONV(token), sub, reg1)) {
468 string data = STRCONV(sub.str(1));
469 while (!data.empty()) {
471 data = split(data, citation, ',');
472 lyxerr[Debug::LATEX] << "Citation: "
474 aux_info.citations.insert(citation);
476 } else if (regex_match(STRCONV(token), sub, reg2)) {
477 string data = sub.STRCONV(str(1));
478 // data is now all the bib files separated by ','
479 // get them one by one and pass them to the helper
480 while (!data.empty()) {
482 data = split(data, database, ',');
483 database = ChangeExtension(database, "bib");
484 lyxerr[Debug::LATEX] << "BibTeX database: `"
485 << database << '\'' << endl;
486 aux_info.databases.insert(database);
488 } else if (regex_match(STRCONV(token), sub, reg3)) {
489 string style = STRCONV(sub.str(1));
490 // token is now the style file
491 // pass it to the helper
492 style = ChangeExtension(style, "bst");
493 lyxerr[Debug::LATEX] << "BibTeX style: `"
494 << style << '\'' << endl;
495 aux_info.styles.insert(style);
496 } else if (regex_match(STRCONV(token), sub, reg4)) {
497 string const file2 = STRCONV(sub.str(1));
498 scanAuxFile(file2, aux_info);
504 void LaTeX::updateBibtexDependencies(DepTable & dep,
505 vector<Aux_Info> const & bibtex_info)
507 // Since a run of Bibtex mandates more latex runs it is ok to
508 // remove all ".bib" and ".bst" files.
509 dep.remove_files_with_extension(".bib");
510 dep.remove_files_with_extension(".bst");
511 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
513 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
514 it != bibtex_info.end(); ++it) {
515 for (set<string>::const_iterator it2 = it->databases.begin();
516 it2 != it->databases.end(); ++it2) {
517 string file = findtexfile(*it2, "bib");
519 dep.insert(file, true);
522 for (set<string>::const_iterator it2 = it->styles.begin();
523 it2 != it->styles.end(); ++it2) {
524 string file = findtexfile(*it2, "bst");
526 dep.insert(file, true);
532 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
535 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
536 it != bibtex_info.end(); ++it) {
537 if (it->databases.empty())
541 string tmp = "bibtex ";
542 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
544 one.startscript(Systemcall::Wait, tmp);
546 // Return whether bibtex was run
551 int LaTeX::scanLogFile(TeXErrors & terr)
555 int retval = NO_ERRORS;
556 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
557 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
558 ifstream ifs(tmp.c_str());
561 while (getline(ifs, token)) {
562 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
567 if (prefixIs(token, "LaTeX Warning:")) {
568 // Here shall we handle different
570 retval |= LATEX_WARNING;
571 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
572 if (contains(token, "Rerun to get cross-references")) {
575 << "We should rerun." << endl;
576 } else if (contains(token, "Citation")
577 && contains(token, "on page")
578 && contains(token, "undefined")) {
581 } else if (prefixIs(token, "Package")) {
583 retval |= PACKAGE_WARNING;
584 if (contains(token, "natbib Warning:")) {
586 if (contains(token, "Citation")
587 && contains(token, "on page")
588 && contains(token, "undefined")) {
591 } else if (contains(token, "run BibTeX")) {
593 } else if (contains(token, "Rerun LaTeX") ||
594 contains(token, "Rerun to get")) {
595 // at least longtable.sty and bibtopic.sty
598 << "We should rerun." << endl;
601 } else if (token[0] == '(') {
602 if (contains(token, "Rerun LaTeX") ||
603 contains(token, "Rerun to get")) {
606 << "We should rerun." << endl;
609 } else if (prefixIs(token, "! ")) {
610 // Ok, we have something that looks like a TeX Error
611 // but what do we really have.
613 // Just get the error description:
614 string desc(token, 2);
615 if (contains(token, "LaTeX Error:"))
616 retval |= LATEX_ERROR;
621 if (!getline(ifs, tmp))
625 } while (!prefixIs(tmp, "l."));
626 if (prefixIs(tmp, "l.")) {
627 // we have a latex error
629 if (contains(desc, "Package babel Error: You haven't defined the language"))
630 retval |= ERROR_RERUN;
631 // get the line number:
633 sscanf(tmp.c_str(), "l.%d", &line);
634 // get the rest of the message:
635 string errstr(tmp, tmp.find(' '));
638 while (!contains(errstr, "l.")
640 && !prefixIs(tmp, "! ")
641 && !contains(tmp, "(job aborted")) {
647 << "line: " << line << '\n'
648 << "Desc: " << desc << '\n'
649 << "Text: " << errstr << endl;
650 if (line == last_line)
656 if (line_count <= 5) {
657 terr.insertError(line, desc, errstr);
662 // information messages, TeX warnings and other
663 // warnings we have not caught earlier.
664 if (prefixIs(token, "Overfull ")) {
665 retval |= TEX_WARNING;
666 } else if (prefixIs(token, "Underfull ")) {
667 retval |= TEX_WARNING;
668 } else if (contains(token, "Rerun to get citations")) {
669 // Natbib seems to use this.
671 } else if (contains(token, "No pages of output")) {
672 // A dvi file was not created
674 } else if (contains(token, "That makes 100 errors")) {
675 // More than 100 errors were reprted
676 retval |= TOO_MANY_ERRORS;
680 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
685 void LaTeX::deplog(DepTable & head)
687 // This function reads the LaTeX log file end extracts all the external
688 // files used by the LaTeX run. The files are then entered into the
691 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
693 regex reg1("\\)* *\\(([^ )]+).*");
694 regex reg2("File: ([^ ]+).*");
695 regex reg3("No file ([^ ]+)\\..*");
696 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
697 // If an index should be created, MikTex does not write a line like
698 // \openout# = 'sample,idx'.
699 // but intstead only a line like this into the log:
700 // Writing index file sample.idx
701 regex reg5("Writing index file ([^ ]+).*");
702 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
704 ifstream ifs(logfile.c_str());
706 // Ok, the scanning of files here is not sufficient.
707 // Sometimes files are named by "File: xxx" only
708 // So I think we should use some regexps to find files instead.
709 // "(\([^ ]+\)" should match the "(file " variant
710 // "File: \([^ ]+\)" should match the "File: file" variant
714 token = rtrim(token, "\r");
715 if (token.empty()) continue;
717 #ifndef USE_INCLUDED_STRING
722 if (regex_match(STRCONV(token), sub, reg1)) {
723 foundfile = STRCONV(sub.str(1));
724 } else if (regex_match(STRCONV(token), sub, reg2)) {
725 foundfile = STRCONV(sub.str(1));
726 } else if (regex_match(STRCONV(token), sub, reg3)) {
727 foundfile = STRCONV(sub.str(1));
728 } else if (regex_match(STRCONV(token), sub, reg4)) {
729 foundfile = STRCONV(sub.str(1));
730 } else if (regex_match(STRCONV(token), sub, reg5)) {
731 foundfile = STRCONV(sub.str(1));
736 // convert from native os path to unix path
737 foundfile = os::internal_path(foundfile);
739 lyxerr[Debug::DEPEND] << "Found file: "
740 << foundfile << endl;
742 // Ok now we found a file.
743 // Now we should make sure that this is a file that we can
744 // access through the normal paths.
745 // We will not try any fancy search methods to
748 // (1) foundfile is an
749 // absolute path and should
751 if (AbsolutePath(foundfile)) {
752 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
753 << foundfile << endl;
754 // On initial insert we want to do the update at once
755 // since this file can not be a file generated by
757 if (FileInfo(foundfile).exist())
758 head.insert(foundfile, true);
761 // (2) foundfile is in the tmpdir
762 // insert it into head
763 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
764 if (regex_match(STRCONV(foundfile), unwanted)) {
765 lyxerr[Debug::DEPEND]
767 << OnlyFilename(foundfile)
768 << " in the dep file"
770 } else if (suffixIs(foundfile, ".tex")) {
771 // This is a tex file generated by LyX
772 // and latex is not likely to change this
774 lyxerr[Debug::DEPEND]
775 << "Tmpdir TeX file: "
776 << OnlyFilename(foundfile)
778 head.insert(foundfile, true);
780 lyxerr[Debug::DEPEND]
782 << OnlyFilename(foundfile)
784 head.insert(OnlyFilename(foundfile));
787 lyxerr[Debug::DEPEND]
788 << "Not a file or we are unable to find it."
792 // Make sure that the main .tex file is in the dependancy file.
793 head.insert(OnlyFilename(file), true);