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"
25 #include "support/filetools.h"
26 #include "support/convert.h"
27 #include "support/lstrings.h"
28 #include "support/lyxlib.h"
29 #include "support/Systemcall.h"
30 #include "support/os.h"
32 #include <boost/filesystem/operations.hpp>
33 #include <boost/filesystem/path.hpp>
34 #include <boost/regex.hpp>
41 #ifndef CXX_GLOBAL_CSTD
55 using support::absolutePath;
56 using support::bformat;
57 using support::changeExtension;
58 using support::contains;
59 using support::FileName;
60 using support::findtexfile;
61 using support::getcwd;
62 using support::makeAbsPath;
63 using support::onlyFilename;
64 using support::prefixIs;
65 using support::quoteName;
66 using support::removeExtension;
68 using support::rsplit;
71 using support::suffixIs;
72 using support::Systemcall;
73 using support::unlink;
76 namespace os = support::os;
77 namespace fs = boost::filesystem;
79 // TODO: in no particular order
80 // - get rid of the call to
81 // BufferList::updateIncludedTeXfiles, this should either
82 // be done before calling LaTeX::funcs or in a completely
84 // - the makeindex style files should be taken care of with
85 // the dependency mechanism.
86 // - makeindex commandline options should be supported
87 // - somewhere support viewing of bibtex and makeindex log files.
88 // - we should perhaps also scan the bibtex log file
92 docstring runMessage(unsigned int count)
94 return bformat(_("Waiting for LaTeX run number %1$d"), count);
103 void TeXErrors::insertError(int line, docstring const & error_desc,
104 docstring const & error_text)
106 Error newerr(line, error_desc, error_text);
107 errors.push_back(newerr);
111 bool operator==(Aux_Info const & a, Aux_Info const & o)
113 return a.aux_file == o.aux_file &&
114 a.citations == o.citations &&
115 a.databases == o.databases &&
116 a.styles == o.styles;
120 bool operator!=(Aux_Info const & a, Aux_Info const & o)
130 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
132 : cmd(latex), file(f), runparams(rp)
135 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
136 depfile = FileName(file.absFilename() + ".dep-pdf");
138 FileName(changeExtension(file.absFilename(), ".pdf"));
140 depfile = FileName(file.absFilename() + ".dep");
142 FileName(changeExtension(file.absFilename(), ".dvi"));
147 void LaTeX::deleteFilesOnError() const
149 // currently just a dummy function.
151 // What files do we have to delete?
153 // This will at least make latex do all the runs
156 // but the reason for the error might be in a generated file...
159 FileName const bbl(changeExtension(file.absFilename(), ".bbl"));
163 FileName const ind(changeExtension(file.absFilename(), ".ind"));
167 FileName const nls(changeExtension(file.absFilename(), ".nls"));
170 // nomencl file (old version of the package)
171 FileName const gls(changeExtension(file.absFilename(), ".gls"));
174 // Also remove the aux file
175 FileName const aux(changeExtension(file.absFilename(), ".aux"));
180 int LaTeX::run(TeXErrors & terr)
181 // We know that this function will only be run if the lyx buffer
182 // has been changed. We also know that a newly written .tex file
183 // is always different from the previous one because of the date
184 // in it. However it seems safe to run latex (at least) on time
185 // each time the .tex file changes.
187 int scanres = NO_ERRORS;
188 unsigned int count = 0; // number of times run
189 num_errors = 0; // just to make sure.
190 unsigned int const MAX_RUN = 6;
191 DepTable head; // empty head
192 bool rerun = false; // rerun requested
194 // The class LaTeX does not know the temp path.
195 theBufferList().updateIncludedTeXfiles(getcwd().absFilename(),
198 // Never write the depfile if an error was encountered.
201 // first check if the file dependencies exist:
202 // ->If it does exist
203 // check if any of the files mentioned in it have
204 // changed (done using a checksum).
206 // run latex once and
207 // remake the dependency file
208 // -> if not changed:
209 // just return there is nothing to do for us.
210 // ->if it doesn't exist
212 // run latex once (we need to run latex once anyway) and
213 // remake the dependency file.
216 bool had_depfile = fs::exists(depfile.toFilesystemEncoding());
217 bool run_bibtex = false;
218 FileName const aux_file(changeExtension(file.absFilename(), "aux"));
221 LYXERR(Debug::DEPEND) << "Dependency file exists" << endl;
222 // Read the dep file:
223 had_depfile = head.read(depfile);
227 // Update the checksums
229 // Can't just check if anything has changed because it might
230 // have aborted on error last time... in which cas we need
231 // to re-run latex and collect the error messages
232 // (even if they are the same).
233 if (!fs::exists(output_file.toFilesystemEncoding())) {
234 LYXERR(Debug::DEPEND)
235 << "re-running LaTeX because output file doesn't exist."
237 } else if (!head.sumchange()) {
238 LYXERR(Debug::DEPEND) << "return no_change" << endl;
241 LYXERR(Debug::DEPEND)
242 << "Dependency file has changed" << endl;
245 if (head.extchanged(".bib") || head.extchanged(".bst"))
248 LYXERR(Debug::DEPEND)
249 << "Dependency file does not exist, or has wrong format"
252 /// We scan the aux file even when had_depfile = false,
253 /// because we can run pdflatex on the file after running latex on it,
254 /// in which case we will not need to run bibtex again.
255 vector<Aux_Info> bibtex_info_old;
257 bibtex_info_old = scanAuxFiles(aux_file);
260 LYXERR(Debug::LATEX) << "Run #" << count << endl;
261 message(runMessage(count));
264 scanres = scanLogFile(terr);
265 if (scanres & ERROR_RERUN) {
266 LYXERR(Debug::LATEX) << "Rerunning LaTeX" << endl;
268 scanres = scanLogFile(terr);
271 if (scanres & ERRORS) {
272 deleteFilesOnError();
273 return scanres; // return on error
276 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
277 if (!run_bibtex && bibtex_info_old != bibtex_info)
280 // update the dependencies.
281 deplog(head); // reads the latex log
285 // At this point we must run external programs if needed.
286 // makeindex will be run if a .idx file changed or was generated.
287 // And if there were undefined citations or changes in references
288 // the .aux file is checked for signs of bibtex. Bibtex is then run
291 // memoir (at least) writes an empty *idx file in the first place.
292 // A second latex run is needed.
293 FileName const idxfile(changeExtension(file.absFilename(), ".idx"));
294 rerun = fs::exists(idxfile.toFilesystemEncoding()) &&
295 fs::is_empty(idxfile.toFilesystemEncoding());
298 if (head.haschanged(idxfile)) {
300 LYXERR(Debug::LATEX) << "Running MakeIndex." << endl;
301 message(_("Running MakeIndex."));
302 // onlyFilename() is needed for cygwin
303 rerun |= runMakeIndex(onlyFilename(idxfile.absFilename()),
306 FileName const nlofile(changeExtension(file.absFilename(), ".nlo"));
307 if (head.haschanged(nlofile))
308 rerun |= runMakeIndexNomencl(file, runparams, ".nlo", ".nls");
309 FileName const glofile(changeExtension(file.absFilename(), ".glo"));
310 if (head.haschanged(glofile))
311 rerun |= runMakeIndexNomencl(file, runparams, ".glo", ".gls");
314 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
315 if (scanres & UNDEF_CIT || run_bibtex) {
316 // Here we must scan the .aux file and look for
317 // "\bibdata" and/or "\bibstyle". If one of those
318 // tags is found -> run bibtex and set rerun = true;
320 LYXERR(Debug::LATEX) << "Running BibTeX." << endl;
321 message(_("Running BibTeX."));
322 updateBibtexDependencies(head, bibtex_info);
323 rerun |= runBibTeX(bibtex_info);
324 } else if (!had_depfile) {
325 /// If we run pdflatex on the file after running latex on it,
326 /// then we do not need to run bibtex, but we do need to
327 /// insert the .bib and .bst files into the .dep-pdf file.
328 updateBibtexDependencies(head, bibtex_info);
332 // we know on this point that latex has been run once (or we just
333 // returned) and the question now is to decide if we need to run
334 // it any more. This is done by asking if any of the files in the
335 // dependency file has changed. (remember that the checksum for
336 // a given file is reported to have changed if it just was created)
337 // -> if changed or rerun == true:
338 // run latex once more and
339 // update the dependency structure
340 // -> if not changed:
341 // we does nothing at this point
343 if (rerun || head.sumchange()) {
346 LYXERR(Debug::DEPEND)
347 << "Dep. file has changed or rerun requested"
350 << "Run #" << count << endl;
351 message(runMessage(count));
353 scanres = scanLogFile(terr);
354 if (scanres & ERRORS) {
355 deleteFilesOnError();
356 return scanres; // return on error
359 // update the depedencies
360 deplog(head); // reads the latex log
363 LYXERR(Debug::DEPEND)
364 << "Dep. file has NOT changed"
369 // The inclusion of files generated by external programs like
370 // makeindex or bibtex might have done changes to pagenumbering,
371 // etc. And because of this we must run the external programs
372 // again to make sure everything is redone correctly.
373 // Also there should be no need to run the external programs any
376 // run makeindex if the <file>.idx has changed or was generated.
377 if (head.haschanged(idxfile)) {
379 LYXERR(Debug::LATEX) << "Running MakeIndex." << endl;
380 message(_("Running MakeIndex."));
381 // onlyFilename() is needed for cygwin
382 rerun = runMakeIndex(onlyFilename(changeExtension(
383 file.absFilename(), ".idx")), runparams);
386 // I am not pretty sure if need this twice.
387 if (head.haschanged(nlofile))
388 rerun |= runMakeIndexNomencl(file, runparams, ".nlo", ".nls");
389 if (head.haschanged(glofile))
390 rerun |= runMakeIndexNomencl(file, runparams, ".glo", ".gls");
393 // we will only run latex more if the log file asks for it.
394 // or if the sumchange() is true.
395 // -> rerun asked for:
397 // remake the dependency file
398 // goto 2 or return if max runs are reached.
399 // -> rerun not asked for:
400 // just return (fall out of bottom of func)
402 while ((head.sumchange() || rerun || (scanres & RERUN))
403 && count < MAX_RUN) {
404 // Yes rerun until message goes away, or until
405 // MAX_RUNS are reached.
408 LYXERR(Debug::LATEX) << "Run #" << count << endl;
409 message(runMessage(count));
411 scanres = scanLogFile(terr);
412 if (scanres & ERRORS) {
413 deleteFilesOnError();
414 return scanres; // return on error
421 // Write the dependencies to file.
423 LYXERR(Debug::LATEX) << "Done." << endl;
428 int LaTeX::startscript()
430 // onlyFilename() is needed for cygwin
431 string tmp = cmd + ' '
432 + quoteName(onlyFilename(file.toFilesystemEncoding()))
433 + " > " + os::nulldev();
435 return one.startscript(Systemcall::Wait, tmp);
439 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
440 string const & params)
443 << "idx file has been made, running makeindex on file "
445 string tmp = lyxrc.index_command + ' ';
447 tmp = subst(tmp, "$$lang", runparams.document_language);
451 one.startscript(Systemcall::Wait, tmp);
456 bool LaTeX::runMakeIndexNomencl(FileName const & file,
457 OutputParams const & runparams,
458 string const & nlo, string const & nls)
460 LYXERR(Debug::LATEX) << "Running MakeIndex for nomencl." << endl;
461 message(_("Running MakeIndex for nomencl."));
462 // onlyFilename() is needed for cygwin
463 string const nomenclstr = " -s nomencl.ist -o "
464 + onlyFilename(changeExtension(file.toFilesystemEncoding(), nls));
466 onlyFilename(changeExtension(file.absFilename(), nlo)),
467 runparams, nomenclstr);
471 vector<Aux_Info> const
472 LaTeX::scanAuxFiles(FileName const & file)
474 vector<Aux_Info> result;
476 result.push_back(scanAuxFile(file));
478 string const basename = removeExtension(file.absFilename());
479 for (int i = 1; i < 1000; ++i) {
480 FileName const file2(basename
481 + '.' + convert<string>(i)
483 if (!fs::exists(file2.toFilesystemEncoding()))
485 result.push_back(scanAuxFile(file2));
491 Aux_Info const LaTeX::scanAuxFile(FileName const & file)
494 result.aux_file = file;
495 scanAuxFile(file, result);
500 void LaTeX::scanAuxFile(FileName const & file, Aux_Info & aux_info)
502 LYXERR(Debug::LATEX) << "Scanning aux file: " << file << endl;
504 ifstream ifs(file.toFilesystemEncoding().c_str());
506 static regex const reg1("\\\\citation\\{([^}]+)\\}");
507 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
508 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
509 static regex const reg4("\\\\@input\\{([^}]+)\\}");
511 while (getline(ifs, token)) {
512 token = rtrim(token, "\r");
514 // FIXME UNICODE: We assume that citation keys and filenames
515 // in the aux file are in the file system encoding.
516 token = to_utf8(from_filesystem8bit(token));
517 if (regex_match(token, sub, reg1)) {
518 string data = sub.str(1);
519 while (!data.empty()) {
521 data = split(data, citation, ',');
522 LYXERR(Debug::LATEX) << "Citation: "
524 aux_info.citations.insert(citation);
526 } else if (regex_match(token, sub, reg2)) {
527 string data = sub.str(1);
528 // data is now all the bib files separated by ','
529 // get them one by one and pass them to the helper
530 while (!data.empty()) {
532 data = split(data, database, ',');
533 database = changeExtension(database, "bib");
534 LYXERR(Debug::LATEX) << "BibTeX database: `"
535 << database << '\'' << endl;
536 aux_info.databases.insert(database);
538 } else if (regex_match(token, sub, reg3)) {
539 string style = sub.str(1);
540 // token is now the style file
541 // pass it to the helper
542 style = changeExtension(style, "bst");
543 LYXERR(Debug::LATEX) << "BibTeX style: `"
544 << style << '\'' << endl;
545 aux_info.styles.insert(style);
546 } else if (regex_match(token, sub, reg4)) {
547 string const file2 = sub.str(1);
548 scanAuxFile(makeAbsPath(file2), aux_info);
554 void LaTeX::updateBibtexDependencies(DepTable & dep,
555 vector<Aux_Info> const & bibtex_info)
557 // Since a run of Bibtex mandates more latex runs it is ok to
558 // remove all ".bib" and ".bst" files.
559 dep.remove_files_with_extension(".bib");
560 dep.remove_files_with_extension(".bst");
561 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
563 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
564 it != bibtex_info.end(); ++it) {
565 for (set<string>::const_iterator it2 = it->databases.begin();
566 it2 != it->databases.end(); ++it2) {
567 FileName const file = findtexfile(*it2, "bib");
569 dep.insert(file, true);
572 for (set<string>::const_iterator it2 = it->styles.begin();
573 it2 != it->styles.end(); ++it2) {
574 FileName const file = findtexfile(*it2, "bst");
576 dep.insert(file, true);
582 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
585 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
586 it != bibtex_info.end(); ++it) {
587 if (it->databases.empty())
591 string tmp = lyxrc.bibtex_command + " ";
592 // onlyFilename() is needed for cygwin
593 tmp += quoteName(onlyFilename(removeExtension(
594 it->aux_file.absFilename())));
596 one.startscript(Systemcall::Wait, tmp);
598 // Return whether bibtex was run
603 int LaTeX::scanLogFile(TeXErrors & terr)
607 int retval = NO_ERRORS;
609 onlyFilename(changeExtension(file.absFilename(), ".log"));
610 LYXERR(Debug::LATEX) << "Log file: " << tmp << endl;
611 FileName const fn = FileName(makeAbsPath(tmp));
612 ifstream ifs(fn.toFilesystemEncoding().c_str());
613 bool fle_style = false;
614 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
617 while (getline(ifs, token)) {
618 // MikTeX sometimes inserts \0 in the log file. They can't be
619 // removed directly with the existing string utility
620 // functions, so convert them first to \r, and remove all
621 // \r's afterwards, since we need to remove them anyway.
622 token = subst(token, '\0', '\r');
623 token = subst(token, "\r", "");
626 LYXERR(Debug::LATEX) << "Log line: " << token << endl;
631 if (contains(token, "file:line:error style messages enabled"))
634 if (prefixIs(token, "LaTeX Warning:") ||
635 prefixIs(token, "! pdfTeX warning")) {
636 // Here shall we handle different
638 retval |= LATEX_WARNING;
639 LYXERR(Debug::LATEX) << "LaTeX Warning." << endl;
640 if (contains(token, "Rerun to get cross-references")) {
643 << "We should rerun." << endl;
644 } else if (contains(token, "Citation")
645 && contains(token, "on page")
646 && contains(token, "undefined")) {
649 } else if (prefixIs(token, "Package")) {
651 retval |= PACKAGE_WARNING;
652 if (contains(token, "natbib Warning:")) {
654 if (contains(token, "Citation")
655 && contains(token, "on page")
656 && contains(token, "undefined")) {
659 } else if (contains(token, "run BibTeX")) {
661 } else if (contains(token, "Rerun LaTeX") ||
662 contains(token, "Rerun to get")) {
663 // at least longtable.sty and bibtopic.sty
666 << "We should rerun." << endl;
669 } else if (token[0] == '(') {
670 if (contains(token, "Rerun LaTeX") ||
671 contains(token, "Rerun to get")) {
674 << "We should rerun." << endl;
677 } else if (prefixIs(token, "! ") ||
678 fle_style && regex_match(token, sub, file_line_error)) {
679 // Ok, we have something that looks like a TeX Error
680 // but what do we really have.
682 // Just get the error description:
684 if (prefixIs(token, "! "))
685 desc = string(token, 2);
688 if (contains(token, "LaTeX Error:"))
689 retval |= LATEX_ERROR;
694 if (!getline(ifs, tmp))
698 } while (!prefixIs(tmp, "l."));
699 if (prefixIs(tmp, "l.")) {
700 // we have a latex error
703 "Package babel Error: You haven't defined the language") ||
705 "Package babel Error: You haven't loaded the option"))
706 retval |= ERROR_RERUN;
707 // get the line number:
709 sscanf(tmp.c_str(), "l.%d", &line);
710 // get the rest of the message:
711 string errstr(tmp, tmp.find(' '));
714 while (!contains(errstr, "l.")
716 && !prefixIs(tmp, "! ")
717 && !contains(tmp, "(job aborted")) {
723 << "line: " << line << '\n'
724 << "Desc: " << desc << '\n'
725 << "Text: " << errstr << endl;
726 if (line == last_line)
732 if (line_count <= 5) {
734 // We have no idea what the encoding of
736 // It seems that the output from the
737 // latex compiler itself is pure ASCII,
738 // but it can include bits from the
739 // document, so whatever encoding we
740 // assume here it can be wrong.
741 terr.insertError(line,
742 from_local8bit(desc),
743 from_local8bit(errstr));
748 // information messages, TeX warnings and other
749 // warnings we have not caught earlier.
750 if (prefixIs(token, "Overfull ")) {
751 retval |= TEX_WARNING;
752 } else if (prefixIs(token, "Underfull ")) {
753 retval |= TEX_WARNING;
754 } else if (contains(token, "Rerun to get citations")) {
755 // Natbib seems to use this.
757 } else if (contains(token, "No pages of output")) {
758 // A dvi file was not created
760 } else if (contains(token, "That makes 100 errors")) {
761 // More than 100 errors were reprted
762 retval |= TOO_MANY_ERRORS;
766 LYXERR(Debug::LATEX) << "Log line: " << token << endl;
774 * Wrapper around fs::exists that can handle invalid file names.
775 * In theory we could test with fs::native whether a filename is valid
776 * before calling fs::exists, but in practice it is unusable: On windows it
777 * does not allow spaces, and on unix it does not allow absolute file names.
778 * This function has the disadvantage that it catches also other errors than
779 * invalid names, but for dependency checking we can live with that.
781 bool exists(FileName const & possible_name) {
783 return fs::exists(possible_name.toFilesystemEncoding());
785 catch (fs::filesystem_error const & fe) {
786 LYXERR(Debug::DEPEND) << "Got error `" << fe.what()
787 << "' while checking whether file `" << possible_name
788 << "' exists." << endl;
794 bool insertIfExists(FileName const & absname, DepTable & head)
796 if (exists(absname) &&
797 !fs::is_directory(absname.toFilesystemEncoding())) {
798 head.insert(absname, true);
805 bool handleFoundFile(string const & ff, DepTable & head)
807 // convert from native os path to unix path
808 string foundfile = os::internal_path(trim(ff));
810 LYXERR(Debug::DEPEND) << "Found file: " << foundfile << endl;
812 // Ok now we found a file.
813 // Now we should make sure that this is a file that we can
814 // access through the normal paths.
815 // We will not try any fancy search methods to
818 // (1) foundfile is an
819 // absolute path and should
821 if (absolutePath(foundfile)) {
822 LYXERR(Debug::DEPEND) << "AbsolutePath file: "
823 << foundfile << endl;
824 // On initial insert we want to do the update at once
825 // since this file cannot be a file generated by
827 FileName absname(foundfile);
828 if (!insertIfExists(absname, head)) {
830 string strippedfile = foundfile;
831 while (contains(strippedfile, " ")) {
832 // files with spaces are often enclosed in quotation
833 // marks; those have to be removed
834 string unquoted = subst(strippedfile, "\"", "");
835 absname.set(unquoted);
836 if (insertIfExists(absname, head))
838 // strip off part after last space and try again
839 string tmp = strippedfile;
840 string const stripoff =
841 rsplit(tmp, strippedfile, ' ');
842 absname.set(strippedfile);
843 if (insertIfExists(absname, head))
849 string onlyfile = onlyFilename(foundfile);
850 FileName absname(makeAbsPath(onlyfile));
853 while (contains(foundfile, ' ')) {
858 // files with spaces are often enclosed in quotation
859 // marks; those have to be removed
860 string unquoted = subst(foundfile, "\"", "");
861 absname = makeAbsPath(unquoted);
864 // strip off part after last space and try again
866 string const stripoff =
867 rsplit(foundfile, strippedfile, ' ');
868 foundfile = strippedfile;
869 onlyfile = onlyFilename(strippedfile);
870 absname = makeAbsPath(onlyfile);
874 // (2) foundfile is in the tmpdir
875 // insert it into head
876 if (exists(absname) &&
877 !fs::is_directory(absname.toFilesystemEncoding())) {
878 // FIXME: This regex contained glo, but glo is used by the old
879 // version of nomencl.sty. Do we need to put it back?
880 static regex unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
881 if (regex_match(onlyfile, unwanted)) {
882 LYXERR(Debug::DEPEND)
885 << " in the dep file"
887 } else if (suffixIs(onlyfile, ".tex")) {
888 // This is a tex file generated by LyX
889 // and latex is not likely to change this
891 LYXERR(Debug::DEPEND)
892 << "Tmpdir TeX file: "
895 head.insert(absname, true);
897 LYXERR(Debug::DEPEND)
901 head.insert(absname);
905 LYXERR(Debug::DEPEND)
906 << "Not a file or we are unable to find it."
913 bool checkLineBreak(string const & ff, DepTable & head)
915 if (contains(ff, '.'))
916 // if we have a dot, we let handleFoundFile decide
917 return handleFoundFile(ff, head);
919 // else, we suspect a line break
926 void LaTeX::deplog(DepTable & head)
928 // This function reads the LaTeX log file end extracts all the
929 // external files used by the LaTeX run. The files are then
930 // entered into the dependency file.
932 string const logfile =
933 onlyFilename(changeExtension(file.absFilename(), ".log"));
935 static regex reg1("File: (.+).*");
936 static regex reg2("No file (.+)(.).*");
937 static regex reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
938 // If an index should be created, MikTex does not write a line like
939 // \openout# = 'sample.idx'.
940 // but instead only a line like this into the log:
941 // Writing index file sample.idx
942 static regex reg4("Writing index file (.+).*");
943 // files also can be enclosed in <...>
944 static regex reg5("<([^>]+)(.).*");
945 static regex regoldnomencl("Writing glossary file (.+).*");
946 static regex regnomencl("Writing nomenclature file (.+).*");
947 // If a toc should be created, MikTex does not write a line like
948 // \openout# = `sample.toc'.
949 // but only a line like this into the log:
951 // This line is also written by tetex.
952 // This line is not present if no toc should be created.
953 static regex miktexTocReg("\\\\tf@toc=\\\\write.*");
954 static regex reg6(".*\\([^)]+.*");
956 FileName const fn(makeAbsPath(logfile));
957 ifstream ifs(fn.toFilesystemEncoding().c_str());
960 // Ok, the scanning of files here is not sufficient.
961 // Sometimes files are named by "File: xxx" only
962 // So I think we should use some regexps to find files instead.
963 // Note: all file names and paths might contains spaces.
964 bool found_file = false;
967 // MikTeX sometimes inserts \0 in the log file. They can't be
968 // removed directly with the existing string utility
969 // functions, so convert them first to \r, and remove all
970 // \r's afterwards, since we need to remove them anyway.
971 token = subst(token, '\0', '\r');
972 token = subst(token, "\r", "");
973 if (token.empty() || token == ")") {
978 // Sometimes, filenames are broken across lines.
979 // We care for that and save suspicious lines.
980 // Here we exclude some cases where we are sure
981 // that there is no continued filename
982 if (!lastline.empty()) {
983 static regex package_info("Package \\w+ Info: .*");
984 static regex package_warning("Package \\w+ Warning: .*");
985 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
986 || prefixIs(token, "Package:")
987 || prefixIs(token, "Language:")
988 || prefixIs(token, "LaTeX Info:")
989 || prefixIs(token, "LaTeX Font Info:")
990 || prefixIs(token, "\\openout[")
991 || prefixIs(token, "))")
992 || regex_match(token, package_info)
993 || regex_match(token, package_warning))
997 if (!lastline.empty())
998 // probably a continued filename from last line
999 token = lastline + token;
1000 if (token.length() > 255) {
1001 // string too long. Cut off.
1002 token.erase(0, token.length() - 251);
1007 // FIXME UNICODE: We assume that the file names in the log
1008 // file are in the file system encoding.
1009 token = to_utf8(from_filesystem8bit(token));
1011 // (1) "File: file.ext"
1012 if (regex_match(token, sub, reg1)) {
1014 found_file = checkLineBreak(sub.str(1), head);
1016 if (suffixIs(token, ")"))
1017 // no line break for sure
1018 // pretend we've been succesfully searching
1020 // (2) "No file file.ext"
1021 } else if (regex_match(token, sub, reg2)) {
1022 // file names must contains a dot, line ends with dot
1023 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1024 found_file = handleFoundFile(sub.str(1), head);
1026 // we suspect a line break
1028 // (3) "\openout<nr> = `file.ext'."
1029 } else if (regex_match(token, sub, reg3)) {
1030 // search for closing '. at the end of the line
1031 if (sub.str(2) == "\'.")
1032 found_file = handleFoundFile(sub.str(1), head);
1034 // probable line break
1036 // (4) "Writing index file file.ext"
1037 } else if (regex_match(token, sub, reg4))
1039 found_file = checkLineBreak(sub.str(1), head);
1041 else if (regex_match(token, sub, reg5)) {
1042 // search for closing '>' and dot ('*.*>') at the eol
1043 if (contains(sub.str(1), '.') && sub.str(2) == ">")
1044 found_file = handleFoundFile(sub.str(1), head);
1046 // probable line break
1048 // (6) "Writing nomenclature file file.ext"
1049 } else if (regex_match(token, sub, regnomencl) ||
1050 regex_match(token, sub, regoldnomencl))
1052 found_file = checkLineBreak(sub.str(1), head);
1053 // (7) "\tf@toc=\write<nr>" (for MikTeX)
1054 else if (regex_match(token, sub, miktexTocReg))
1055 found_file = handleFoundFile(onlyFilename(changeExtension(
1056 file.absFilename(), ".toc")), head);
1058 // not found, but we won't check further
1059 // pretend we've been succesfully searching
1063 // note that we can have several of these on one line
1064 // this must be queried separated, because of
1065 // cases such as "File: file.ext (type eps)"
1066 // where "File: file.ext" would be skipped
1067 if (regex_match(token, sub, reg6)) {
1068 // search for strings in (...)
1069 static regex reg6_1("\\(([^()]+)(.).*");
1071 string::const_iterator first = token.begin();
1072 string::const_iterator end = token.end();
1074 while (regex_search(first, end, what, reg6_1)) {
1075 // if we have a dot, try to handle as file
1076 if (contains(what.str(1), '.')) {
1077 first = what[0].second;
1078 if (what.str(2) == ")") {
1079 handleFoundFile(what.str(1), head);
1080 // since we had a closing bracket,
1081 // do not investigate further
1084 // if we have no closing bracket,
1085 // try to handle as file nevertheless
1086 found_file = handleFoundFile(
1087 what.str(1) + what.str(2), head);
1089 // if we do not have a dot, check if the line has
1090 // a closing bracket (else, we suspect a line break)
1091 else if (what.str(2) != ")") {
1092 first = what[0].second;
1095 // we have a closing bracket, so the content
1096 // is not a file name.
1097 // no need to investigate further
1098 // pretend we've been succesfully searching
1099 first = what[0].second;
1106 // probable linebreak:
1110 // no linebreak: reset
1111 lastline = string();
1114 // Make sure that the main .tex file is in the dependency file.
1115 head.insert(file, true);