3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
12 * Full author contact details are available in file CREDITS.
18 #include "bufferlist.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"
30 #include <boost/regex.hpp>
34 using lyx::support::AbsolutePath;
35 using lyx::support::bformat;
36 using lyx::support::ChangeExtension;
37 using lyx::support::contains;
38 using lyx::support::FileInfo;
39 using lyx::support::findtexfile;
40 using lyx::support::getcwd;
41 using lyx::support::OnlyFilename;
42 using lyx::support::os;
43 using lyx::support::prefixIs;
44 using lyx::support::QuoteName;
45 using lyx::support::rtrim;
46 using lyx::support::split;
47 using lyx::support::suffixIs;
48 using lyx::support::Systemcall;
49 using lyx::support::unlink;
51 #ifndef CXX_GLOBAL_CSTD
64 #ifndef USE_INCLUDED_STRING
71 // TODO: in no particular order
72 // - get rid of the extern BufferList and the call to
73 // BufferList::updateIncludedTeXfiles, this should either
74 // be done before calling LaTeX::funcs or in a completely
76 // - the bibtex command options should be supported.
77 // - the makeindex style files should be taken care of with
78 // the dependency mechanism.
79 // - makeindex commandline options should be supported
80 // - somewhere support viewing of bibtex and makeindex log files.
81 // - we should perhaps also scan the bibtex log file
82 // - we should perhaps also scan the bibtex log file
84 extern BufferList bufferlist;
88 string runMessage(unsigned int count)
90 return bformat(_("Waiting for LaTeX run number %1$s"), tostr(count));
99 void TeXErrors::insertError(int line, string const & error_desc,
100 string const & error_text)
102 Error newerr(line, error_desc, error_text);
103 errors.push_back(newerr);
107 bool operator==(Aux_Info const & a, Aux_Info const & o)
109 return a.aux_file == o.aux_file &&
110 a.citations == o.citations &&
111 a.databases == o.databases &&
112 a.styles == o.styles;
116 bool operator!=(Aux_Info const & a, Aux_Info const & o)
126 LaTeX::LaTeX(string const & latex, LatexRunParams const & rp,
127 string const & f, string const & p)
128 : cmd(latex), file(f), path(p), runparams(rp)
131 depfile = file + ".dep";
132 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
134 output_file = ChangeExtension(file,".pdf");
136 output_file = ChangeExtension(file,".dvi");
141 void LaTeX::deleteFilesOnError() const
143 // currently just a dummy function.
145 // What files do we have to delete?
147 // This will at least make latex do all the runs
150 // but the reason for the error might be in a generated file...
152 string const ofname = OnlyFilename(file);
155 string const bbl = ChangeExtension(ofname, ".bbl");
159 string const ind = ChangeExtension(ofname, ".ind");
162 // Also remove the aux file
163 string const aux = ChangeExtension(ofname, ".aux");
168 int LaTeX::run(TeXErrors & terr)
169 // We know that this function will only be run if the lyx buffer
170 // has been changed. We also know that a newly written .tex file
171 // is always different from the previous one because of the date
172 // in it. However it seems safe to run latex (at least) on time each
173 // time the .tex file changes.
175 int scanres = NO_ERRORS;
176 unsigned int count = 0; // number of times run
177 num_errors = 0; // just to make sure.
178 unsigned int const MAX_RUN = 6;
179 DepTable head; // empty head
180 bool rerun = false; // rerun requested
182 // The class LaTeX does not know the temp path.
183 bufferlist.updateIncludedTeXfiles(getcwd(), runparams);
185 // Never write the depfile if an error was encountered.
188 // first check if the file dependencies exist:
189 // ->If it does exist
190 // check if any of the files mentioned in it have
191 // changed (done using a checksum).
193 // run latex once and
194 // remake the dependency file
195 // -> if not changed:
196 // just return there is nothing to do for us.
197 // ->if it doesn't exist
199 // run latex once (we need to run latex once anyway) and
200 // remake the dependency file.
203 FileInfo fi(depfile);
204 bool had_depfile = fi.exist();
205 bool run_bibtex = false;
206 string aux_file = OnlyFilename(ChangeExtension(file, "aux"));
209 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
210 // Read the dep file:
211 had_depfile = head.read(depfile);
215 // Update the checksums
217 // Can't just check if anything has changed because it might have aborted
218 // on error last time... in which cas we need to re-run latex
219 // and collect the error messages (even if they are the same).
220 if (!FileInfo(output_file).exist()) {
221 lyxerr[Debug::DEPEND]
222 << "re-running LaTeX because output file doesn't exist." << endl;
223 } else if (!head.sumchange()) {
224 lyxerr[Debug::DEPEND] << "return no_change" << endl;
227 lyxerr[Debug::DEPEND]
228 << "Dependency file has changed" << endl;
231 if (head.extchanged(".bib") || head.extchanged(".bst"))
234 lyxerr[Debug::DEPEND]
235 << "Dependency file does not exist, or has wrong format" << endl;
237 /// We scan the aux file even when had_depfile = false,
238 /// because we can run pdflatex on the file after running latex on it,
239 /// in which case we will not need to run bibtex again.
240 vector<Aux_Info> bibtex_info_old;
242 bibtex_info_old = scanAuxFiles(aux_file);
245 lyxerr[Debug::LATEX] << "Run #" << count << endl;
246 message(runMessage(count));
249 scanres = scanLogFile(terr);
250 if (scanres & ERROR_RERUN) {
251 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
253 scanres = scanLogFile(terr);
256 if (scanres & ERRORS) {
257 deleteFilesOnError();
258 return scanres; // return on error
261 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
262 if (!run_bibtex && bibtex_info_old != bibtex_info)
265 // update the dependencies.
266 deplog(head); // reads the latex log
270 // At this point we must run external programs if needed.
271 // makeindex will be run if a .idx file changed or was generated.
272 // And if there were undefined citations or changes in references
273 // the .aux file is checked for signs of bibtex. Bibtex is then run
277 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
279 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
280 message(_("Running MakeIndex."));
281 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
285 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
286 if (scanres & UNDEF_CIT || run_bibtex) {
287 // Here we must scan the .aux file and look for
288 // "\bibdata" and/or "\bibstyle". If one of those
289 // tags is found -> run bibtex and set rerun = true;
291 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
292 message(_("Running BibTeX."));
293 updateBibtexDependencies(head, bibtex_info);
294 rerun |= runBibTeX(bibtex_info);
295 } else if (!had_depfile) {
296 /// If we run pdflatex on the file after running latex on it,
297 /// then we do not need to run bibtex, but we do need to
298 /// insert the .bib and .bst files into the .dep-pdf file.
299 updateBibtexDependencies(head, bibtex_info);
303 // we know on this point that latex has been run once (or we just
304 // returned) and the question now is to decide if we need to run
305 // it any more. This is done by asking if any of the files in the
306 // dependency file has changed. (remember that the checksum for
307 // a given file is reported to have changed if it just was created)
308 // -> if changed or rerun == true:
309 // run latex once more and
310 // update the dependency structure
311 // -> if not changed:
312 // we does nothing at this point
314 if (rerun || head.sumchange()) {
317 lyxerr[Debug::DEPEND]
318 << "Dep. file has changed or rerun requested" << endl;
320 << "Run #" << count << endl;
321 message(runMessage(count));
323 scanres = scanLogFile(terr);
324 if (scanres & ERRORS) {
325 deleteFilesOnError();
326 return scanres; // return on error
329 // update the depedencies
330 deplog(head); // reads the latex log
333 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
337 // The inclusion of files generated by external programs like
338 // makeindex or bibtex might have done changes to pagenumbereing,
339 // etc. And because of this we must run the external programs
340 // again to make sure everything is redone correctly.
341 // Also there should be no need to run the external programs any
344 // run makeindex if the <file>.idx has changed or was generated.
345 if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
347 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
348 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;
369 message(runMessage(count));
371 scanres = scanLogFile(terr);
372 if (scanres & ERRORS) {
373 deleteFilesOnError();
374 return scanres; // return on error
381 // Write the dependencies to file.
383 lyxerr[Debug::LATEX] << "Done." << endl;
388 int LaTeX::startscript()
391 string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
392 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
393 string tmp = cmd + ' ' + file + " > nul";
396 return one.startscript(Systemcall::Wait, tmp);
400 bool LaTeX::runMakeIndex(string const & f)
402 lyxerr[Debug::LATEX] << "idx file has been made,"
403 " running makeindex on file "
406 // It should be possible to set the switches for makeindex
407 // sorting style and such. It would also be very convenient
408 // to be able to make style files from within LyX. This has
409 // to come for a later time.
410 string tmp = "makeindex -c -q ";
413 one.startscript(Systemcall::Wait, tmp);
418 vector<Aux_Info> const
419 LaTeX::scanAuxFiles(string const & file)
421 vector<Aux_Info> result;
423 result.push_back(scanAuxFile(file));
425 for (int i = 1; i < 1000; ++i) {
426 string file2 = ChangeExtension(file, "") + '.' + tostr(i)
431 result.push_back(scanAuxFile(file2));
437 Aux_Info const LaTeX::scanAuxFile(string const & file)
440 result.aux_file = file;
441 scanAuxFile(file, result);
446 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
448 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
450 ifstream ifs(file.c_str());
452 regex reg1("\\\\citation\\{([^}]+)\\}");
453 regex reg2("\\\\bibdata\\{([^}]+)\\}");
454 regex reg3("\\\\bibstyle\\{([^}]+)\\}");
455 regex reg4("\\\\@input\\{([^}]+)\\}");
457 while (getline(ifs, token)) {
458 token = rtrim(token, "\r");
459 #ifndef USE_INCLUDED_STRING
464 if (regex_match(STRCONV(token), sub, reg1)) {
465 string data = STRCONV(sub.str(1));
466 while (!data.empty()) {
468 data = split(data, citation, ',');
469 lyxerr[Debug::LATEX] << "Citation: "
471 aux_info.citations.insert(citation);
473 } else if (regex_match(STRCONV(token), sub, reg2)) {
474 string data = sub.STRCONV(str(1));
475 // data is now all the bib files separated by ','
476 // get them one by one and pass them to the helper
477 while (!data.empty()) {
479 data = split(data, database, ',');
480 database = ChangeExtension(database, "bib");
481 lyxerr[Debug::LATEX] << "BibTeX database: `"
482 << database << '\'' << endl;
483 aux_info.databases.insert(database);
485 } else if (regex_match(STRCONV(token), sub, reg3)) {
486 string style = STRCONV(sub.str(1));
487 // token is now the style file
488 // pass it to the helper
489 style = ChangeExtension(style, "bst");
490 lyxerr[Debug::LATEX] << "BibTeX style: `"
491 << style << '\'' << endl;
492 aux_info.styles.insert(style);
493 } else if (regex_match(STRCONV(token), sub, reg4)) {
494 string const file2 = STRCONV(sub.str(1));
495 scanAuxFile(file2, aux_info);
501 void LaTeX::updateBibtexDependencies(DepTable & dep,
502 vector<Aux_Info> const & bibtex_info)
504 // Since a run of Bibtex mandates more latex runs it is ok to
505 // remove all ".bib" and ".bst" files.
506 dep.remove_files_with_extension(".bib");
507 dep.remove_files_with_extension(".bst");
508 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
510 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
511 it != bibtex_info.end(); ++it) {
512 for (set<string>::const_iterator it2 = it->databases.begin();
513 it2 != it->databases.end(); ++it2) {
514 string file = findtexfile(*it2, "bib");
516 dep.insert(file, true);
519 for (set<string>::const_iterator it2 = it->styles.begin();
520 it2 != it->styles.end(); ++it2) {
521 string file = findtexfile(*it2, "bst");
523 dep.insert(file, true);
529 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
532 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
533 it != bibtex_info.end(); ++it) {
534 if (it->databases.empty())
538 string tmp = "bibtex ";
539 tmp += OnlyFilename(ChangeExtension(it->aux_file, string()));
541 one.startscript(Systemcall::Wait, tmp);
543 // Return whether bibtex was run
548 int LaTeX::scanLogFile(TeXErrors & terr)
552 int retval = NO_ERRORS;
553 string tmp = OnlyFilename(ChangeExtension(file, ".log"));
554 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
555 ifstream ifs(tmp.c_str());
558 while (getline(ifs, token)) {
559 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
564 if (prefixIs(token, "LaTeX Warning:")) {
565 // Here shall we handle different
567 retval |= LATEX_WARNING;
568 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
569 if (contains(token, "Rerun to get cross-references")) {
572 << "We should rerun." << endl;
573 } else if (contains(token, "Citation")
574 && contains(token, "on page")
575 && contains(token, "undefined")) {
578 } else if (prefixIs(token, "Package")) {
580 retval |= PACKAGE_WARNING;
581 if (contains(token, "natbib Warning:")) {
583 if (contains(token, "Citation")
584 && contains(token, "on page")
585 && contains(token, "undefined")) {
588 } else if (contains(token, "run BibTeX")) {
590 } else if (contains(token, "Rerun LaTeX") ||
591 contains(token, "Rerun to get")) {
592 // at least longtable.sty and bibtopic.sty
595 << "We should rerun." << endl;
598 } else if (token[0] == '(') {
599 if (contains(token, "Rerun LaTeX") ||
600 contains(token, "Rerun to get")) {
603 << "We should rerun." << endl;
606 } else if (prefixIs(token, "! ")) {
607 // Ok, we have something that looks like a TeX Error
608 // but what do we really have.
610 // Just get the error description:
611 string desc(token, 2);
612 if (contains(token, "LaTeX Error:"))
613 retval |= LATEX_ERROR;
618 if (!getline(ifs, tmp))
622 } while (!prefixIs(tmp, "l."));
623 if (prefixIs(tmp, "l.")) {
624 // we have a latex error
626 if (contains(desc, "Package babel Error: You haven't defined the language"))
627 retval |= ERROR_RERUN;
628 // get the line number:
630 sscanf(tmp.c_str(), "l.%d", &line);
631 // get the rest of the message:
632 string errstr(tmp, tmp.find(' '));
635 while (!contains(errstr, "l.")
637 && !prefixIs(tmp, "! ")
638 && !contains(tmp, "(job aborted")) {
644 << "line: " << line << '\n'
645 << "Desc: " << desc << '\n'
646 << "Text: " << errstr << endl;
647 if (line == last_line)
653 if (line_count <= 5) {
654 terr.insertError(line, desc, errstr);
659 // information messages, TeX warnings and other
660 // warnings we have not caught earlier.
661 if (prefixIs(token, "Overfull ")) {
662 retval |= TEX_WARNING;
663 } else if (prefixIs(token, "Underfull ")) {
664 retval |= TEX_WARNING;
665 } else if (contains(token, "Rerun to get citations")) {
666 // Natbib seems to use this.
668 } else if (contains(token, "No pages of output")) {
669 // A dvi file was not created
671 } else if (contains(token, "That makes 100 errors")) {
672 // More than 100 errors were reprted
673 retval |= TOO_MANY_ERRORS;
677 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
682 void LaTeX::deplog(DepTable & head)
684 // This function reads the LaTeX log file end extracts all the external
685 // files used by the LaTeX run. The files are then entered into the
688 string const logfile = OnlyFilename(ChangeExtension(file, ".log"));
690 regex reg1("\\)* *\\(([^ )]+).*");
691 regex reg2("File: ([^ ]+).*");
692 regex reg3("No file ([^ ]+)\\..*");
693 regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
694 // If an index should be created, MikTex does not write a line like
695 // \openout# = 'sample,idx'.
696 // but intstead only a line like this into the log:
697 // Writing index file sample.idx
698 regex reg5("Writing index file ([^ ]+).*");
699 regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
701 ifstream ifs(logfile.c_str());
703 // Ok, the scanning of files here is not sufficient.
704 // Sometimes files are named by "File: xxx" only
705 // So I think we should use some regexps to find files instead.
706 // "(\([^ ]+\)" should match the "(file " variant
707 // "File: \([^ ]+\)" should match the "File: file" variant
711 token = rtrim(token, "\r");
712 if (token.empty()) continue;
714 #ifndef USE_INCLUDED_STRING
719 if (regex_match(STRCONV(token), sub, reg1)) {
720 foundfile = STRCONV(sub.str(1));
721 } else if (regex_match(STRCONV(token), sub, reg2)) {
722 foundfile = STRCONV(sub.str(1));
723 } else if (regex_match(STRCONV(token), sub, reg3)) {
724 foundfile = STRCONV(sub.str(1));
725 } else if (regex_match(STRCONV(token), sub, reg4)) {
726 foundfile = STRCONV(sub.str(1));
727 } else if (regex_match(STRCONV(token), sub, reg5)) {
728 foundfile = STRCONV(sub.str(1));
733 // convert from native os path to unix path
734 foundfile = os::internal_path(foundfile);
736 lyxerr[Debug::DEPEND] << "Found file: "
737 << foundfile << endl;
739 // Ok now we found a file.
740 // Now we should make sure that this is a file that we can
741 // access through the normal paths.
742 // We will not try any fancy search methods to
745 // (1) foundfile is an
746 // absolute path and should
748 if (AbsolutePath(foundfile)) {
749 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
750 << foundfile << endl;
751 // On initial insert we want to do the update at once
752 // since this file can not be a file generated by
754 if (FileInfo(foundfile).exist())
755 head.insert(foundfile, true);
758 // (2) foundfile is in the tmpdir
759 // insert it into head
760 else if (FileInfo(OnlyFilename(foundfile)).exist()) {
761 if (regex_match(STRCONV(foundfile), unwanted)) {
762 lyxerr[Debug::DEPEND]
764 << OnlyFilename(foundfile)
765 << " in the dep file"
767 } else if (suffixIs(foundfile, ".tex")) {
768 // This is a tex file generated by LyX
769 // and latex is not likely to change this
771 lyxerr[Debug::DEPEND]
772 << "Tmpdir TeX file: "
773 << OnlyFilename(foundfile)
775 head.insert(foundfile, true);
777 lyxerr[Debug::DEPEND]
779 << OnlyFilename(foundfile)
781 head.insert(OnlyFilename(foundfile));
784 lyxerr[Debug::DEPEND]
785 << "Not a file or we are unable to find it."
789 // Make sure that the main .tex file is in the dependancy file.
790 head.insert(OnlyFilename(file), true);