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 "support/regex.h"
38 using namespace lyx::support;
42 namespace os = support::os;
44 // TODO: in no particular order
45 // - get rid of the call to
46 // BufferList::updateIncludedTeXfiles, this should either
47 // be done before calling LaTeX::funcs or in a completely
49 // - the makeindex style files should be taken care of with
50 // the dependency mechanism.
51 // - we should perhaps also scan the bibtex log file
55 docstring runMessage(unsigned int count)
57 return bformat(_("Waiting for LaTeX run number %1$d"), count);
66 void TeXErrors::insertError(int line, docstring const & error_desc,
67 docstring const & error_text)
69 Error newerr(line, error_desc, error_text);
70 errors.push_back(newerr);
74 bool operator==(AuxInfo const & a, AuxInfo const & o)
76 return a.aux_file == o.aux_file
77 && a.citations == o.citations
78 && a.databases == o.databases
79 && a.styles == o.styles;
83 bool operator!=(AuxInfo const & a, AuxInfo const & o)
93 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
95 : cmd(latex), file(f), runparams(rp)
98 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
99 depfile = FileName(file.absFileName() + ".dep-pdf");
101 FileName(changeExtension(file.absFileName(), ".pdf"));
103 depfile = FileName(file.absFileName() + ".dep");
105 FileName(changeExtension(file.absFileName(), ".dvi"));
110 void LaTeX::deleteFilesOnError() const
112 // currently just a dummy function.
114 // What files do we have to delete?
116 // This will at least make latex do all the runs
117 depfile.removeFile();
119 // but the reason for the error might be in a generated file...
122 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
126 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
130 FileName const ind(changeExtension(file.absFileName(), ".ind"));
134 FileName const nls(changeExtension(file.absFileName(), ".nls"));
137 // nomencl file (old version of the package)
138 FileName const gls(changeExtension(file.absFileName(), ".gls"));
141 // Also remove the aux file
142 FileName const aux(changeExtension(file.absFileName(), ".aux"));
147 int LaTeX::run(TeXErrors & terr)
148 // We know that this function will only be run if the lyx buffer
149 // has been changed. We also know that a newly written .tex file
150 // is always different from the previous one because of the date
151 // in it. However it seems safe to run latex (at least) one time
152 // each time the .tex file changes.
154 int scanres = NO_ERRORS;
155 unsigned int count = 0; // number of times run
156 num_errors = 0; // just to make sure.
157 unsigned int const MAX_RUN = 6;
158 DepTable head; // empty head
159 bool rerun = false; // rerun requested
161 // The class LaTeX does not know the temp path.
162 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
165 // Never write the depfile if an error was encountered.
168 // first check if the file dependencies exist:
169 // ->If it does exist
170 // check if any of the files mentioned in it have
171 // changed (done using a checksum).
173 // run latex once and
174 // remake the dependency file
175 // -> if not changed:
176 // just return there is nothing to do for us.
177 // ->if it doesn't exist
179 // run latex once (we need to run latex once anyway) and
180 // remake the dependency file.
183 bool had_depfile = depfile.exists();
184 bool run_bibtex = false;
185 FileName const aux_file(changeExtension(file.absFileName(), "aux"));
188 LYXERR(Debug::DEPEND, "Dependency file exists");
189 // Read the dep file:
190 had_depfile = head.read(depfile);
194 // Update the checksums
196 // Can't just check if anything has changed because it might
197 // have aborted on error last time... in which cas we need
198 // to re-run latex and collect the error messages
199 // (even if they are the same).
200 if (!output_file.exists()) {
201 LYXERR(Debug::DEPEND,
202 "re-running LaTeX because output file doesn't exist.");
203 } else if (!head.sumchange()) {
204 LYXERR(Debug::DEPEND, "return no_change");
207 LYXERR(Debug::DEPEND, "Dependency file has changed");
210 if (head.extchanged(".bib") || head.extchanged(".bst")
211 || head.extchanged(".bcf"))
214 LYXERR(Debug::DEPEND,
215 "Dependency file does not exist, or has wrong format");
217 /// We scan the aux file even when had_depfile = false,
218 /// because we can run pdflatex on the file after running latex on it,
219 /// in which case we will not need to run bibtex again.
220 vector<AuxInfo> bibtex_info_old;
222 bibtex_info_old = scanAuxFiles(aux_file);
225 LYXERR(Debug::LATEX, "Run #" << count);
226 message(runMessage(count));
229 scanres = scanLogFile(terr);
230 if (scanres & ERROR_RERUN) {
231 LYXERR(Debug::LATEX, "Rerunning LaTeX");
233 scanres = scanLogFile(terr);
236 if (scanres & ERRORS) {
237 deleteFilesOnError();
238 return scanres; // return on error
241 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
242 if (!run_bibtex && bibtex_info_old != bibtex_info)
245 // update the dependencies.
246 deplog(head); // reads the latex log
250 // At this point we must run external programs if needed.
251 // makeindex will be run if a .idx file changed or was generated.
252 // And if there were undefined citations or changes in references
253 // the .aux file is checked for signs of bibtex. Bibtex is then run
256 // memoir (at least) writes an empty *idx file in the first place.
257 // A second latex run is needed.
258 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
259 rerun = idxfile.exists() && idxfile.isFileEmpty();
262 if (head.haschanged(idxfile)) {
264 LYXERR(Debug::LATEX, "Running MakeIndex.");
265 message(_("Running Index Processor."));
266 // onlyFileName() is needed for cygwin
267 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
270 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
271 if (head.haschanged(nlofile))
272 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
273 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
274 if (head.haschanged(glofile))
275 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
277 // check if we're using biber instead of bibtex
278 // biber writes no info to the aux file, so we just check
279 // if a bcf file exists (and, above, if it was updated)
280 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
281 bool const biber = bcffile.exists();
284 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
285 if (scanres & UNDEF_CIT || run_bibtex) {
286 // Here we must scan the .aux file and look for
287 // "\bibdata" and/or "\bibstyle". If one of those
288 // tags is found -> run bibtex and set rerun = true;
290 LYXERR(Debug::LATEX, "Running BibTeX.");
291 message(_("Running BibTeX."));
292 updateBibtexDependencies(head, bibtex_info);
293 rerun |= runBibTeX(bibtex_info, runparams, biber);
294 } else if (!had_depfile) {
295 /// If we run pdflatex on the file after running latex on it,
296 /// then we do not need to run bibtex, but we do need to
297 /// insert the .bib and .bst files into the .dep-pdf file.
298 updateBibtexDependencies(head, bibtex_info);
302 // we know on this point that latex has been run once (or we just
303 // returned) and the question now is to decide if we need to run
304 // it any more. This is done by asking if any of the files in the
305 // dependency file has changed. (remember that the checksum for
306 // a given file is reported to have changed if it just was created)
307 // -> if changed or rerun == true:
308 // run latex once more and
309 // update the dependency structure
310 // -> if not changed:
311 // we do nothing at this point
313 if (rerun || head.sumchange()) {
316 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
317 LYXERR(Debug::LATEX, "Run #" << count);
318 message(runMessage(count));
320 scanres = scanLogFile(terr);
321 if (scanres & ERRORS) {
322 deleteFilesOnError();
323 return scanres; // return on error
326 // update the depedencies
327 deplog(head); // reads the latex log
330 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
335 // Complex bibliography packages such as Biblatex require
336 // an additional bibtex cycle sometimes.
337 if (scanres & UNDEF_CIT) {
338 // Here we must scan the .aux file and look for
339 // "\bibdata" and/or "\bibstyle". If one of those
340 // tags is found -> run bibtex and set rerun = true;
342 LYXERR(Debug::LATEX, "Running BibTeX.");
343 message(_("Running BibTeX."));
344 updateBibtexDependencies(head, bibtex_info);
345 rerun |= runBibTeX(bibtex_info, runparams, biber);
349 // The inclusion of files generated by external programs such as
350 // makeindex or bibtex might have done changes to pagenumbering,
351 // etc. And because of this we must run the external programs
352 // again to make sure everything is redone correctly.
353 // Also there should be no need to run the external programs any
356 // run makeindex if the <file>.idx has changed or was generated.
357 if (head.haschanged(idxfile)) {
359 LYXERR(Debug::LATEX, "Running MakeIndex.");
360 message(_("Running Index Processor."));
361 // onlyFileName() is needed for cygwin
362 rerun = runMakeIndex(onlyFileName(changeExtension(
363 file.absFileName(), ".idx")), runparams);
366 // I am not pretty sure if need this twice.
367 if (head.haschanged(nlofile))
368 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
369 if (head.haschanged(glofile))
370 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
373 // we will only run latex more if the log file asks for it.
374 // or if the sumchange() is true.
375 // -> rerun asked for:
377 // remake the dependency file
378 // goto 2 or return if max runs are reached.
379 // -> rerun not asked for:
380 // just return (fall out of bottom of func)
382 while ((head.sumchange() || rerun || (scanres & RERUN))
383 && count < MAX_RUN) {
384 // Yes rerun until message goes away, or until
385 // MAX_RUNS are reached.
388 LYXERR(Debug::LATEX, "Run #" << count);
389 message(runMessage(count));
391 scanres = scanLogFile(terr);
392 if (scanres & ERRORS) {
393 deleteFilesOnError();
394 return scanres; // return on error
401 // Write the dependencies to file.
403 LYXERR(Debug::LATEX, "Done.");
408 int LaTeX::startscript()
410 // onlyFileName() is needed for cygwin
411 string tmp = cmd + ' '
412 + quoteName(onlyFileName(file.toFilesystemEncoding()))
413 + " > " + os::nulldev();
415 return one.startscript(Systemcall::Wait, tmp);
419 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
420 string const & params)
422 string tmp = runparams.use_japanese ?
423 lyxrc.jindex_command : lyxrc.index_command;
425 if (!runparams.index_command.empty())
426 tmp = runparams.index_command;
429 "idx file has been made, running index processor ("
430 << tmp << ") on file " << f);
432 tmp = subst(tmp, "$$lang", runparams.document_language);
433 if (runparams.use_indices) {
434 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
436 "Multiple indices. Using splitindex command: " << tmp);
442 one.startscript(Systemcall::Wait, tmp);
447 bool LaTeX::runMakeIndexNomencl(FileName const & file,
448 string const & nlo, string const & nls)
450 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
451 message(_("Running MakeIndex for nomencl."));
452 string tmp = lyxrc.nomencl_command + ' ';
453 // onlyFileName() is needed for cygwin
454 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
456 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
458 one.startscript(Systemcall::Wait, tmp);
463 vector<AuxInfo> const
464 LaTeX::scanAuxFiles(FileName const & file)
466 vector<AuxInfo> result;
468 result.push_back(scanAuxFile(file));
470 string const basename = removeExtension(file.absFileName());
471 for (int i = 1; i < 1000; ++i) {
472 FileName const file2(basename
473 + '.' + convert<string>(i)
477 result.push_back(scanAuxFile(file2));
483 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
486 result.aux_file = file;
487 scanAuxFile(file, result);
492 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
494 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
496 ifstream ifs(file.toFilesystemEncoding().c_str());
498 static regex const reg1("\\\\citation\\{([^}]+)\\}");
499 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
500 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
501 static regex const reg4("\\\\@input\\{([^}]+)\\}");
503 while (getline(ifs, token)) {
504 token = rtrim(token, "\r");
506 // FIXME UNICODE: We assume that citation keys and filenames
507 // in the aux file are in the file system encoding.
508 token = to_utf8(from_filesystem8bit(token));
509 if (regex_match(token, sub, reg1)) {
510 string data = sub.str(1);
511 while (!data.empty()) {
513 data = split(data, citation, ',');
514 LYXERR(Debug::LATEX, "Citation: " << citation);
515 aux_info.citations.insert(citation);
517 } else if (regex_match(token, sub, reg2)) {
518 string data = sub.str(1);
519 // data is now all the bib files separated by ','
520 // get them one by one and pass them to the helper
521 while (!data.empty()) {
523 data = split(data, database, ',');
524 database = changeExtension(database, "bib");
525 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
526 aux_info.databases.insert(database);
528 } else if (regex_match(token, sub, reg3)) {
529 string style = sub.str(1);
530 // token is now the style file
531 // pass it to the helper
532 style = changeExtension(style, "bst");
533 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
534 aux_info.styles.insert(style);
535 } else if (regex_match(token, sub, reg4)) {
536 string const file2 = sub.str(1);
537 scanAuxFile(makeAbsPath(file2), aux_info);
543 void LaTeX::updateBibtexDependencies(DepTable & dep,
544 vector<AuxInfo> const & bibtex_info)
546 // Since a run of Bibtex mandates more latex runs it is ok to
547 // remove all ".bib" and ".bst" files.
548 dep.remove_files_with_extension(".bib");
549 dep.remove_files_with_extension(".bst");
550 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
552 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
553 it != bibtex_info.end(); ++it) {
554 for (set<string>::const_iterator it2 = it->databases.begin();
555 it2 != it->databases.end(); ++it2) {
556 FileName const file = findtexfile(*it2, "bib");
558 dep.insert(file, true);
561 for (set<string>::const_iterator it2 = it->styles.begin();
562 it2 != it->styles.end(); ++it2) {
563 FileName const file = findtexfile(*it2, "bst");
565 dep.insert(file, true);
571 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
572 OutputParams const & runparams, bool biber)
575 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
576 it != bibtex_info.end(); ++it) {
577 if (!biber && it->databases.empty())
581 string tmp = runparams.use_japanese ?
582 lyxrc.jbibtex_command : lyxrc.bibtex_command;
584 if (!runparams.bibtex_command.empty())
585 tmp = runparams.bibtex_command;
587 // onlyFileName() is needed for cygwin
588 tmp += quoteName(onlyFileName(removeExtension(
589 it->aux_file.absFileName())));
591 one.startscript(Systemcall::Wait, tmp);
593 // Return whether bibtex was run
598 int LaTeX::scanLogFile(TeXErrors & terr)
602 int retval = NO_ERRORS;
604 onlyFileName(changeExtension(file.absFileName(), ".log"));
605 LYXERR(Debug::LATEX, "Log file: " << tmp);
606 FileName const fn = FileName(makeAbsPath(tmp));
607 ifstream ifs(fn.toFilesystemEncoding().c_str());
608 bool fle_style = false;
609 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
610 // Flag for 'File ended while scanning' message.
611 // We need to wait for subsequent processing.
612 string wait_for_error;
615 while (getline(ifs, token)) {
616 // MikTeX sometimes inserts \0 in the log file. They can't be
617 // removed directly with the existing string utility
618 // functions, so convert them first to \r, and remove all
619 // \r's afterwards, since we need to remove them anyway.
620 token = subst(token, '\0', '\r');
621 token = subst(token, "\r", "");
624 LYXERR(Debug::LATEX, "Log line: " << token);
629 if (contains(token, "file:line:error style messages enabled"))
632 if (prefixIs(token, "LaTeX Warning:") ||
633 prefixIs(token, "! pdfTeX warning")) {
634 // Here shall we handle different
636 retval |= LATEX_WARNING;
637 LYXERR(Debug::LATEX, "LaTeX Warning.");
638 if (contains(token, "Rerun to get cross-references")) {
640 LYXERR(Debug::LATEX, "We should rerun.");
641 // package clefval needs 2 latex runs before bibtex
642 } else if (contains(token, "Value of")
643 && contains(token, "on page")
644 && contains(token, "undefined")) {
645 retval |= ERROR_RERUN;
646 LYXERR(Debug::LATEX, "Force rerun.");
648 } else if (contains(token, "Etaremune labels have changed")) {
649 retval |= ERROR_RERUN;
650 LYXERR(Debug::LATEX, "Force rerun.");
651 } else if (contains(token, "Citation")
652 && contains(token, "on page")
653 && contains(token, "undefined")) {
656 } else if (prefixIs(token, "Package")) {
658 retval |= PACKAGE_WARNING;
659 if (contains(token, "natbib Warning:")) {
661 if (contains(token, "Citation")
662 && contains(token, "on page")
663 && contains(token, "undefined")) {
666 } else if (contains(token, "run BibTeX")) {
668 } else if (contains(token, "Rerun LaTeX") ||
669 contains(token, "Please rerun LaTeX") ||
670 contains(token, "Rerun to get")) {
671 // at least longtable.sty and bibtopic.sty
673 LYXERR(Debug::LATEX, "We should rerun.");
676 } else if (prefixIs(token, "LETTRE WARNING:")) {
677 if (contains(token, "veuillez recompiler")) {
679 LYXERR(Debug::LATEX, "We should rerun.");
682 } else if (token[0] == '(') {
683 if (contains(token, "Rerun LaTeX") ||
684 contains(token, "Rerun to get")) {
686 LYXERR(Debug::LATEX, "We should rerun.");
689 } else if (prefixIs(token, "! ")
691 && regex_match(token, sub, file_line_error)
692 && !contains(token, "pdfTeX warning"))) {
693 // Ok, we have something that looks like a TeX Error
694 // but what do we really have.
696 // Just get the error description:
698 if (prefixIs(token, "! "))
699 desc = string(token, 2);
702 if (contains(token, "LaTeX Error:"))
703 retval |= LATEX_ERROR;
705 // bug 6445. At this point its not clear we finish with error.
706 if (prefixIs(token, "! File ended while scanning")){
707 wait_for_error = desc;
710 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
711 retval |= LATEX_ERROR;
714 errstr = wait_for_error;
716 if (!getline(ifs, tmp))
718 errstr += "\n" + tmp;
721 } while (!contains(tmp, "(job aborted"));
724 from_local8bit("Emergency stop"),
725 from_local8bit(errstr));
732 if (!getline(ifs, tmp))
736 } while (!prefixIs(tmp, "l."));
737 if (prefixIs(tmp, "l.")) {
738 // we have a latex error
741 "Package babel Error: You haven't defined the language") ||
743 "Package babel Error: You haven't loaded the option"))
744 retval |= ERROR_RERUN;
745 // get the line number:
747 sscanf(tmp.c_str(), "l.%d", &line);
748 // get the rest of the message:
749 string errstr(tmp, tmp.find(' '));
752 while (!contains(errstr, "l.")
754 && !prefixIs(tmp, "! ")
755 && !contains(tmp, "(job aborted")) {
760 LYXERR(Debug::LATEX, "line: " << line << '\n'
761 << "Desc: " << desc << '\n' << "Text: " << errstr);
762 if (line == last_line)
768 if (line_count <= 5) {
770 // We have no idea what the encoding of
772 // It seems that the output from the
773 // latex compiler itself is pure ASCII,
774 // but it can include bits from the
775 // document, so whatever encoding we
776 // assume here it can be wrong.
777 terr.insertError(line,
778 from_local8bit(desc),
779 from_local8bit(errstr));
784 // information messages, TeX warnings and other
785 // warnings we have not caught earlier.
786 if (prefixIs(token, "Overfull ")) {
787 retval |= TEX_WARNING;
788 } else if (prefixIs(token, "Underfull ")) {
789 retval |= TEX_WARNING;
790 } else if (contains(token, "Rerun to get citations")) {
791 // Natbib seems to use this.
793 } else if (contains(token, "No pages of output")) {
794 // A dvi file was not created
796 } else if (contains(token, "That makes 100 errors")) {
797 // More than 100 errors were reprted
798 retval |= TOO_MANY_ERRORS;
799 } else if (prefixIs(token, "!pdfTeX error:")){
800 // otherwise we dont catch e.g.:
801 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
804 from_local8bit("pdfTeX Error"),
805 from_local8bit(token));
809 LYXERR(Debug::LATEX, "Log line: " << token);
816 bool insertIfExists(FileName const & absname, DepTable & head)
818 if (absname.exists() && !absname.isDirectory()) {
819 head.insert(absname, true);
826 bool handleFoundFile(string const & ff, DepTable & head)
828 // convert from native os path to unix path
829 string foundfile = os::internal_path(trim(ff));
831 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
833 // Ok now we found a file.
834 // Now we should make sure that this is a file that we can
835 // access through the normal paths.
836 // We will not try any fancy search methods to
839 // (1) foundfile is an
840 // absolute path and should
843 if (FileName::isAbsolute(foundfile)) {
844 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
845 // On initial insert we want to do the update at once
846 // since this file cannot be a file generated by
848 absname.set(foundfile);
849 if (!insertIfExists(absname, head)) {
851 string strippedfile = foundfile;
852 while (contains(strippedfile, " ")) {
853 // files with spaces are often enclosed in quotation
854 // marks; those have to be removed
855 string unquoted = subst(strippedfile, "\"", "");
856 absname.set(unquoted);
857 if (insertIfExists(absname, head))
859 // strip off part after last space and try again
860 string tmp = strippedfile;
861 string const stripoff =
862 rsplit(tmp, strippedfile, ' ');
863 absname.set(strippedfile);
864 if (insertIfExists(absname, head))
870 string onlyfile = onlyFileName(foundfile);
871 absname = makeAbsPath(onlyfile);
874 while (contains(foundfile, ' ')) {
875 if (absname.exists())
879 // files with spaces are often enclosed in quotation
880 // marks; those have to be removed
881 string unquoted = subst(foundfile, "\"", "");
882 absname = makeAbsPath(unquoted);
883 if (absname.exists())
885 // strip off part after last space and try again
887 string const stripoff =
888 rsplit(foundfile, strippedfile, ' ');
889 foundfile = strippedfile;
890 onlyfile = onlyFileName(strippedfile);
891 absname = makeAbsPath(onlyfile);
895 // (2) foundfile is in the tmpdir
896 // insert it into head
897 if (absname.exists() && !absname.isDirectory()) {
898 // FIXME: This regex contained glo, but glo is used by the old
899 // version of nomencl.sty. Do we need to put it back?
900 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
901 if (regex_match(onlyfile, unwanted)) {
902 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
903 << " in the dep file");
904 } else if (suffixIs(onlyfile, ".tex")) {
905 // This is a tex file generated by LyX
906 // and latex is not likely to change this
908 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
909 head.insert(absname, true);
911 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
912 head.insert(absname);
916 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
922 bool checkLineBreak(string const & ff, DepTable & head)
924 if (!contains(ff, '.'))
927 // if we have a dot, we let handleFoundFile decide
928 return handleFoundFile(ff, head);
934 void LaTeX::deplog(DepTable & head)
936 // This function reads the LaTeX log file end extracts all the
937 // external files used by the LaTeX run. The files are then
938 // entered into the dependency file.
940 string const logfile =
941 onlyFileName(changeExtension(file.absFileName(), ".log"));
943 static regex const reg1("File: (.+).*");
944 static regex const reg2("No file (.+)(.).*");
945 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
946 // If an index should be created, MikTex does not write a line like
947 // \openout# = 'sample.idx'.
948 // but instead only a line like this into the log:
949 // Writing index file sample.idx
950 static regex const reg4("Writing index file (.+).*");
951 // files also can be enclosed in <...>
952 static regex const reg5("<([^>]+)(.).*");
953 static regex const regoldnomencl("Writing glossary file (.+).*");
954 static regex const regnomencl("Writing nomenclature file (.+).*");
955 // If a toc should be created, MikTex does not write a line like
956 // \openout# = `sample.toc'.
957 // but only a line like this into the log:
959 // This line is also written by tetex.
960 // This line is not present if no toc should be created.
961 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
962 static regex const reg6(".*\\([^)]+.*");
964 FileName const fn = makeAbsPath(logfile);
965 ifstream ifs(fn.toFilesystemEncoding().c_str());
968 // Ok, the scanning of files here is not sufficient.
969 // Sometimes files are named by "File:� xxx" only
970 // So I think we should use some regexps to find files instead.
971 // Note: all file names and paths might contains spaces.
972 bool found_file = false;
975 // MikTeX sometimes inserts \0 in the log file. They can't be
976 // removed directly with the existing string utility
977 // functions, so convert them first to \r, and remove all
978 // \r's afterwards, since we need to remove them anyway.
979 token = subst(token, '\0', '\r');
980 token = subst(token, "\r", "");
981 if (token.empty() || token == ")") {
986 // Sometimes, filenames are broken across lines.
987 // We care for that and save suspicious lines.
988 // Here we exclude some cases where we are sure
989 // that there is no continued filename
990 if (!lastline.empty()) {
991 static regex const package_info("Package \\w+ Info: .*");
992 static regex const package_warning("Package \\w+ Warning: .*");
993 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
994 || prefixIs(token, "Package:")
995 || prefixIs(token, "Language:")
996 || prefixIs(token, "LaTeX Info:")
997 || prefixIs(token, "LaTeX Font Info:")
998 || prefixIs(token, "\\openout[")
999 || prefixIs(token, "))")
1000 || regex_match(token, package_info)
1001 || regex_match(token, package_warning))
1002 lastline = string();
1005 if (!lastline.empty())
1006 // probably a continued filename from last line
1007 token = lastline + token;
1008 if (token.length() > 255) {
1009 // string too long. Cut off.
1010 token.erase(0, token.length() - 251);
1015 // FIXME UNICODE: We assume that the file names in the log
1016 // file are in the file system encoding.
1017 token = to_utf8(from_filesystem8bit(token));
1019 // (1) "File: file.ext"
1020 if (regex_match(token, sub, reg1)) {
1022 found_file = checkLineBreak(sub.str(1), head);
1024 if (suffixIs(token, ")"))
1025 // no line break for sure
1026 // pretend we've been successfully searching
1028 // (2) "No file file.ext"
1029 } else if (regex_match(token, sub, reg2)) {
1030 // file names must contains a dot, line ends with dot
1031 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1032 found_file = handleFoundFile(sub.str(1), head);
1034 // we suspect a line break
1036 // (3) "\openout<nr> = `file.ext'."
1037 } else if (regex_match(token, sub, reg3)) {
1038 // search for closing '. at the end of the line
1039 if (sub.str(2) == "\'.")
1040 found_file = handleFoundFile(sub.str(1), head);
1042 // probable line break
1044 // (4) "Writing index file file.ext"
1045 } else if (regex_match(token, sub, reg4))
1047 found_file = checkLineBreak(sub.str(1), head);
1049 else if (regex_match(token, sub, reg5)) {
1050 // search for closing '>' and dot ('*.*>') at the eol
1051 if (contains(sub.str(1), '.') && sub.str(2) == ">")
1052 found_file = handleFoundFile(sub.str(1), head);
1054 // probable line break
1056 // (6) "Writing nomenclature file file.ext"
1057 } else if (regex_match(token, sub, regnomencl) ||
1058 regex_match(token, sub, regoldnomencl))
1060 found_file = checkLineBreak(sub.str(1), head);
1061 // (7) "\tf@toc=\write<nr>" (for MikTeX)
1062 else if (regex_match(token, sub, miktexTocReg))
1063 found_file = handleFoundFile(onlyFileName(changeExtension(
1064 file.absFileName(), ".toc")), head);
1066 // not found, but we won't check further
1067 // pretend we've been successfully searching
1071 // note that we can have several of these on one line
1072 // this must be queried separated, because of
1073 // cases such as "File: file.ext (type eps)"
1074 // where "File: file.ext" would be skipped
1075 if (regex_match(token, sub, reg6)) {
1076 // search for strings in (...)
1077 static regex reg6_1("\\(([^()]+)(.)");
1079 string::const_iterator first = token.begin();
1080 string::const_iterator end = token.end();
1082 while (regex_search(first, end, what, reg6_1)) {
1083 // if we have a dot, try to handle as file
1084 if (contains(what.str(1), '.')) {
1085 first = what[0].second;
1086 if (what.str(2) == ")") {
1087 handleFoundFile(what.str(1), head);
1088 // since we had a closing bracket,
1089 // do not investigate further
1092 // if we have no closing bracket,
1093 // try to handle as file nevertheless
1094 found_file = handleFoundFile(
1095 what.str(1) + what.str(2), head);
1097 // if we do not have a dot, check if the line has
1098 // a closing bracket (else, we suspect a line break)
1099 else if (what.str(2) != ")") {
1100 first = what[0].second;
1103 // we have a closing bracket, so the content
1104 // is not a file name.
1105 // no need to investigate further
1106 // pretend we've been successfully searching
1107 first = what[0].second;
1114 // probable linebreak:
1118 // no linebreak: reset
1119 lastline = string();
1122 // Make sure that the main .tex file is in the dependency file.
1123 head.insert(file, true);