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 // - we should perhaps also scan the bibtex log file
57 docstring runMessage(unsigned int count)
59 return bformat(_("Waiting for LaTeX run number %1$d"), count);
68 void TeXErrors::insertError(int line, docstring const & error_desc,
69 docstring const & error_text)
71 Error newerr(line, error_desc, error_text);
72 errors.push_back(newerr);
76 bool operator==(AuxInfo const & a, AuxInfo const & o)
78 return a.aux_file == o.aux_file
79 && a.citations == o.citations
80 && a.databases == o.databases
81 && a.styles == o.styles;
85 bool operator!=(AuxInfo const & a, AuxInfo const & o)
95 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
97 : cmd(latex), file(f), runparams(rp)
100 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
101 depfile = FileName(file.absFileName() + ".dep-pdf");
103 FileName(changeExtension(file.absFileName(), ".pdf"));
105 depfile = FileName(file.absFileName() + ".dep");
107 FileName(changeExtension(file.absFileName(), ".dvi"));
112 void LaTeX::deleteFilesOnError() const
114 // currently just a dummy function.
116 // What files do we have to delete?
118 // This will at least make latex do all the runs
119 depfile.removeFile();
121 // but the reason for the error might be in a generated file...
124 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
128 FileName const ind(changeExtension(file.absFileName(), ".ind"));
132 FileName const nls(changeExtension(file.absFileName(), ".nls"));
135 // nomencl file (old version of the package)
136 FileName const gls(changeExtension(file.absFileName(), ".gls"));
139 // Also remove the aux file
140 FileName const aux(changeExtension(file.absFileName(), ".aux"));
145 int LaTeX::run(TeXErrors & terr)
146 // We know that this function will only be run if the lyx buffer
147 // has been changed. We also know that a newly written .tex file
148 // is always different from the previous one because of the date
149 // in it. However it seems safe to run latex (at least) one time
150 // each time the .tex file changes.
152 int scanres = NO_ERRORS;
153 unsigned int count = 0; // number of times run
154 num_errors = 0; // just to make sure.
155 unsigned int const MAX_RUN = 6;
156 DepTable head; // empty head
157 bool rerun = false; // rerun requested
159 // The class LaTeX does not know the temp path.
160 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
163 // Never write the depfile if an error was encountered.
166 // first check if the file dependencies exist:
167 // ->If it does exist
168 // check if any of the files mentioned in it have
169 // changed (done using a checksum).
171 // run latex once and
172 // remake the dependency file
173 // -> if not changed:
174 // just return there is nothing to do for us.
175 // ->if it doesn't exist
177 // run latex once (we need to run latex once anyway) and
178 // remake the dependency file.
181 bool had_depfile = depfile.exists();
182 bool run_bibtex = false;
183 FileName const aux_file(changeExtension(file.absFileName(), "aux"));
186 LYXERR(Debug::DEPEND, "Dependency file exists");
187 // Read the dep file:
188 had_depfile = head.read(depfile);
192 // Update the checksums
194 // Can't just check if anything has changed because it might
195 // have aborted on error last time... in which cas we need
196 // to re-run latex and collect the error messages
197 // (even if they are the same).
198 if (!output_file.exists()) {
199 LYXERR(Debug::DEPEND,
200 "re-running LaTeX because output file doesn't exist.");
201 } else if (!head.sumchange()) {
202 LYXERR(Debug::DEPEND, "return no_change");
205 LYXERR(Debug::DEPEND, "Dependency file has changed");
208 if (head.extchanged(".bib") || head.extchanged(".bst"))
211 LYXERR(Debug::DEPEND,
212 "Dependency file does not exist, or has wrong format");
214 /// We scan the aux file even when had_depfile = false,
215 /// because we can run pdflatex on the file after running latex on it,
216 /// in which case we will not need to run bibtex again.
217 vector<AuxInfo> bibtex_info_old;
219 bibtex_info_old = scanAuxFiles(aux_file);
222 LYXERR(Debug::LATEX, "Run #" << count);
223 message(runMessage(count));
226 scanres = scanLogFile(terr);
227 if (scanres & ERROR_RERUN) {
228 LYXERR(Debug::LATEX, "Rerunning LaTeX");
230 scanres = scanLogFile(terr);
233 if (scanres & ERRORS) {
234 deleteFilesOnError();
235 return scanres; // return on error
238 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
239 if (!run_bibtex && bibtex_info_old != bibtex_info)
242 // update the dependencies.
243 deplog(head); // reads the latex log
247 // At this point we must run external programs if needed.
248 // makeindex will be run if a .idx file changed or was generated.
249 // And if there were undefined citations or changes in references
250 // the .aux file is checked for signs of bibtex. Bibtex is then run
253 // memoir (at least) writes an empty *idx file in the first place.
254 // A second latex run is needed.
255 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
256 rerun = idxfile.exists() && idxfile.isFileEmpty();
259 if (head.haschanged(idxfile)) {
261 LYXERR(Debug::LATEX, "Running MakeIndex.");
262 message(_("Running Index Processor."));
263 // onlyFileName() is needed for cygwin
264 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
267 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
268 if (head.haschanged(nlofile))
269 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
270 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
271 if (head.haschanged(glofile))
272 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
275 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
276 if (scanres & UNDEF_CIT || run_bibtex) {
277 // Here we must scan the .aux file and look for
278 // "\bibdata" and/or "\bibstyle". If one of those
279 // tags is found -> run bibtex and set rerun = true;
281 LYXERR(Debug::LATEX, "Running BibTeX.");
282 message(_("Running BibTeX."));
283 updateBibtexDependencies(head, bibtex_info);
284 rerun |= runBibTeX(bibtex_info, runparams);
285 } else if (!had_depfile) {
286 /// If we run pdflatex on the file after running latex on it,
287 /// then we do not need to run bibtex, but we do need to
288 /// insert the .bib and .bst files into the .dep-pdf file.
289 updateBibtexDependencies(head, bibtex_info);
293 // we know on this point that latex has been run once (or we just
294 // returned) and the question now is to decide if we need to run
295 // it any more. This is done by asking if any of the files in the
296 // dependency file has changed. (remember that the checksum for
297 // a given file is reported to have changed if it just was created)
298 // -> if changed or rerun == true:
299 // run latex once more and
300 // update the dependency structure
301 // -> if not changed:
302 // we do nothing at this point
304 if (rerun || head.sumchange()) {
307 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
308 LYXERR(Debug::LATEX, "Run #" << count);
309 message(runMessage(count));
311 scanres = scanLogFile(terr);
312 if (scanres & ERRORS) {
313 deleteFilesOnError();
314 return scanres; // return on error
317 // update the depedencies
318 deplog(head); // reads the latex log
321 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
326 // Complex bibliography packages such as Biblatex require
327 // an additional bibtex cycle sometimes.
328 if (scanres & UNDEF_CIT) {
329 // Here we must scan the .aux file and look for
330 // "\bibdata" and/or "\bibstyle". If one of those
331 // tags is found -> run bibtex and set rerun = true;
333 LYXERR(Debug::LATEX, "Running BibTeX.");
334 message(_("Running BibTeX."));
335 updateBibtexDependencies(head, bibtex_info);
336 rerun |= runBibTeX(bibtex_info, runparams);
340 // The inclusion of files generated by external programs such as
341 // makeindex or bibtex might have done changes to pagenumbering,
342 // etc. And because of this we must run the external programs
343 // again to make sure everything is redone correctly.
344 // Also there should be no need to run the external programs any
347 // run makeindex if the <file>.idx has changed or was generated.
348 if (head.haschanged(idxfile)) {
350 LYXERR(Debug::LATEX, "Running MakeIndex.");
351 message(_("Running Index Processor."));
352 // onlyFileName() is needed for cygwin
353 rerun = runMakeIndex(onlyFileName(changeExtension(
354 file.absFileName(), ".idx")), runparams);
357 // I am not pretty sure if need this twice.
358 if (head.haschanged(nlofile))
359 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
360 if (head.haschanged(glofile))
361 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
364 // we will only run latex more if the log file asks for it.
365 // or if the sumchange() is true.
366 // -> rerun asked for:
368 // remake the dependency file
369 // goto 2 or return if max runs are reached.
370 // -> rerun not asked for:
371 // just return (fall out of bottom of func)
373 while ((head.sumchange() || rerun || (scanres & RERUN))
374 && count < MAX_RUN) {
375 // Yes rerun until message goes away, or until
376 // MAX_RUNS are reached.
379 LYXERR(Debug::LATEX, "Run #" << count);
380 message(runMessage(count));
382 scanres = scanLogFile(terr);
383 if (scanres & ERRORS) {
384 deleteFilesOnError();
385 return scanres; // return on error
392 // Write the dependencies to file.
394 LYXERR(Debug::LATEX, "Done.");
399 int LaTeX::startscript()
401 // onlyFileName() is needed for cygwin
402 string tmp = cmd + ' '
403 + quoteName(onlyFileName(file.toFilesystemEncoding()))
404 + " > " + os::nulldev();
406 return one.startscript(Systemcall::Wait, tmp);
410 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
411 string const & params)
413 string tmp = runparams.use_japanese ?
414 lyxrc.jindex_command : lyxrc.index_command;
416 if (!runparams.index_command.empty())
417 tmp = runparams.index_command;
420 "idx file has been made, running index processor ("
421 << tmp << ") on file " << f);
423 tmp = subst(tmp, "$$lang", runparams.document_language);
424 if (runparams.use_indices) {
425 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
427 "Multiple indices. Using splitindex command: " << tmp);
433 one.startscript(Systemcall::Wait, tmp);
438 bool LaTeX::runMakeIndexNomencl(FileName const & file,
439 string const & nlo, string const & nls)
441 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
442 message(_("Running MakeIndex for nomencl."));
443 string tmp = lyxrc.nomencl_command + ' ';
444 // onlyFileName() is needed for cygwin
445 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
447 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
449 one.startscript(Systemcall::Wait, tmp);
454 vector<AuxInfo> const
455 LaTeX::scanAuxFiles(FileName const & file)
457 vector<AuxInfo> result;
459 result.push_back(scanAuxFile(file));
461 string const basename = removeExtension(file.absFileName());
462 for (int i = 1; i < 1000; ++i) {
463 FileName const file2(basename
464 + '.' + convert<string>(i)
468 result.push_back(scanAuxFile(file2));
474 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
477 result.aux_file = file;
478 scanAuxFile(file, result);
483 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
485 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
487 ifstream ifs(file.toFilesystemEncoding().c_str());
489 static regex const reg1("\\\\citation\\{([^}]+)\\}");
490 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
491 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
492 static regex const reg4("\\\\@input\\{([^}]+)\\}");
494 while (getline(ifs, token)) {
495 token = rtrim(token, "\r");
497 // FIXME UNICODE: We assume that citation keys and filenames
498 // in the aux file are in the file system encoding.
499 token = to_utf8(from_filesystem8bit(token));
500 if (regex_match(token, sub, reg1)) {
501 string data = sub.str(1);
502 while (!data.empty()) {
504 data = split(data, citation, ',');
505 LYXERR(Debug::LATEX, "Citation: " << citation);
506 aux_info.citations.insert(citation);
508 } else if (regex_match(token, sub, reg2)) {
509 string data = sub.str(1);
510 // data is now all the bib files separated by ','
511 // get them one by one and pass them to the helper
512 while (!data.empty()) {
514 data = split(data, database, ',');
515 database = changeExtension(database, "bib");
516 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
517 aux_info.databases.insert(database);
519 } else if (regex_match(token, sub, reg3)) {
520 string style = sub.str(1);
521 // token is now the style file
522 // pass it to the helper
523 style = changeExtension(style, "bst");
524 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
525 aux_info.styles.insert(style);
526 } else if (regex_match(token, sub, reg4)) {
527 string const file2 = sub.str(1);
528 scanAuxFile(makeAbsPath(file2), aux_info);
534 void LaTeX::updateBibtexDependencies(DepTable & dep,
535 vector<AuxInfo> const & bibtex_info)
537 // Since a run of Bibtex mandates more latex runs it is ok to
538 // remove all ".bib" and ".bst" files.
539 dep.remove_files_with_extension(".bib");
540 dep.remove_files_with_extension(".bst");
541 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
543 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
544 it != bibtex_info.end(); ++it) {
545 for (set<string>::const_iterator it2 = it->databases.begin();
546 it2 != it->databases.end(); ++it2) {
547 FileName const file = findtexfile(*it2, "bib");
549 dep.insert(file, true);
552 for (set<string>::const_iterator it2 = it->styles.begin();
553 it2 != it->styles.end(); ++it2) {
554 FileName const file = findtexfile(*it2, "bst");
556 dep.insert(file, true);
562 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
563 OutputParams const & runparams)
566 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
567 it != bibtex_info.end(); ++it) {
568 if (it->databases.empty())
572 string tmp = runparams.use_japanese ?
573 lyxrc.jbibtex_command : lyxrc.bibtex_command;
575 if (!runparams.bibtex_command.empty())
576 tmp = runparams.bibtex_command;
578 // onlyFileName() is needed for cygwin
579 tmp += quoteName(onlyFileName(removeExtension(
580 it->aux_file.absFileName())));
582 one.startscript(Systemcall::Wait, tmp);
584 // Return whether bibtex was run
589 int LaTeX::scanLogFile(TeXErrors & terr)
593 int retval = NO_ERRORS;
595 onlyFileName(changeExtension(file.absFileName(), ".log"));
596 LYXERR(Debug::LATEX, "Log file: " << tmp);
597 FileName const fn = FileName(makeAbsPath(tmp));
598 ifstream ifs(fn.toFilesystemEncoding().c_str());
599 bool fle_style = false;
600 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
601 // Flag for 'File ended while scanning' message.
602 // We need to wait for subsequent processing.
603 string wait_for_error;
606 while (getline(ifs, token)) {
607 // MikTeX sometimes inserts \0 in the log file. They can't be
608 // removed directly with the existing string utility
609 // functions, so convert them first to \r, and remove all
610 // \r's afterwards, since we need to remove them anyway.
611 token = subst(token, '\0', '\r');
612 token = subst(token, "\r", "");
615 LYXERR(Debug::LATEX, "Log line: " << token);
620 if (contains(token, "file:line:error style messages enabled"))
623 if (prefixIs(token, "LaTeX Warning:") ||
624 prefixIs(token, "! pdfTeX warning")) {
625 // Here shall we handle different
627 retval |= LATEX_WARNING;
628 LYXERR(Debug::LATEX, "LaTeX Warning.");
629 if (contains(token, "Rerun to get cross-references")) {
631 LYXERR(Debug::LATEX, "We should rerun.");
632 // package clefval needs 2 latex runs before bibtex
633 } else if (contains(token, "Value of")
634 && contains(token, "on page")
635 && contains(token, "undefined")) {
636 retval |= ERROR_RERUN;
637 LYXERR(Debug::LATEX, "Force rerun.");
638 } else if (contains(token, "Citation")
639 && contains(token, "on page")
640 && contains(token, "undefined")) {
643 } else if (prefixIs(token, "Package")) {
645 retval |= PACKAGE_WARNING;
646 if (contains(token, "natbib Warning:")) {
648 if (contains(token, "Citation")
649 && contains(token, "on page")
650 && contains(token, "undefined")) {
653 } else if (contains(token, "run BibTeX")) {
655 } else if (contains(token, "Rerun LaTeX") ||
656 contains(token, "Rerun to get")) {
657 // at least longtable.sty and bibtopic.sty
659 LYXERR(Debug::LATEX, "We should rerun.");
662 } else if (prefixIs(token, "LETTRE WARNING:")) {
663 if (contains(token, "veuillez recompiler")) {
665 LYXERR(Debug::LATEX, "We should rerun.");
668 } else if (token[0] == '(') {
669 if (contains(token, "Rerun LaTeX") ||
670 contains(token, "Rerun to get")) {
672 LYXERR(Debug::LATEX, "We should rerun.");
675 } else if (prefixIs(token, "! ")
677 && regex_match(token, sub, file_line_error)
678 && !contains(token, "pdfTeX warning"))) {
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;
691 // bug 6445. At this point its not clear we finish with error.
692 if (prefixIs(token, "! File ended while scanning")){
693 wait_for_error = desc;
696 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
697 retval |= LATEX_ERROR;
700 errstr = wait_for_error;
702 if (!getline(ifs, tmp))
704 errstr += "\n" + tmp;
707 } while (!contains(tmp, "(job aborted"));
710 from_local8bit("Emergency stop"),
711 from_local8bit(errstr));
718 if (!getline(ifs, tmp))
722 } while (!prefixIs(tmp, "l."));
723 if (prefixIs(tmp, "l.")) {
724 // we have a latex error
727 "Package babel Error: You haven't defined the language") ||
729 "Package babel Error: You haven't loaded the option"))
730 retval |= ERROR_RERUN;
731 // get the line number:
733 sscanf(tmp.c_str(), "l.%d", &line);
734 // get the rest of the message:
735 string errstr(tmp, tmp.find(' '));
738 while (!contains(errstr, "l.")
740 && !prefixIs(tmp, "! ")
741 && !contains(tmp, "(job aborted")) {
746 LYXERR(Debug::LATEX, "line: " << line << '\n'
747 << "Desc: " << desc << '\n' << "Text: " << errstr);
748 if (line == last_line)
754 if (line_count <= 5) {
756 // We have no idea what the encoding of
758 // It seems that the output from the
759 // latex compiler itself is pure ASCII,
760 // but it can include bits from the
761 // document, so whatever encoding we
762 // assume here it can be wrong.
763 terr.insertError(line,
764 from_local8bit(desc),
765 from_local8bit(errstr));
770 // information messages, TeX warnings and other
771 // warnings we have not caught earlier.
772 if (prefixIs(token, "Overfull ")) {
773 retval |= TEX_WARNING;
774 } else if (prefixIs(token, "Underfull ")) {
775 retval |= TEX_WARNING;
776 } else if (contains(token, "Rerun to get citations")) {
777 // Natbib seems to use this.
779 } else if (contains(token, "No pages of output")) {
780 // A dvi file was not created
782 } else if (contains(token, "That makes 100 errors")) {
783 // More than 100 errors were reprted
784 retval |= TOO_MANY_ERRORS;
785 } else if (prefixIs(token, "!pdfTeX error:")){
786 // otherwise we dont catch e.g.:
787 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
790 from_local8bit("pdfTeX Error"),
791 from_local8bit(token));
795 LYXERR(Debug::LATEX, "Log line: " << token);
802 bool insertIfExists(FileName const & absname, DepTable & head)
804 if (absname.exists() && !absname.isDirectory()) {
805 head.insert(absname, true);
812 bool handleFoundFile(string const & ff, DepTable & head)
814 // convert from native os path to unix path
815 string foundfile = os::internal_path(trim(ff));
817 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
819 // Ok now we found a file.
820 // Now we should make sure that this is a file that we can
821 // access through the normal paths.
822 // We will not try any fancy search methods to
825 // (1) foundfile is an
826 // absolute path and should
829 if (FileName::isAbsolute(foundfile)) {
830 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
831 // On initial insert we want to do the update at once
832 // since this file cannot be a file generated by
834 absname.set(foundfile);
835 if (!insertIfExists(absname, head)) {
837 string strippedfile = foundfile;
838 while (contains(strippedfile, " ")) {
839 // files with spaces are often enclosed in quotation
840 // marks; those have to be removed
841 string unquoted = subst(strippedfile, "\"", "");
842 absname.set(unquoted);
843 if (insertIfExists(absname, head))
845 // strip off part after last space and try again
846 string tmp = strippedfile;
847 string const stripoff =
848 rsplit(tmp, strippedfile, ' ');
849 absname.set(strippedfile);
850 if (insertIfExists(absname, head))
856 string onlyfile = onlyFileName(foundfile);
857 absname = makeAbsPath(onlyfile);
860 while (contains(foundfile, ' ')) {
861 if (absname.exists())
865 // files with spaces are often enclosed in quotation
866 // marks; those have to be removed
867 string unquoted = subst(foundfile, "\"", "");
868 absname = makeAbsPath(unquoted);
869 if (absname.exists())
871 // strip off part after last space and try again
873 string const stripoff =
874 rsplit(foundfile, strippedfile, ' ');
875 foundfile = strippedfile;
876 onlyfile = onlyFileName(strippedfile);
877 absname = makeAbsPath(onlyfile);
881 // (2) foundfile is in the tmpdir
882 // insert it into head
883 if (absname.exists() && !absname.isDirectory()) {
884 // FIXME: This regex contained glo, but glo is used by the old
885 // version of nomencl.sty. Do we need to put it back?
886 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
887 if (regex_match(onlyfile, unwanted)) {
888 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
889 << " in the dep file");
890 } else if (suffixIs(onlyfile, ".tex")) {
891 // This is a tex file generated by LyX
892 // and latex is not likely to change this
894 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
895 head.insert(absname, true);
897 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
898 head.insert(absname);
902 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
908 bool checkLineBreak(string const & ff, DepTable & head)
910 if (!contains(ff, '.'))
913 // if we have a dot, we let handleFoundFile decide
914 return handleFoundFile(ff, head);
920 void LaTeX::deplog(DepTable & head)
922 // This function reads the LaTeX log file end extracts all the
923 // external files used by the LaTeX run. The files are then
924 // entered into the dependency file.
926 string const logfile =
927 onlyFileName(changeExtension(file.absFileName(), ".log"));
929 static regex const reg1("File: (.+).*");
930 static regex const reg2("No file (.+)(.).*");
931 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
932 // If an index should be created, MikTex does not write a line like
933 // \openout# = 'sample.idx'.
934 // but instead only a line like this into the log:
935 // Writing index file sample.idx
936 static regex const reg4("Writing index file (.+).*");
937 // files also can be enclosed in <...>
938 static regex const reg5("<([^>]+)(.).*");
939 static regex const regoldnomencl("Writing glossary file (.+).*");
940 static regex const regnomencl("Writing nomenclature file (.+).*");
941 // If a toc should be created, MikTex does not write a line like
942 // \openout# = `sample.toc'.
943 // but only a line like this into the log:
945 // This line is also written by tetex.
946 // This line is not present if no toc should be created.
947 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
948 static regex const reg6(".*\\([^)]+.*");
950 FileName const fn = makeAbsPath(logfile);
951 ifstream ifs(fn.toFilesystemEncoding().c_str());
954 // Ok, the scanning of files here is not sufficient.
955 // Sometimes files are named by "File: xxx" only
956 // So I think we should use some regexps to find files instead.
957 // Note: all file names and paths might contains spaces.
958 bool found_file = false;
961 // MikTeX sometimes inserts \0 in the log file. They can't be
962 // removed directly with the existing string utility
963 // functions, so convert them first to \r, and remove all
964 // \r's afterwards, since we need to remove them anyway.
965 token = subst(token, '\0', '\r');
966 token = subst(token, "\r", "");
967 if (token.empty() || token == ")") {
972 // Sometimes, filenames are broken across lines.
973 // We care for that and save suspicious lines.
974 // Here we exclude some cases where we are sure
975 // that there is no continued filename
976 if (!lastline.empty()) {
977 static regex const package_info("Package \\w+ Info: .*");
978 static regex const package_warning("Package \\w+ Warning: .*");
979 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
980 || prefixIs(token, "Package:")
981 || prefixIs(token, "Language:")
982 || prefixIs(token, "LaTeX Info:")
983 || prefixIs(token, "LaTeX Font Info:")
984 || prefixIs(token, "\\openout[")
985 || prefixIs(token, "))")
986 || regex_match(token, package_info)
987 || regex_match(token, package_warning))
991 if (!lastline.empty())
992 // probably a continued filename from last line
993 token = lastline + token;
994 if (token.length() > 255) {
995 // string too long. Cut off.
996 token.erase(0, token.length() - 251);
1001 // FIXME UNICODE: We assume that the file names in the log
1002 // file are in the file system encoding.
1003 token = to_utf8(from_filesystem8bit(token));
1005 // (1) "File: file.ext"
1006 if (regex_match(token, sub, reg1)) {
1008 found_file = checkLineBreak(sub.str(1), head);
1010 if (suffixIs(token, ")"))
1011 // no line break for sure
1012 // pretend we've been succesfully searching
1014 // (2) "No file file.ext"
1015 } else if (regex_match(token, sub, reg2)) {
1016 // file names must contains a dot, line ends with dot
1017 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1018 found_file = handleFoundFile(sub.str(1), head);
1020 // we suspect a line break
1022 // (3) "\openout<nr> = `file.ext'."
1023 } else if (regex_match(token, sub, reg3)) {
1024 // search for closing '. at the end of the line
1025 if (sub.str(2) == "\'.")
1026 found_file = handleFoundFile(sub.str(1), head);
1028 // probable line break
1030 // (4) "Writing index file file.ext"
1031 } else if (regex_match(token, sub, reg4))
1033 found_file = checkLineBreak(sub.str(1), head);
1035 else if (regex_match(token, sub, reg5)) {
1036 // search for closing '>' and dot ('*.*>') at the eol
1037 if (contains(sub.str(1), '.') && sub.str(2) == ">")
1038 found_file = handleFoundFile(sub.str(1), head);
1040 // probable line break
1042 // (6) "Writing nomenclature file file.ext"
1043 } else if (regex_match(token, sub, regnomencl) ||
1044 regex_match(token, sub, regoldnomencl))
1046 found_file = checkLineBreak(sub.str(1), head);
1047 // (7) "\tf@toc=\write<nr>" (for MikTeX)
1048 else if (regex_match(token, sub, miktexTocReg))
1049 found_file = handleFoundFile(onlyFileName(changeExtension(
1050 file.absFileName(), ".toc")), head);
1052 // not found, but we won't check further
1053 // pretend we've been succesfully searching
1057 // note that we can have several of these on one line
1058 // this must be queried separated, because of
1059 // cases such as "File: file.ext (type eps)"
1060 // where "File: file.ext" would be skipped
1061 if (regex_match(token, sub, reg6)) {
1062 // search for strings in (...)
1063 static regex reg6_1("\\(([^()]+)(.)");
1065 string::const_iterator first = token.begin();
1066 string::const_iterator end = token.end();
1068 while (regex_search(first, end, what, reg6_1)) {
1069 // if we have a dot, try to handle as file
1070 if (contains(what.str(1), '.')) {
1071 first = what[0].second;
1072 if (what.str(2) == ")") {
1073 handleFoundFile(what.str(1), head);
1074 // since we had a closing bracket,
1075 // do not investigate further
1078 // if we have no closing bracket,
1079 // try to handle as file nevertheless
1080 found_file = handleFoundFile(
1081 what.str(1) + what.str(2), head);
1083 // if we do not have a dot, check if the line has
1084 // a closing bracket (else, we suspect a line break)
1085 else if (what.str(2) != ")") {
1086 first = what[0].second;
1089 // we have a closing bracket, so the content
1090 // is not a file name.
1091 // no need to investigate further
1092 // pretend we've been succesfully searching
1093 first = what[0].second;
1100 // probable linebreak:
1104 // no linebreak: reset
1105 lastline = string();
1108 // Make sure that the main .tex file is in the dependency file.
1109 head.insert(file, true);