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
11 * \author Jürgen Spitzmüller
13 * Full author contact details are available in file CREDITS.
18 #include "BufferList.h"
23 #include "support/debug.h"
24 #include "support/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/gettext.h"
28 #include "support/lstrings.h"
29 #include "support/Systemcall.h"
30 #include "support/os.h"
32 #include <boost/regex.hpp>
40 using namespace lyx::support;
44 namespace os = support::os;
46 // TODO: in no particular order
47 // - get rid of the call to
48 // BufferList::updateIncludedTeXfiles, this should either
49 // be done before calling LaTeX::funcs or in a completely
51 // - the makeindex style files should be taken care of with
52 // the dependency mechanism.
53 // - somewhere support viewing of bibtex and makeindex log files.
54 // - we should perhaps also scan the bibtex log file
58 docstring runMessage(unsigned int count)
60 return bformat(_("Waiting for LaTeX run number %1$d"), count);
69 void TeXErrors::insertError(int line, docstring const & error_desc,
70 docstring const & error_text)
72 Error newerr(line, error_desc, error_text);
73 errors.push_back(newerr);
77 bool operator==(AuxInfo const & a, AuxInfo const & o)
79 return a.aux_file == o.aux_file
80 && a.citations == o.citations
81 && a.databases == o.databases
82 && a.styles == o.styles;
86 bool operator!=(AuxInfo const & a, AuxInfo const & o)
96 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
98 : cmd(latex), file(f), runparams(rp)
101 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
102 depfile = FileName(file.absFilename() + ".dep-pdf");
104 FileName(changeExtension(file.absFilename(), ".pdf"));
106 depfile = FileName(file.absFilename() + ".dep");
108 FileName(changeExtension(file.absFilename(), ".dvi"));
113 void LaTeX::deleteFilesOnError() const
115 // currently just a dummy function.
117 // What files do we have to delete?
119 // This will at least make latex do all the runs
120 depfile.removeFile();
122 // but the reason for the error might be in a generated file...
125 FileName const bbl(changeExtension(file.absFilename(), ".bbl"));
129 FileName const ind(changeExtension(file.absFilename(), ".ind"));
133 FileName const nls(changeExtension(file.absFilename(), ".nls"));
136 // nomencl file (old version of the package)
137 FileName const gls(changeExtension(file.absFilename(), ".gls"));
140 // Also remove the aux file
141 FileName const aux(changeExtension(file.absFilename(), ".aux"));
146 int LaTeX::run(TeXErrors & terr)
147 // We know that this function will only be run if the lyx buffer
148 // has been changed. We also know that a newly written .tex file
149 // is always different from the previous one because of the date
150 // in it. However it seems safe to run latex (at least) on time
151 // each time the .tex file changes.
153 int scanres = NO_ERRORS;
154 unsigned int count = 0; // number of times run
155 num_errors = 0; // just to make sure.
156 unsigned int const MAX_RUN = 6;
157 DepTable head; // empty head
158 bool rerun = false; // rerun requested
160 // The class LaTeX does not know the temp path.
161 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFilename(),
164 // Never write the depfile if an error was encountered.
167 // first check if the file dependencies exist:
168 // ->If it does exist
169 // check if any of the files mentioned in it have
170 // changed (done using a checksum).
172 // run latex once and
173 // remake the dependency file
174 // -> if not changed:
175 // just return there is nothing to do for us.
176 // ->if it doesn't exist
178 // run latex once (we need to run latex once anyway) and
179 // remake the dependency file.
182 bool had_depfile = depfile.exists();
183 bool run_bibtex = false;
184 FileName const aux_file(changeExtension(file.absFilename(), "aux"));
187 LYXERR(Debug::DEPEND, "Dependency file exists");
188 // Read the dep file:
189 had_depfile = head.read(depfile);
193 // Update the checksums
195 // Can't just check if anything has changed because it might
196 // have aborted on error last time... in which cas we need
197 // to re-run latex and collect the error messages
198 // (even if they are the same).
199 if (!output_file.exists()) {
200 LYXERR(Debug::DEPEND,
201 "re-running LaTeX because output file doesn't exist.");
202 } else if (!head.sumchange()) {
203 LYXERR(Debug::DEPEND, "return no_change");
206 LYXERR(Debug::DEPEND, "Dependency file has changed");
209 if (head.extchanged(".bib") || head.extchanged(".bst"))
212 LYXERR(Debug::DEPEND,
213 "Dependency file does not exist, or has wrong format");
215 /// We scan the aux file even when had_depfile = false,
216 /// because we can run pdflatex on the file after running latex on it,
217 /// in which case we will not need to run bibtex again.
218 vector<AuxInfo> bibtex_info_old;
220 bibtex_info_old = scanAuxFiles(aux_file);
223 LYXERR(Debug::LATEX, "Run #" << count);
224 message(runMessage(count));
227 scanres = scanLogFile(terr);
228 if (scanres & ERROR_RERUN) {
229 LYXERR(Debug::LATEX, "Rerunning LaTeX");
231 scanres = scanLogFile(terr);
234 if (scanres & ERRORS) {
235 deleteFilesOnError();
236 return scanres; // return on error
239 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
240 if (!run_bibtex && bibtex_info_old != bibtex_info)
243 // update the dependencies.
244 deplog(head); // reads the latex log
248 // At this point we must run external programs if needed.
249 // makeindex will be run if a .idx file changed or was generated.
250 // And if there were undefined citations or changes in references
251 // the .aux file is checked for signs of bibtex. Bibtex is then run
254 // memoir (at least) writes an empty *idx file in the first place.
255 // A second latex run is needed.
256 FileName const idxfile(changeExtension(file.absFilename(), ".idx"));
257 rerun = idxfile.exists() && idxfile.isFileEmpty();
260 if (head.haschanged(idxfile)) {
262 LYXERR(Debug::LATEX, "Running MakeIndex.");
263 message(_("Running Index Processor."));
264 // onlyFilename() is needed for cygwin
265 rerun |= runMakeIndex(onlyFilename(idxfile.absFilename()),
268 FileName const nlofile(changeExtension(file.absFilename(), ".nlo"));
269 if (head.haschanged(nlofile))
270 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
271 FileName const glofile(changeExtension(file.absFilename(), ".glo"));
272 if (head.haschanged(glofile))
273 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
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.");
283 message(_("Running BibTeX."));
284 updateBibtexDependencies(head, bibtex_info);
285 rerun |= runBibTeX(bibtex_info, runparams);
286 } else if (!had_depfile) {
287 /// If we run pdflatex on the file after running latex on it,
288 /// then we do not need to run bibtex, but we do need to
289 /// insert the .bib and .bst files into the .dep-pdf file.
290 updateBibtexDependencies(head, bibtex_info);
294 // we know on this point that latex has been run once (or we just
295 // returned) and the question now is to decide if we need to run
296 // it any more. This is done by asking if any of the files in the
297 // dependency file has changed. (remember that the checksum for
298 // a given file is reported to have changed if it just was created)
299 // -> if changed or rerun == true:
300 // run latex once more and
301 // update the dependency structure
302 // -> if not changed:
303 // we do nothing at this point
305 if (rerun || head.sumchange()) {
308 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
309 LYXERR(Debug::LATEX, "Run #" << count);
310 message(runMessage(count));
312 scanres = scanLogFile(terr);
313 if (scanres & ERRORS) {
314 deleteFilesOnError();
315 return scanres; // return on error
318 // update the depedencies
319 deplog(head); // reads the latex log
322 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
327 // Complex bibliography packages such as Biblatex require
328 // an additional bibtex cycle sometimes.
329 if (scanres & UNDEF_CIT) {
330 // Here we must scan the .aux file and look for
331 // "\bibdata" and/or "\bibstyle". If one of those
332 // tags is found -> run bibtex and set rerun = true;
334 LYXERR(Debug::LATEX, "Running BibTeX.");
335 message(_("Running BibTeX."));
336 updateBibtexDependencies(head, bibtex_info);
337 rerun |= runBibTeX(bibtex_info, runparams);
341 // The inclusion of files generated by external programs such as
342 // makeindex or bibtex might have done changes to pagenumbering,
343 // etc. And because of this we must run the external programs
344 // again to make sure everything is redone correctly.
345 // Also there should be no need to run the external programs any
348 // run makeindex if the <file>.idx has changed or was generated.
349 if (head.haschanged(idxfile)) {
351 LYXERR(Debug::LATEX, "Running MakeIndex.");
352 message(_("Running Index Processor."));
353 // onlyFilename() is needed for cygwin
354 rerun = runMakeIndex(onlyFilename(changeExtension(
355 file.absFilename(), ".idx")), runparams);
358 // I am not pretty sure if need this twice.
359 if (head.haschanged(nlofile))
360 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
361 if (head.haschanged(glofile))
362 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
365 // we will only run latex more if the log file asks for it.
366 // or if the sumchange() is true.
367 // -> rerun asked for:
369 // remake the dependency file
370 // goto 2 or return if max runs are reached.
371 // -> rerun not asked for:
372 // just return (fall out of bottom of func)
374 while ((head.sumchange() || rerun || (scanres & RERUN))
375 && count < MAX_RUN) {
376 // Yes rerun until message goes away, or until
377 // MAX_RUNS are reached.
380 LYXERR(Debug::LATEX, "Run #" << count);
381 message(runMessage(count));
383 scanres = scanLogFile(terr);
384 if (scanres & ERRORS) {
385 deleteFilesOnError();
386 return scanres; // return on error
393 // Write the dependencies to file.
395 LYXERR(Debug::LATEX, "Done.");
400 int LaTeX::startscript()
402 // onlyFilename() is needed for cygwin
403 string tmp = cmd + ' '
404 + quoteName(onlyFilename(file.toFilesystemEncoding()))
405 + " > " + os::nulldev();
407 return one.startscript(Systemcall::Wait, tmp);
411 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
412 string const & params)
414 string tmp = runparams.use_japanese ?
415 lyxrc.jindex_command : lyxrc.index_command;
417 if (!runparams.index_command.empty())
418 tmp = runparams.index_command;
421 "idx file has been made, running index processor ("
422 << tmp << ") on file " << f);
424 tmp = subst(tmp, "$$lang", runparams.document_language);
425 if (runparams.use_indices) {
426 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
428 "Multiple indices. Using splitindex command: " << tmp);
434 one.startscript(Systemcall::Wait, tmp);
439 bool LaTeX::runMakeIndexNomencl(FileName const & file,
440 string const & nlo, string const & nls)
442 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
443 message(_("Running MakeIndex for nomencl."));
444 string tmp = lyxrc.nomencl_command + ' ';
445 // onlyFilename() is needed for cygwin
446 tmp += quoteName(onlyFilename(changeExtension(file.absFilename(), nlo)));
448 + onlyFilename(changeExtension(file.toFilesystemEncoding(), nls));
450 one.startscript(Systemcall::Wait, tmp);
455 vector<AuxInfo> const
456 LaTeX::scanAuxFiles(FileName const & file)
458 vector<AuxInfo> result;
460 result.push_back(scanAuxFile(file));
462 string const basename = removeExtension(file.absFilename());
463 for (int i = 1; i < 1000; ++i) {
464 FileName const file2(basename
465 + '.' + convert<string>(i)
469 result.push_back(scanAuxFile(file2));
475 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
478 result.aux_file = file;
479 scanAuxFile(file, result);
484 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
486 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
488 ifstream ifs(file.toFilesystemEncoding().c_str());
490 static regex const reg1("\\\\citation\\{([^}]+)\\}");
491 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
492 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
493 static regex const reg4("\\\\@input\\{([^}]+)\\}");
495 while (getline(ifs, token)) {
496 token = rtrim(token, "\r");
498 // FIXME UNICODE: We assume that citation keys and filenames
499 // in the aux file are in the file system encoding.
500 token = to_utf8(from_filesystem8bit(token));
501 if (regex_match(token, sub, reg1)) {
502 string data = sub.str(1);
503 while (!data.empty()) {
505 data = split(data, citation, ',');
506 LYXERR(Debug::LATEX, "Citation: " << citation);
507 aux_info.citations.insert(citation);
509 } else if (regex_match(token, sub, reg2)) {
510 string data = sub.str(1);
511 // data is now all the bib files separated by ','
512 // get them one by one and pass them to the helper
513 while (!data.empty()) {
515 data = split(data, database, ',');
516 database = changeExtension(database, "bib");
517 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
518 aux_info.databases.insert(database);
520 } else if (regex_match(token, sub, reg3)) {
521 string style = sub.str(1);
522 // token is now the style file
523 // pass it to the helper
524 style = changeExtension(style, "bst");
525 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
526 aux_info.styles.insert(style);
527 } else if (regex_match(token, sub, reg4)) {
528 string const file2 = sub.str(1);
529 scanAuxFile(makeAbsPath(file2), aux_info);
535 void LaTeX::updateBibtexDependencies(DepTable & dep,
536 vector<AuxInfo> const & bibtex_info)
538 // Since a run of Bibtex mandates more latex runs it is ok to
539 // remove all ".bib" and ".bst" files.
540 dep.remove_files_with_extension(".bib");
541 dep.remove_files_with_extension(".bst");
542 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
544 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
545 it != bibtex_info.end(); ++it) {
546 for (set<string>::const_iterator it2 = it->databases.begin();
547 it2 != it->databases.end(); ++it2) {
548 FileName const file = findtexfile(*it2, "bib");
550 dep.insert(file, true);
553 for (set<string>::const_iterator it2 = it->styles.begin();
554 it2 != it->styles.end(); ++it2) {
555 FileName const file = findtexfile(*it2, "bst");
557 dep.insert(file, true);
563 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
564 OutputParams const & runparams)
567 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
568 it != bibtex_info.end(); ++it) {
569 if (it->databases.empty())
573 string tmp = runparams.use_japanese ?
574 lyxrc.jbibtex_command : lyxrc.bibtex_command;
576 if (!runparams.bibtex_command.empty())
577 tmp = runparams.bibtex_command;
579 // onlyFilename() is needed for cygwin
580 tmp += quoteName(onlyFilename(removeExtension(
581 it->aux_file.absFilename())));
583 one.startscript(Systemcall::Wait, tmp);
585 // Return whether bibtex was run
590 int LaTeX::scanLogFile(TeXErrors & terr)
594 int retval = NO_ERRORS;
596 onlyFilename(changeExtension(file.absFilename(), ".log"));
597 LYXERR(Debug::LATEX, "Log file: " << tmp);
598 FileName const fn = FileName(makeAbsPath(tmp));
599 ifstream ifs(fn.toFilesystemEncoding().c_str());
600 bool fle_style = false;
601 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
604 while (getline(ifs, token)) {
605 // MikTeX sometimes inserts \0 in the log file. They can't be
606 // removed directly with the existing string utility
607 // functions, so convert them first to \r, and remove all
608 // \r's afterwards, since we need to remove them anyway.
609 token = subst(token, '\0', '\r');
610 token = subst(token, "\r", "");
613 LYXERR(Debug::LATEX, "Log line: " << token);
618 if (contains(token, "file:line:error style messages enabled"))
621 if (prefixIs(token, "LaTeX Warning:") ||
622 prefixIs(token, "! pdfTeX warning")) {
623 // Here shall we handle different
625 retval |= LATEX_WARNING;
626 LYXERR(Debug::LATEX, "LaTeX Warning.");
627 if (contains(token, "Rerun to get cross-references")) {
629 LYXERR(Debug::LATEX, "We should rerun.");
630 // package clefval needs 2 latex runs before bibtex
631 } else if (contains(token, "Value of")
632 && contains(token, "on page")
633 && contains(token, "undefined")) {
634 retval |= ERROR_RERUN;
635 LYXERR(Debug::LATEX, "Force rerun.");
636 } else if (contains(token, "Citation")
637 && contains(token, "on page")
638 && contains(token, "undefined")) {
641 } else if (prefixIs(token, "Package")) {
643 retval |= PACKAGE_WARNING;
644 if (contains(token, "natbib Warning:")) {
646 if (contains(token, "Citation")
647 && contains(token, "on page")
648 && contains(token, "undefined")) {
651 } else if (contains(token, "run BibTeX")) {
653 } else if (contains(token, "Rerun LaTeX") ||
654 contains(token, "Rerun to get")) {
655 // at least longtable.sty and bibtopic.sty
657 LYXERR(Debug::LATEX, "We should rerun.");
660 } else if (prefixIs(token, "LETTRE WARNING:")) {
661 if (contains(token, "veuillez recompiler")) {
663 LYXERR(Debug::LATEX, "We should rerun.");
666 } else if (token[0] == '(') {
667 if (contains(token, "Rerun LaTeX") ||
668 contains(token, "Rerun to get")) {
670 LYXERR(Debug::LATEX, "We should rerun.");
673 } else if (prefixIs(token, "! ")
675 && regex_match(token, sub, file_line_error)
676 && !contains(token, "pdfTeX warning"))) {
677 // Ok, we have something that looks like a TeX Error
678 // but what do we really have.
680 // Just get the error description:
682 if (prefixIs(token, "! "))
683 desc = string(token, 2);
686 if (contains(token, "LaTeX Error:"))
687 retval |= LATEX_ERROR;
692 if (!getline(ifs, tmp))
696 } while (!prefixIs(tmp, "l."));
697 if (prefixIs(tmp, "l.")) {
698 // we have a latex error
701 "Package babel Error: You haven't defined the language") ||
703 "Package babel Error: You haven't loaded the option"))
704 retval |= ERROR_RERUN;
705 // get the line number:
707 sscanf(tmp.c_str(), "l.%d", &line);
708 // get the rest of the message:
709 string errstr(tmp, tmp.find(' '));
712 while (!contains(errstr, "l.")
714 && !prefixIs(tmp, "! ")
715 && !contains(tmp, "(job aborted")) {
720 LYXERR(Debug::LATEX, "line: " << line << '\n'
721 << "Desc: " << desc << '\n' << "Text: " << errstr);
722 if (line == last_line)
728 if (line_count <= 5) {
730 // We have no idea what the encoding of
732 // It seems that the output from the
733 // latex compiler itself is pure ASCII,
734 // but it can include bits from the
735 // document, so whatever encoding we
736 // assume here it can be wrong.
737 terr.insertError(line,
738 from_local8bit(desc),
739 from_local8bit(errstr));
744 // information messages, TeX warnings and other
745 // warnings we have not caught earlier.
746 if (prefixIs(token, "Overfull ")) {
747 retval |= TEX_WARNING;
748 } else if (prefixIs(token, "Underfull ")) {
749 retval |= TEX_WARNING;
750 } else if (contains(token, "Rerun to get citations")) {
751 // Natbib seems to use this.
753 } else if (contains(token, "No pages of output")) {
754 // A dvi file was not created
756 } else if (contains(token, "That makes 100 errors")) {
757 // More than 100 errors were reprted
758 retval |= TOO_MANY_ERRORS;
762 LYXERR(Debug::LATEX, "Log line: " << token);
769 bool insertIfExists(FileName const & absname, DepTable & head)
771 if (absname.exists() && !absname.isDirectory()) {
772 head.insert(absname, true);
779 bool handleFoundFile(string const & ff, DepTable & head)
781 // convert from native os path to unix path
782 string foundfile = os::internal_path(trim(ff));
784 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
786 // Ok now we found a file.
787 // Now we should make sure that this is a file that we can
788 // access through the normal paths.
789 // We will not try any fancy search methods to
792 // (1) foundfile is an
793 // absolute path and should
796 if (FileName::isAbsolute(foundfile)) {
797 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
798 // On initial insert we want to do the update at once
799 // since this file cannot be a file generated by
801 absname.set(foundfile);
802 if (!insertIfExists(absname, head)) {
804 string strippedfile = foundfile;
805 while (contains(strippedfile, " ")) {
806 // files with spaces are often enclosed in quotation
807 // marks; those have to be removed
808 string unquoted = subst(strippedfile, "\"", "");
809 absname.set(unquoted);
810 if (insertIfExists(absname, head))
812 // strip off part after last space and try again
813 string tmp = strippedfile;
814 string const stripoff =
815 rsplit(tmp, strippedfile, ' ');
816 absname.set(strippedfile);
817 if (insertIfExists(absname, head))
823 string onlyfile = onlyFilename(foundfile);
824 absname = makeAbsPath(onlyfile);
827 while (contains(foundfile, ' ')) {
828 if (absname.exists())
832 // files with spaces are often enclosed in quotation
833 // marks; those have to be removed
834 string unquoted = subst(foundfile, "\"", "");
835 absname = makeAbsPath(unquoted);
836 if (absname.exists())
838 // strip off part after last space and try again
840 string const stripoff =
841 rsplit(foundfile, strippedfile, ' ');
842 foundfile = strippedfile;
843 onlyfile = onlyFilename(strippedfile);
844 absname = makeAbsPath(onlyfile);
848 // (2) foundfile is in the tmpdir
849 // insert it into head
850 if (absname.exists() && !absname.isDirectory()) {
851 // FIXME: This regex contained glo, but glo is used by the old
852 // version of nomencl.sty. Do we need to put it back?
853 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
854 if (regex_match(onlyfile, unwanted)) {
855 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
856 << " in the dep file");
857 } else if (suffixIs(onlyfile, ".tex")) {
858 // This is a tex file generated by LyX
859 // and latex is not likely to change this
861 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
862 head.insert(absname, true);
864 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
865 head.insert(absname);
869 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
875 bool checkLineBreak(string const & ff, DepTable & head)
877 if (!contains(ff, '.'))
880 // if we have a dot, we let handleFoundFile decide
881 return handleFoundFile(ff, head);
887 void LaTeX::deplog(DepTable & head)
889 // This function reads the LaTeX log file end extracts all the
890 // external files used by the LaTeX run. The files are then
891 // entered into the dependency file.
893 string const logfile =
894 onlyFilename(changeExtension(file.absFilename(), ".log"));
896 static regex const reg1("File: (.+).*");
897 static regex const reg2("No file (.+)(.).*");
898 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
899 // If an index should be created, MikTex does not write a line like
900 // \openout# = 'sample.idx'.
901 // but instead only a line like this into the log:
902 // Writing index file sample.idx
903 static regex const reg4("Writing index file (.+).*");
904 // files also can be enclosed in <...>
905 static regex const reg5("<([^>]+)(.).*");
906 static regex const regoldnomencl("Writing glossary file (.+).*");
907 static regex const regnomencl("Writing nomenclature file (.+).*");
908 // If a toc should be created, MikTex does not write a line like
909 // \openout# = `sample.toc'.
910 // but only a line like this into the log:
912 // This line is also written by tetex.
913 // This line is not present if no toc should be created.
914 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
915 static regex const reg6(".*\\([^)]+.*");
917 FileName const fn = makeAbsPath(logfile);
918 ifstream ifs(fn.toFilesystemEncoding().c_str());
921 // Ok, the scanning of files here is not sufficient.
922 // Sometimes files are named by "File: xxx" only
923 // So I think we should use some regexps to find files instead.
924 // Note: all file names and paths might contains spaces.
925 bool found_file = false;
928 // MikTeX sometimes inserts \0 in the log file. They can't be
929 // removed directly with the existing string utility
930 // functions, so convert them first to \r, and remove all
931 // \r's afterwards, since we need to remove them anyway.
932 token = subst(token, '\0', '\r');
933 token = subst(token, "\r", "");
934 if (token.empty() || token == ")") {
939 // Sometimes, filenames are broken across lines.
940 // We care for that and save suspicious lines.
941 // Here we exclude some cases where we are sure
942 // that there is no continued filename
943 if (!lastline.empty()) {
944 static regex const package_info("Package \\w+ Info: .*");
945 static regex const package_warning("Package \\w+ Warning: .*");
946 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
947 || prefixIs(token, "Package:")
948 || prefixIs(token, "Language:")
949 || prefixIs(token, "LaTeX Info:")
950 || prefixIs(token, "LaTeX Font Info:")
951 || prefixIs(token, "\\openout[")
952 || prefixIs(token, "))")
953 || regex_match(token, package_info)
954 || regex_match(token, package_warning))
958 if (!lastline.empty())
959 // probably a continued filename from last line
960 token = lastline + token;
961 if (token.length() > 255) {
962 // string too long. Cut off.
963 token.erase(0, token.length() - 251);
968 // FIXME UNICODE: We assume that the file names in the log
969 // file are in the file system encoding.
970 token = to_utf8(from_filesystem8bit(token));
972 // (1) "File: file.ext"
973 if (regex_match(token, sub, reg1)) {
975 found_file = checkLineBreak(sub.str(1), head);
977 if (suffixIs(token, ")"))
978 // no line break for sure
979 // pretend we've been succesfully searching
981 // (2) "No file file.ext"
982 } else if (regex_match(token, sub, reg2)) {
983 // file names must contains a dot, line ends with dot
984 if (contains(sub.str(1), '.') && sub.str(2) == ".")
985 found_file = handleFoundFile(sub.str(1), head);
987 // we suspect a line break
989 // (3) "\openout<nr> = `file.ext'."
990 } else if (regex_match(token, sub, reg3)) {
991 // search for closing '. at the end of the line
992 if (sub.str(2) == "\'.")
993 found_file = handleFoundFile(sub.str(1), head);
995 // probable line break
997 // (4) "Writing index file file.ext"
998 } else if (regex_match(token, sub, reg4))
1000 found_file = checkLineBreak(sub.str(1), head);
1002 else if (regex_match(token, sub, reg5)) {
1003 // search for closing '>' and dot ('*.*>') at the eol
1004 if (contains(sub.str(1), '.') && sub.str(2) == ">")
1005 found_file = handleFoundFile(sub.str(1), head);
1007 // probable line break
1009 // (6) "Writing nomenclature file file.ext"
1010 } else if (regex_match(token, sub, regnomencl) ||
1011 regex_match(token, sub, regoldnomencl))
1013 found_file = checkLineBreak(sub.str(1), head);
1014 // (7) "\tf@toc=\write<nr>" (for MikTeX)
1015 else if (regex_match(token, sub, miktexTocReg))
1016 found_file = handleFoundFile(onlyFilename(changeExtension(
1017 file.absFilename(), ".toc")), head);
1019 // not found, but we won't check further
1020 // pretend we've been succesfully searching
1024 // note that we can have several of these on one line
1025 // this must be queried separated, because of
1026 // cases such as "File: file.ext (type eps)"
1027 // where "File: file.ext" would be skipped
1028 if (regex_match(token, sub, reg6)) {
1029 // search for strings in (...)
1030 static regex reg6_1("\\(([^()]+)(.)");
1032 string::const_iterator first = token.begin();
1033 string::const_iterator end = token.end();
1035 while (regex_search(first, end, what, reg6_1)) {
1036 // if we have a dot, try to handle as file
1037 if (contains(what.str(1), '.')) {
1038 first = what[0].second;
1039 if (what.str(2) == ")") {
1040 handleFoundFile(what.str(1), head);
1041 // since we had a closing bracket,
1042 // do not investigate further
1045 // if we have no closing bracket,
1046 // try to handle as file nevertheless
1047 found_file = handleFoundFile(
1048 what.str(1) + what.str(2), head);
1050 // if we do not have a dot, check if the line has
1051 // a closing bracket (else, we suspect a line break)
1052 else if (what.str(2) != ")") {
1053 first = what[0].second;
1056 // we have a closing bracket, so the content
1057 // is not a file name.
1058 // no need to investigate further
1059 // pretend we've been succesfully searching
1060 first = what[0].second;
1067 // probable linebreak:
1071 // no linebreak: reset
1072 lastline = string();
1075 // Make sure that the main .tex file is in the dependency file.
1076 head.insert(file, true);