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;
51 #ifndef USE_INCLUDED_STRING
57 // TODO: in no particular order
58 // - get rid of the extern BufferList and the call to
59 // BufferList::updateIncludedTeXfiles, this should either
60 // be done before calling LaTeX::funcs or in a completely
62 // - the bibtex command options should be supported.
63 // - the makeindex style files should be taken care of with
64 // the dependency mechanism.
65 // - makeindex commandline options should be supported
66 // - somewhere support viewing of bibtex and makeindex log files.
67 // - we should perhaps also scan the bibtex log file
68 // - we should perhaps also scan the bibtex log file
70 extern BufferList bufferlist;
76 void TeXErrors::insertError(int line, string const & error_desc,
77 string const & error_text)
79 Error newerr(line, error_desc, error_text);
80 errors.push_back(newerr);
87 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
88 : cmd(latex), file(f), path(p)
91 depfile = file + ".dep";
92 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
94 output_file = ChangeExtension(file,".pdf");
96 output_file = ChangeExtension(file,".dvi");
101 void LaTeX::deleteFilesOnError() const
103 // currently just a dummy function.
105 // What files do we have to delete?
107 // This will at least make latex do all the runs
108 lyx::unlink(depfile);
110 // but the reason for the error might be in a generated file...
112 string const ofname = OnlyFilename(file);
115 string const bbl = ChangeExtension(ofname, ".bbl");
119 string const ind = ChangeExtension(ofname, ".ind");
122 // Also remove the aux file
123 string const aux = ChangeExtension(ofname, ".aux");
128 int LaTeX::run(TeXErrors & terr, LyXFunc * lfun)
129 // We know that this function will only be run if the lyx buffer
130 // has been changed. We also know that a newly written .tex file
131 // is always different from the previous one because of the date
132 // in it. However it seems safe to run latex (at least) on time each
133 // time the .tex file changes.
135 int scanres = NO_ERRORS;
136 unsigned int count = 0; // number of times run
137 num_errors = 0; // just to make sure.
138 unsigned int const MAX_RUN = 6;
139 DepTable head; // empty head
140 bool rerun = false; // rerun requested
142 // The class LaTeX does not know the temp path.
143 bufferlist.updateIncludedTeXfiles(lyx::getcwd()); //GetCWD());
145 // Never write the depfile if an error was encountered.
148 // first check if the file dependencies exist:
149 // ->If it does exist
150 // check if any of the files mentioned in it have
151 // changed (done using a checksum).
153 // run latex once and
154 // remake the dependency file
155 // -> if not changed:
156 // just return there is nothing to do for us.
157 // ->if it doesn't exist
159 // run latex once (we need to run latex once anyway) and
160 // remake the dependency file.
163 FileInfo fi(depfile);
164 bool had_depfile = fi.exist();
165 bool run_bibtex = false;
166 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
169 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
170 // Read the dep file:
172 // Update the checksums
174 // Can't just check if anything has changed because it might have aborted
175 // on error last time... in which cas we need to re-run latex
176 // and collect the error messages (even if they are the same).
177 if (!FileInfo(output_file).exist()) {
178 lyxerr[Debug::DEPEND]
179 << "re-running LaTeX because output file doesn't exist." << endl;
180 } else if (!head.sumchange()) {
181 lyxerr[Debug::DEPEND] << "return no_change" << endl;
184 lyxerr[Debug::DEPEND]
185 << "Dependency file has changed" << endl;
188 if (head.extchanged(".bib") || head.extchanged(".bst"))
191 lyxerr[Debug::DEPEND]
192 << "Dependency file does not exist" << endl;
194 /// We scan the aux file even when had_depfile = false,
195 /// because we can run pdflatex on the file after running latex on it,
196 /// in which case we will not need to run bibtex again.
197 vector<Aux_Info> bibtex_info_old;
199 bibtex_info_old = scanAuxFiles(aux_file);
202 lyxerr[Debug::LATEX] << "Run #" << count << endl;
205 str << _("LaTeX run number") << ' ' << count;
206 lfun->dispatch(FuncRequest(LFUN_MESSAGE, STRCONV(str.str())));
210 scanres = scanLogFile(terr);
211 if (scanres & ERROR_RERUN) {
212 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
214 scanres = scanLogFile(terr);
217 if (scanres & ERRORS) {
218 deleteFilesOnError();
219 return scanres; // return on error
222 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
223 if (!run_bibtex && bibtex_info_old != bibtex_info)
226 // update the dependencies.
227 deplog(head); // reads the latex log
231 // At this point we must run external programs if needed.
232 // makeindex will be run if a .idx file changed or was generated.
233 // And if there were undefined citations or changes in references
234 // the .aux file is checked for signs of bibtex. Bibtex is then run
238 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
240 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
242 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
245 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
249 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
250 if (scanres & UNDEF_CIT || run_bibtex) {
251 // Here we must scan the .aux file and look for
252 // "\bibdata" and/or "\bibstyle". If one of those
253 // tags is found -> run bibtex and set rerun = true;
255 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
257 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running BibTeX.")));
260 updateBibtexDependencies(head, bibtex_info);
261 rerun |= runBibTeX(bibtex_info);
262 } else if (!had_depfile) {
263 /// If we run pdflatex on the file after running latex on it,
264 /// then we do not need to run bibtex, but we do need to
265 /// insert the .bib and .bst files into the .dep-pdf file.
266 updateBibtexDependencies(head, bibtex_info);
270 // we know on this point that latex has been run once (or we just
271 // returned) and the question now is to decide if we need to run
272 // it any more. This is done by asking if any of the files in the
273 // dependency file has changed. (remember that the checksum for
274 // a given file is reported to have changed if it just was created)
275 // -> if changed or rerun == true:
276 // run latex once more and
277 // update the dependency structure
278 // -> if not changed:
279 // we does nothing at this point
281 if (rerun || head.sumchange()) {
284 lyxerr[Debug::DEPEND]
285 << "Dep. file has changed or rerun requested" << endl;
287 << "Run #" << count << endl;
290 str << _("LaTeX run number") << ' ' << count;
291 // check lyxstring string stream and gcc 3.1 before fixing
292 lfun->dispatch(FuncRequest(LFUN_MESSAGE, STRCONV(str.str())));
296 scanres = scanLogFile(terr);
297 if (scanres & ERRORS) {
298 deleteFilesOnError();
299 return scanres; // return on error
302 // update the depedencies
303 deplog(head); // reads the latex log
306 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
310 // The inclusion of files generated by external programs like
311 // makeindex or bibtex might have done changes to pagenumbereing,
312 // etc. And because of this we must run the external programs
313 // again to make sure everything is redone correctly.
314 // Also there should be no need to run the external programs any
317 // run makeindex if the <file>.idx has changed or was generated.
318 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
320 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
322 lfun->dispatch(FuncRequest(LFUN_MESSAGE, _("Running MakeIndex.")));
325 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
329 // we will only run latex more if the log file asks for it.
330 // or if the sumchange() is true.
331 // -> rerun asked for:
333 // remake the dependency file
334 // goto 2 or return if max runs are reached.
335 // -> rerun not asked for:
336 // just return (fall out of bottom of func)
338 while ((head.sumchange() || rerun || (scanres & RERUN))
339 && count < MAX_RUN) {
340 // Yes rerun until message goes away, or until
341 // MAX_RUNS are reached.
344 lyxerr[Debug::LATEX] << "Run #" << count << endl;
347 str << _("LaTeX run number") << ' ' << count;
348 lfun->dispatch(FuncRequest(LFUN_MESSAGE, STRCONV(str.str())));
352 scanres = scanLogFile(terr);
353 if (scanres & ERRORS) {
354 deleteFilesOnError();
355 return scanres; // return on error
362 // Write the dependencies to file.
364 lyxerr[Debug::LATEX] << "Done." << endl;
369 int LaTeX::operator()()
372 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
373 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
374 string tmp = cmd + ' ' + file + " > nul";
377 return one.startscript(Systemcall::Wait, tmp);
381 bool LaTeX::runMakeIndex(string const & f)
383 lyxerr[Debug::LATEX] << "idx file has been made,"
384 " running makeindex on file "
387 // It should be possible to set the switches for makeindex
388 // sorting style and such. It would also be very convenient
389 // to be able to make style files from within LyX. This has
390 // to come for a later time.
391 string tmp = "makeindex -c -q ";
394 one.startscript(Systemcall::Wait, tmp);
399 vector<Aux_Info> const
400 LaTeX::scanAuxFiles(string const & file)
402 vector<Aux_Info> result;
404 result.push_back(scanAuxFile(file));
406 for (int i = 1; i < 1000; ++i) {
407 string file2 = ChangeExtension(file, "") + "." + tostr(i)
412 result.push_back(scanAuxFile(file2));
418 Aux_Info const LaTeX::scanAuxFile(string const & file)
421 result.aux_file = file;
422 scanAuxFile(file, result);
427 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
429 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
431 ifstream ifs(file.c_str());
433 regex reg1("\\\\citation\\{([^}]+)\\}");
434 regex reg2("\\\\bibdata\\{([^}]+)\\}");
435 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
436 regex reg4("\\\\@input\\{([^}]+)\\}");
438 while (getline(ifs, token)) {
439 token = rtrim(token, "\r");
440 #ifndef USE_INCLUDED_STRING
445 if (regex_match(STRCONV(token), sub, reg1)) {
446 string data = STRCONV(sub.str(1));
447 while (!data.empty()) {
449 data = split(data, citation, ',');
450 lyxerr[Debug::LATEX] << "Citation: "
452 aux_info.citations.insert(citation);
454 } else if (regex_match(STRCONV(token), sub, reg2)) {
455 string data = sub.STRCONV(str(1));
456 // data is now all the bib files separated by ','
457 // get them one by one and pass them to the helper
458 while (!data.empty()) {
460 data = split(data, database, ',');
461 database = ChangeExtension(database, "bib");
462 lyxerr[Debug::LATEX] << "Bibtex database: `"
463 << database << "'" << endl;
464 aux_info.databases.insert(database);
466 } else if (regex_match(STRCONV(token), sub, reg3)) {
467 string style = STRCONV(sub.str(1));
468 // token is now the style file
469 // pass it to the helper
470 style = ChangeExtension(style, "bst");
471 lyxerr[Debug::LATEX] << "Bibtex style: `"
472 << style << "'" << endl;
473 aux_info.styles.insert(style);
474 } else if (regex_match(STRCONV(token), sub, reg4)) {
475 string const file2 = STRCONV(sub.str(1));
476 scanAuxFile(file2, aux_info);
482 void LaTeX::updateBibtexDependencies(DepTable & dep,
483 vector<Aux_Info> const & bibtex_info)
485 // Since a run of Bibtex mandates more latex runs it is ok to
486 // remove all ".bib" and ".bst" files.
487 dep.remove_files_with_extension(".bib");
488 dep.remove_files_with_extension(".bst");
489 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
491 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
492 it != bibtex_info.end(); ++it) {
493 for (set<string>::const_iterator it2 = it->databases.begin();
494 it2 != it->databases.end(); ++it2) {
495 string file = findtexfile(*it2, "bib");
497 dep.insert(file, true);
500 for (set<string>::const_iterator it2 = it->styles.begin();
501 it2 != it->styles.end(); ++it2) {
502 string file = findtexfile(*it2, "bst");
504 dep.insert(file, true);
510 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
513 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
514 it != bibtex_info.end(); ++it) {
515 if (it->databases.empty())
519 string tmp = "bibtex ";
520 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
522 one.startscript(Systemcall::Wait, tmp);
524 // Return whether bibtex was run
529 int LaTeX::scanLogFile(TeXErrors & terr)
533 int retval = NO_ERRORS;
534 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
535 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
536 ifstream ifs(tmp.c_str());
539 while (getline(ifs, token)) {
540 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
545 if (prefixIs(token, "LaTeX Warning:")) {
546 // Here shall we handle different
548 retval |= LATEX_WARNING;
549 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
550 if (contains(token, "Rerun to get cross-references")) {
553 << "We should rerun." << endl;
554 } else if (contains(token, "Citation")
555 && contains(token, "on page")
556 && contains(token, "undefined")) {
559 } else if (prefixIs(token, "Package")) {
561 retval |= PACKAGE_WARNING;
562 if (contains(token, "natbib Warning:")) {
564 if (contains(token, "Citation")
565 && contains(token, "on page")
566 && contains(token, "undefined")) {
569 } else if (contains(token, "run BibTeX")) {
571 } else if (contains(token, "Rerun LaTeX") ||
572 contains(token, "Rerun to get")) {
573 // at least longtable.sty and bibtopic.sty
576 << "We should rerun." << endl;
579 } else if (prefixIs(token, "(")) {
580 if (contains(token, "Rerun LaTeX") ||
581 contains(token, "Rerun to get")) {
584 << "We should rerun." << endl;
587 } else if (prefixIs(token, "! ")) {
588 // Ok, we have something that looks like a TeX Error
589 // but what do we really have.
591 // Just get the error description:
592 string desc(token, 2);
593 if (contains(token, "LaTeX Error:"))
594 retval |= LATEX_ERROR;
599 if (!getline(ifs, tmp))
603 } while (!prefixIs(tmp, "l."));
604 if (prefixIs(tmp, "l.")) {
605 // we have a latex error
607 if (contains(desc, "Package babel Error: You haven't defined the language"))
608 retval |= ERROR_RERUN;
609 // get the line number:
611 sscanf(tmp.c_str(), "l.%d", &line);
612 // get the rest of the message:
613 string errstr(tmp, tmp.find(' '));
616 while (!contains(errstr, "l.")
618 && !prefixIs(tmp, "! ")
619 && !contains(tmp, "(job aborted")) {
625 << "line: " << line << '\n'
626 << "Desc: " << desc << '\n'
627 << "Text: " << errstr << endl;
628 if (line == last_line)
634 if (line_count <= 5) {
635 terr.insertError(line, desc, errstr);
640 // information messages, TeX warnings and other
641 // warnings we have not caught earlier.
642 if (prefixIs(token, "Overfull ")) {
643 retval |= TEX_WARNING;
644 } else if (prefixIs(token, "Underfull ")) {
645 retval |= TEX_WARNING;
646 } else if (contains(token, "Rerun to get citations")) {
647 // Natbib seems to use this.
649 } else if (contains(token, "No pages of output")) {
650 // A dvi file was not created
652 } else if (contains(token, "That makes 100 errors")) {
653 // More than 100 errors were reprted
654 retval |= TOO_MANY_ERRORS;
658 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
663 void LaTeX::deplog(DepTable & head)
665 // This function reads the LaTeX log file end extracts all the external
666 // files used by the LaTeX run. The files are then entered into the
669 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
671 regex reg1("\\)* *\\(([^ )]+).*");
672 regex reg2("File: ([^ ]+).*");
673 regex reg3("No file ([^ ]+)\\..*");
674 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
675 // If an index should be created, MikTex does not write a line like
676 // \openout# = 'sample,idx'.
677 // but intstead only a line like this into the log:
678 // Writing index file sample.idx
679 regex reg5("Writing index file ([^ ]+).*");
680 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
682 ifstream ifs(logfile.c_str());
684 // Ok, the scanning of files here is not sufficient.
685 // Sometimes files are named by "File: xxx" only
686 // So I think we should use some regexps to find files instead.
687 // "(\([^ ]+\)" should match the "(file " variant
688 // "File: \([^ ]+\)" should match the "File: file" variant
692 token = rtrim(token, "\r");
693 if (token.empty()) continue;
695 #ifndef USE_INCLUDED_STRING
700 if (regex_match(STRCONV(token), sub, reg1)) {
701 foundfile = STRCONV(sub.str(1));
702 } else if (regex_match(STRCONV(token), sub, reg2)) {
703 foundfile = STRCONV(sub.str(1));
704 } else if (regex_match(STRCONV(token), sub, reg3)) {
705 foundfile = STRCONV(sub.str(1));
706 } else if (regex_match(STRCONV(token), sub, reg4)) {
707 foundfile = STRCONV(sub.str(1));
708 } else if (regex_match(STRCONV(token), sub, reg5)) {
709 foundfile = STRCONV(sub.str(1));
714 // convert from native os path to unix path
715 foundfile = os::internal_path(foundfile);
717 lyxerr[Debug::DEPEND] << "Found file: "
718 << foundfile << endl;
720 // Ok now we found a file.
721 // Now we should make sure that this is a file that we can
722 // access through the normal paths.
723 // We will not try any fancy search methods to
726 // (1) foundfile is an
727 // absolute path and should
729 if (AbsolutePath(foundfile)) {
730 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
731 << foundfile << endl;
732 // On initial insert we want to do the update at once
733 // since this file can not be a file generated by
735 if (FileInfo(foundfile).exist())
736 head.insert(foundfile, true);
739 // (2) foundfile is in the tmpdir
740 // insert it into head
741 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
742 if (regex_match(STRCONV(foundfile), unwanted)) {
743 lyxerr[Debug::DEPEND]
745 << OnlyFilename(foundfile)
746 << " in the dep file"
748 } else if (suffixIs(foundfile, ".tex")) {
749 // This is a tex file generated by LyX
750 // and latex is not likely to change this
752 lyxerr[Debug::DEPEND]
753 << "Tmpdir TeX file: "
754 << OnlyFilename(foundfile)
756 head.insert(foundfile, true);
758 lyxerr[Debug::DEPEND]
760 << OnlyFilename(foundfile)
762 head.insert(OnlyFilename(foundfile));
765 lyxerr[Debug::DEPEND]
766 << "Not a file or we are unable to find it."
770 // Make sure that the main .tex file is in the dependancy file.
771 head.insert(OnlyFilename(file), true);