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"))
213 LYXERR(Debug::DEPEND,
214 "Dependency file does not exist, or has wrong format");
216 /// We scan the aux file even when had_depfile = false,
217 /// because we can run pdflatex on the file after running latex on it,
218 /// in which case we will not need to run bibtex again.
219 vector<AuxInfo> bibtex_info_old;
221 bibtex_info_old = scanAuxFiles(aux_file);
224 LYXERR(Debug::LATEX, "Run #" << count);
225 message(runMessage(count));
228 scanres = scanLogFile(terr);
229 if (scanres & ERROR_RERUN) {
230 LYXERR(Debug::LATEX, "Rerunning LaTeX");
232 scanres = scanLogFile(terr);
235 if (scanres & ERRORS) {
236 deleteFilesOnError();
237 return scanres; // return on error
240 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
241 if (!run_bibtex && bibtex_info_old != bibtex_info)
244 // update the dependencies.
245 deplog(head); // reads the latex log
249 // At this point we must run external programs if needed.
250 // makeindex will be run if a .idx file changed or was generated.
251 // And if there were undefined citations or changes in references
252 // the .aux file is checked for signs of bibtex. Bibtex is then run
255 // memoir (at least) writes an empty *idx file in the first place.
256 // A second latex run is needed.
257 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
258 rerun = idxfile.exists() && idxfile.isFileEmpty();
261 if (head.haschanged(idxfile)) {
263 LYXERR(Debug::LATEX, "Running MakeIndex.");
264 message(_("Running Index Processor."));
265 // onlyFileName() is needed for cygwin
266 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
269 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
270 if (head.haschanged(nlofile))
271 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
272 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
273 if (head.haschanged(glofile))
274 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
276 // check if we're using biber instead of bibtex
277 // biber writes no info to the aux file, so we just check
278 // if a bcf file exists (and if it was updated)
279 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
280 bool const biber = head.exist(bcffile);
283 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
284 if (scanres & UNDEF_CIT || run_bibtex) {
285 // Here we must scan the .aux file and look for
286 // "\bibdata" and/or "\bibstyle". If one of those
287 // tags is found -> run bibtex and set rerun = true;
289 LYXERR(Debug::LATEX, "Running BibTeX.");
290 message(_("Running BibTeX."));
291 updateBibtexDependencies(head, bibtex_info, biber);
292 rerun |= runBibTeX(bibtex_info, runparams, biber);
294 // since biber writes no info to the aux file, we have
295 // to parse the blg file (which only exists after biber
297 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
298 if (blgfile.exists())
301 } else if (!had_depfile) {
302 /// If we run pdflatex on the file after running latex on it,
303 /// then we do not need to run bibtex, but we do need to
304 /// insert the .bib and .bst files into the .dep-pdf file.
305 updateBibtexDependencies(head, bibtex_info, biber);
309 // we know on this point that latex has been run once (or we just
310 // returned) and the question now is to decide if we need to run
311 // it any more. This is done by asking if any of the files in the
312 // dependency file has changed. (remember that the checksum for
313 // a given file is reported to have changed if it just was created)
314 // -> if changed or rerun == true:
315 // run latex once more and
316 // update the dependency structure
317 // -> if not changed:
318 // we do nothing at this point
320 if (rerun || head.sumchange()) {
323 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
324 LYXERR(Debug::LATEX, "Run #" << count);
325 message(runMessage(count));
327 scanres = scanLogFile(terr);
328 if (scanres & ERRORS) {
329 deleteFilesOnError();
330 return scanres; // return on error
333 // update the depedencies
334 deplog(head); // reads the latex log
337 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
342 // Complex bibliography packages such as Biblatex require
343 // an additional bibtex cycle sometimes.
344 if (scanres & UNDEF_CIT) {
345 // Here we must scan the .aux file and look for
346 // "\bibdata" and/or "\bibstyle". If one of those
347 // tags is found -> run bibtex and set rerun = true;
349 LYXERR(Debug::LATEX, "Running BibTeX.");
350 message(_("Running BibTeX."));
351 updateBibtexDependencies(head, bibtex_info, biber);
352 rerun |= runBibTeX(bibtex_info, runparams, biber);
356 // The inclusion of files generated by external programs such as
357 // makeindex or bibtex might have done changes to pagenumbering,
358 // etc. And because of this we must run the external programs
359 // again to make sure everything is redone correctly.
360 // Also there should be no need to run the external programs any
363 // run makeindex if the <file>.idx has changed or was generated.
364 if (head.haschanged(idxfile)) {
366 LYXERR(Debug::LATEX, "Running MakeIndex.");
367 message(_("Running Index Processor."));
368 // onlyFileName() is needed for cygwin
369 rerun = runMakeIndex(onlyFileName(changeExtension(
370 file.absFileName(), ".idx")), runparams);
373 // I am not pretty sure if need this twice.
374 if (head.haschanged(nlofile))
375 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
376 if (head.haschanged(glofile))
377 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
380 // we will only run latex more if the log file asks for it.
381 // or if the sumchange() is true.
382 // -> rerun asked for:
384 // remake the dependency file
385 // goto 2 or return if max runs are reached.
386 // -> rerun not asked for:
387 // just return (fall out of bottom of func)
389 while ((head.sumchange() || rerun || (scanres & RERUN))
390 && count < MAX_RUN) {
391 // Yes rerun until message goes away, or until
392 // MAX_RUNS are reached.
395 LYXERR(Debug::LATEX, "Run #" << count);
396 message(runMessage(count));
398 scanres = scanLogFile(terr);
399 if (scanres & ERRORS) {
400 deleteFilesOnError();
401 return scanres; // return on error
408 // Write the dependencies to file.
410 LYXERR(Debug::LATEX, "Done.");
415 int LaTeX::startscript()
417 // onlyFileName() is needed for cygwin
418 string tmp = cmd + ' '
419 + quoteName(onlyFileName(file.toFilesystemEncoding()))
420 + " > " + os::nulldev();
422 return one.startscript(Systemcall::Wait, tmp);
426 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
427 string const & params)
429 string tmp = runparams.use_japanese ?
430 lyxrc.jindex_command : lyxrc.index_command;
432 if (!runparams.index_command.empty())
433 tmp = runparams.index_command;
436 "idx file has been made, running index processor ("
437 << tmp << ") on file " << f);
439 tmp = subst(tmp, "$$lang", runparams.document_language);
440 if (runparams.use_indices) {
441 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
443 "Multiple indices. Using splitindex command: " << tmp);
449 one.startscript(Systemcall::Wait, tmp);
454 bool LaTeX::runMakeIndexNomencl(FileName const & file,
455 string const & nlo, string const & nls)
457 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
458 message(_("Running MakeIndex for nomencl."));
459 string tmp = lyxrc.nomencl_command + ' ';
460 // onlyFileName() is needed for cygwin
461 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
463 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
465 one.startscript(Systemcall::Wait, tmp);
470 vector<AuxInfo> const
471 LaTeX::scanAuxFiles(FileName const & file)
473 vector<AuxInfo> result;
475 result.push_back(scanAuxFile(file));
477 string const basename = removeExtension(file.absFileName());
478 for (int i = 1; i < 1000; ++i) {
479 FileName const file2(basename
480 + '.' + convert<string>(i)
484 result.push_back(scanAuxFile(file2));
490 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
493 result.aux_file = file;
494 scanAuxFile(file, result);
499 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
501 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
503 ifstream ifs(file.toFilesystemEncoding().c_str());
505 static regex const reg1("\\\\citation\\{([^}]+)\\}");
506 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
507 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
508 static regex const reg4("\\\\@input\\{([^}]+)\\}");
510 while (getline(ifs, token)) {
511 token = rtrim(token, "\r");
513 // FIXME UNICODE: We assume that citation keys and filenames
514 // in the aux file are in the file system encoding.
515 token = to_utf8(from_filesystem8bit(token));
516 if (regex_match(token, sub, reg1)) {
517 string data = sub.str(1);
518 while (!data.empty()) {
520 data = split(data, citation, ',');
521 LYXERR(Debug::LATEX, "Citation: " << citation);
522 aux_info.citations.insert(citation);
524 } else if (regex_match(token, sub, reg2)) {
525 string data = sub.str(1);
526 // data is now all the bib files separated by ','
527 // get them one by one and pass them to the helper
528 while (!data.empty()) {
530 data = split(data, database, ',');
531 database = changeExtension(database, "bib");
532 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
533 aux_info.databases.insert(database);
535 } else if (regex_match(token, sub, reg3)) {
536 string style = sub.str(1);
537 // token is now the style file
538 // pass it to the helper
539 style = changeExtension(style, "bst");
540 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
541 aux_info.styles.insert(style);
542 } else if (regex_match(token, sub, reg4)) {
543 string const file2 = sub.str(1);
544 scanAuxFile(makeAbsPath(file2), aux_info);
550 void LaTeX::updateBibtexDependencies(DepTable & dep,
551 vector<AuxInfo> const & bibtex_info,
554 // Since a run of Bibtex mandates more latex runs it is ok to
555 // remove all ".bib" and ".bst" files.
556 dep.remove_files_with_extension(".bib");
557 dep.remove_files_with_extension(".bst");
558 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
560 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
561 it != bibtex_info.end(); ++it) {
562 for (set<string>::const_iterator it2 = it->databases.begin();
563 it2 != it->databases.end(); ++it2) {
564 FileName const file = findtexfile(*it2, "bib");
566 dep.insert(file, true);
569 for (set<string>::const_iterator it2 = it->styles.begin();
570 it2 != it->styles.end(); ++it2) {
571 FileName const file = findtexfile(*it2, "bst");
573 dep.insert(file, true);
577 // biber writes nothing into the aux file.
578 // Instead, we have to scan the blg file
585 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
586 OutputParams const & runparams, bool biber)
589 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
590 it != bibtex_info.end(); ++it) {
591 if (!biber && it->databases.empty())
595 string tmp = runparams.use_japanese ?
596 lyxrc.jbibtex_command : lyxrc.bibtex_command;
598 if (!runparams.bibtex_command.empty())
599 tmp = runparams.bibtex_command;
601 // onlyFileName() is needed for cygwin
602 tmp += quoteName(onlyFileName(removeExtension(
603 it->aux_file.absFileName())));
605 one.startscript(Systemcall::Wait, tmp);
607 // Return whether bibtex was run
612 int LaTeX::scanLogFile(TeXErrors & terr)
616 int retval = NO_ERRORS;
618 onlyFileName(changeExtension(file.absFileName(), ".log"));
619 LYXERR(Debug::LATEX, "Log file: " << tmp);
620 FileName const fn = FileName(makeAbsPath(tmp));
621 ifstream ifs(fn.toFilesystemEncoding().c_str());
622 bool fle_style = false;
623 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
624 // Flag for 'File ended while scanning' message.
625 // We need to wait for subsequent processing.
626 string wait_for_error;
629 while (getline(ifs, token)) {
630 // MikTeX sometimes inserts \0 in the log file. They can't be
631 // removed directly with the existing string utility
632 // functions, so convert them first to \r, and remove all
633 // \r's afterwards, since we need to remove them anyway.
634 token = subst(token, '\0', '\r');
635 token = subst(token, "\r", "");
638 LYXERR(Debug::LATEX, "Log line: " << token);
643 if (contains(token, "file:line:error style messages enabled"))
646 if (prefixIs(token, "LaTeX Warning:") ||
647 prefixIs(token, "! pdfTeX warning")) {
648 // Here shall we handle different
650 retval |= LATEX_WARNING;
651 LYXERR(Debug::LATEX, "LaTeX Warning.");
652 if (contains(token, "Rerun to get cross-references")) {
654 LYXERR(Debug::LATEX, "We should rerun.");
655 // package clefval needs 2 latex runs before bibtex
656 } else if (contains(token, "Value of")
657 && contains(token, "on page")
658 && contains(token, "undefined")) {
659 retval |= ERROR_RERUN;
660 LYXERR(Debug::LATEX, "Force rerun.");
662 } else if (contains(token, "Etaremune labels have changed")) {
663 retval |= ERROR_RERUN;
664 LYXERR(Debug::LATEX, "Force rerun.");
665 } else if (contains(token, "Citation")
666 && contains(token, "on page")
667 && contains(token, "undefined")) {
670 } else if (prefixIs(token, "Package")) {
672 retval |= PACKAGE_WARNING;
673 if (contains(token, "natbib Warning:")) {
675 if (contains(token, "Citation")
676 && contains(token, "on page")
677 && contains(token, "undefined")) {
680 } else if (contains(token, "run BibTeX")) {
682 } else if (contains(token, "Rerun LaTeX") ||
683 contains(token, "Please rerun LaTeX") ||
684 contains(token, "Rerun to get")) {
685 // at least longtable.sty and bibtopic.sty
687 LYXERR(Debug::LATEX, "We should rerun.");
690 } else if (prefixIs(token, "LETTRE WARNING:")) {
691 if (contains(token, "veuillez recompiler")) {
693 LYXERR(Debug::LATEX, "We should rerun.");
696 } else if (token[0] == '(') {
697 if (contains(token, "Rerun LaTeX") ||
698 contains(token, "Rerun to get")) {
700 LYXERR(Debug::LATEX, "We should rerun.");
703 } else if (prefixIs(token, "! ")
705 && regex_match(token, sub, file_line_error)
706 && !contains(token, "pdfTeX warning"))) {
707 // Ok, we have something that looks like a TeX Error
708 // but what do we really have.
710 // Just get the error description:
712 if (prefixIs(token, "! "))
713 desc = string(token, 2);
716 if (contains(token, "LaTeX Error:"))
717 retval |= LATEX_ERROR;
719 // bug 6445. At this point its not clear we finish with error.
720 if (prefixIs(token, "! File ended while scanning")){
721 wait_for_error = desc;
724 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
725 retval |= LATEX_ERROR;
728 errstr = wait_for_error;
730 if (!getline(ifs, tmp))
732 errstr += "\n" + tmp;
735 } while (!contains(tmp, "(job aborted"));
738 from_local8bit("Emergency stop"),
739 from_local8bit(errstr));
746 if (!getline(ifs, tmp))
750 } while (!prefixIs(tmp, "l."));
751 if (prefixIs(tmp, "l.")) {
752 // we have a latex error
755 "Package babel Error: You haven't defined the language") ||
757 "Package babel Error: You haven't loaded the option"))
758 retval |= ERROR_RERUN;
759 // get the line number:
761 sscanf(tmp.c_str(), "l.%d", &line);
762 // get the rest of the message:
763 string errstr(tmp, tmp.find(' '));
766 while (!contains(errstr, "l.")
768 && !prefixIs(tmp, "! ")
769 && !contains(tmp, "(job aborted")) {
774 LYXERR(Debug::LATEX, "line: " << line << '\n'
775 << "Desc: " << desc << '\n' << "Text: " << errstr);
776 if (line == last_line)
782 if (line_count <= 5) {
784 // We have no idea what the encoding of
786 // It seems that the output from the
787 // latex compiler itself is pure ASCII,
788 // but it can include bits from the
789 // document, so whatever encoding we
790 // assume here it can be wrong.
791 terr.insertError(line,
792 from_local8bit(desc),
793 from_local8bit(errstr));
798 // information messages, TeX warnings and other
799 // warnings we have not caught earlier.
800 if (prefixIs(token, "Overfull ")) {
801 retval |= TEX_WARNING;
802 } else if (prefixIs(token, "Underfull ")) {
803 retval |= TEX_WARNING;
804 } else if (contains(token, "Rerun to get citations")) {
805 // Natbib seems to use this.
807 } else if (contains(token, "No pages of output")) {
808 // A dvi file was not created
810 } else if (contains(token, "That makes 100 errors")) {
811 // More than 100 errors were reprted
812 retval |= TOO_MANY_ERRORS;
813 } else if (prefixIs(token, "!pdfTeX error:")){
814 // otherwise we dont catch e.g.:
815 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
818 from_local8bit("pdfTeX Error"),
819 from_local8bit(token));
823 LYXERR(Debug::LATEX, "Log line: " << token);
830 bool insertIfExists(FileName const & absname, DepTable & head)
832 if (absname.exists() && !absname.isDirectory()) {
833 head.insert(absname, true);
840 bool handleFoundFile(string const & ff, DepTable & head)
842 // convert from native os path to unix path
843 string foundfile = os::internal_path(trim(ff));
845 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
847 // Ok now we found a file.
848 // Now we should make sure that this is a file that we can
849 // access through the normal paths.
850 // We will not try any fancy search methods to
853 // (1) foundfile is an
854 // absolute path and should
857 if (FileName::isAbsolute(foundfile)) {
858 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
859 // On initial insert we want to do the update at once
860 // since this file cannot be a file generated by
862 absname.set(foundfile);
863 if (!insertIfExists(absname, head)) {
865 string strippedfile = foundfile;
866 while (contains(strippedfile, " ")) {
867 // files with spaces are often enclosed in quotation
868 // marks; those have to be removed
869 string unquoted = subst(strippedfile, "\"", "");
870 absname.set(unquoted);
871 if (insertIfExists(absname, head))
873 // strip off part after last space and try again
874 string tmp = strippedfile;
875 string const stripoff =
876 rsplit(tmp, strippedfile, ' ');
877 absname.set(strippedfile);
878 if (insertIfExists(absname, head))
884 string onlyfile = onlyFileName(foundfile);
885 absname = makeAbsPath(onlyfile);
888 while (contains(foundfile, ' ')) {
889 if (absname.exists())
893 // files with spaces are often enclosed in quotation
894 // marks; those have to be removed
895 string unquoted = subst(foundfile, "\"", "");
896 absname = makeAbsPath(unquoted);
897 if (absname.exists())
899 // strip off part after last space and try again
901 string const stripoff =
902 rsplit(foundfile, strippedfile, ' ');
903 foundfile = strippedfile;
904 onlyfile = onlyFileName(strippedfile);
905 absname = makeAbsPath(onlyfile);
909 // (2) foundfile is in the tmpdir
910 // insert it into head
911 if (absname.exists() && !absname.isDirectory()) {
912 // FIXME: This regex contained glo, but glo is used by the old
913 // version of nomencl.sty. Do we need to put it back?
914 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
915 if (regex_match(onlyfile, unwanted)) {
916 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
917 << " in the dep file");
918 } else if (suffixIs(onlyfile, ".tex")) {
919 // This is a tex file generated by LyX
920 // and latex is not likely to change this
922 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
923 head.insert(absname, true);
925 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
926 head.insert(absname);
930 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
936 bool checkLineBreak(string const & ff, DepTable & head)
938 if (!contains(ff, '.'))
941 // if we have a dot, we let handleFoundFile decide
942 return handleFoundFile(ff, head);
948 void LaTeX::deplog(DepTable & head)
950 // This function reads the LaTeX log file end extracts all the
951 // external files used by the LaTeX run. The files are then
952 // entered into the dependency file.
954 string const logfile =
955 onlyFileName(changeExtension(file.absFileName(), ".log"));
957 static regex const reg1("File: (.+).*");
958 static regex const reg2("No file (.+)(.).*");
959 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
960 // If an index should be created, MikTex does not write a line like
961 // \openout# = 'sample.idx'.
962 // but instead only a line like this into the log:
963 // Writing index file sample.idx
964 static regex const reg4("Writing index file (.+).*");
965 // files also can be enclosed in <...>
966 static regex const reg5("<([^>]+)(.).*");
967 static regex const regoldnomencl("Writing glossary file (.+).*");
968 static regex const regnomencl("Writing nomenclature file (.+).*");
969 // If a toc should be created, MikTex does not write a line like
970 // \openout# = `sample.toc'.
971 // but only a line like this into the log:
973 // This line is also written by tetex.
974 // This line is not present if no toc should be created.
975 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
976 static regex const reg6(".*\\([^)]+.*");
978 FileName const fn = makeAbsPath(logfile);
979 ifstream ifs(fn.toFilesystemEncoding().c_str());
982 // Ok, the scanning of files here is not sufficient.
983 // Sometimes files are named by "File:� xxx" only
984 // So I think we should use some regexps to find files instead.
985 // Note: all file names and paths might contains spaces.
986 bool found_file = false;
989 // MikTeX sometimes inserts \0 in the log file. They can't be
990 // removed directly with the existing string utility
991 // functions, so convert them first to \r, and remove all
992 // \r's afterwards, since we need to remove them anyway.
993 token = subst(token, '\0', '\r');
994 token = subst(token, "\r", "");
995 if (token.empty() || token == ")") {
1000 // Sometimes, filenames are broken across lines.
1001 // We care for that and save suspicious lines.
1002 // Here we exclude some cases where we are sure
1003 // that there is no continued filename
1004 if (!lastline.empty()) {
1005 static regex const package_info("Package \\w+ Info: .*");
1006 static regex const package_warning("Package \\w+ Warning: .*");
1007 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1008 || prefixIs(token, "Package:")
1009 || prefixIs(token, "Language:")
1010 || prefixIs(token, "LaTeX Info:")
1011 || prefixIs(token, "LaTeX Font Info:")
1012 || prefixIs(token, "\\openout[")
1013 || prefixIs(token, "))")
1014 || regex_match(token, package_info)
1015 || regex_match(token, package_warning))
1016 lastline = string();
1019 if (!lastline.empty())
1020 // probably a continued filename from last line
1021 token = lastline + token;
1022 if (token.length() > 255) {
1023 // string too long. Cut off.
1024 token.erase(0, token.length() - 251);
1029 // FIXME UNICODE: We assume that the file names in the log
1030 // file are in the file system encoding.
1031 token = to_utf8(from_filesystem8bit(token));
1033 // (1) "File: file.ext"
1034 if (regex_match(token, sub, reg1)) {
1036 found_file = checkLineBreak(sub.str(1), head);
1038 if (suffixIs(token, ")"))
1039 // no line break for sure
1040 // pretend we've been successfully searching
1042 // (2) "No file file.ext"
1043 } else if (regex_match(token, sub, reg2)) {
1044 // file names must contains a dot, line ends with dot
1045 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1046 found_file = handleFoundFile(sub.str(1), head);
1048 // we suspect a line break
1050 // (3) "\openout<nr> = `file.ext'."
1051 } else if (regex_match(token, sub, reg3)) {
1052 // search for closing '. at the end of the line
1053 if (sub.str(2) == "\'.")
1054 found_file = handleFoundFile(sub.str(1), head);
1056 // probable line break
1058 // (4) "Writing index file file.ext"
1059 } else if (regex_match(token, sub, reg4))
1061 found_file = checkLineBreak(sub.str(1), head);
1063 else if (regex_match(token, sub, reg5)) {
1064 // search for closing '>' and dot ('*.*>') at the eol
1065 if (contains(sub.str(1), '.') && sub.str(2) == ">")
1066 found_file = handleFoundFile(sub.str(1), head);
1068 // probable line break
1070 // (6) "Writing nomenclature file file.ext"
1071 } else if (regex_match(token, sub, regnomencl) ||
1072 regex_match(token, sub, regoldnomencl))
1074 found_file = checkLineBreak(sub.str(1), head);
1075 // (7) "\tf@toc=\write<nr>" (for MikTeX)
1076 else if (regex_match(token, sub, miktexTocReg))
1077 found_file = handleFoundFile(onlyFileName(changeExtension(
1078 file.absFileName(), ".toc")), head);
1080 // not found, but we won't check further
1081 // pretend we've been successfully searching
1085 // note that we can have several of these on one line
1086 // this must be queried separated, because of
1087 // cases such as "File: file.ext (type eps)"
1088 // where "File: file.ext" would be skipped
1089 if (regex_match(token, sub, reg6)) {
1090 // search for strings in (...)
1091 static regex reg6_1("\\(([^()]+)(.)");
1093 string::const_iterator first = token.begin();
1094 string::const_iterator end = token.end();
1096 while (regex_search(first, end, what, reg6_1)) {
1097 // if we have a dot, try to handle as file
1098 if (contains(what.str(1), '.')) {
1099 first = what[0].second;
1100 if (what.str(2) == ")") {
1101 handleFoundFile(what.str(1), head);
1102 // since we had a closing bracket,
1103 // do not investigate further
1106 // if we have no closing bracket,
1107 // try to handle as file nevertheless
1108 found_file = handleFoundFile(
1109 what.str(1) + what.str(2), head);
1111 // if we do not have a dot, check if the line has
1112 // a closing bracket (else, we suspect a line break)
1113 else if (what.str(2) != ")") {
1114 first = what[0].second;
1117 // we have a closing bracket, so the content
1118 // is not a file name.
1119 // no need to investigate further
1120 // pretend we've been successfully searching
1121 first = what[0].second;
1128 // probable linebreak:
1132 // no linebreak: reset
1133 lastline = string();
1136 // Make sure that the main .tex file is in the dependency file.
1137 head.insert(file, true);
1141 void LaTeX::scanBlgFile(DepTable & dep)
1143 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1144 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1146 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1148 static regex const reg1(".*Found bibtex data file '([^']+).*");
1150 while (getline(ifs, token)) {
1151 token = rtrim(token, "\r");
1153 // FIXME UNICODE: We assume that citation keys and filenames
1154 // in the aux file are in the file system encoding.
1155 token = to_utf8(from_filesystem8bit(token));
1156 if (regex_match(token, sub, reg1)) {
1157 string data = sub.str(1);
1158 if (!data.empty()) {
1159 LYXERR(Debug::LATEX, "Found bib file: " << data);
1160 handleFoundFile(data, dep);