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"
39 using namespace lyx::support;
43 namespace os = support::os;
45 // TODO: in no particular order
46 // - get rid of the call to
47 // BufferList::updateIncludedTeXfiles, this should either
48 // be done before calling LaTeX::funcs or in a completely
50 // - the makeindex style files should be taken care of with
51 // the dependency mechanism.
52 // - we should perhaps also scan the bibtex log file
56 docstring runMessage(unsigned int count)
58 return bformat(_("Waiting for LaTeX run number %1$d"), count);
67 void TeXErrors::insertError(int line, docstring const & error_desc,
68 docstring const & error_text,
69 string const & child_name)
71 Error newerr(line, error_desc, error_text, child_name);
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,
96 FileName const & f, string const & p)
97 : cmd(latex), file(f), path(p), 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 bcf(changeExtension(file.absFileName(), ".bcf"));
132 FileName const ind(changeExtension(file.absFileName(), ".ind"));
136 FileName const nls(changeExtension(file.absFileName(), ".nls"));
139 // nomencl file (old version of the package)
140 FileName const gls(changeExtension(file.absFileName(), ".gls"));
143 // Also remove the aux file
144 FileName const aux(changeExtension(file.absFileName(), ".aux"));
149 int LaTeX::run(TeXErrors & terr)
150 // We know that this function will only be run if the lyx buffer
151 // has been changed. We also know that a newly written .tex file
152 // is always different from the previous one because of the date
153 // in it. However it seems safe to run latex (at least) one time
154 // each time the .tex file changes.
156 int scanres = NO_ERRORS;
157 unsigned int count = 0; // number of times run
158 num_errors = 0; // just to make sure.
159 unsigned int const MAX_RUN = 6;
160 DepTable head; // empty head
161 bool rerun = false; // rerun requested
163 // The class LaTeX does not know the temp path.
164 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
167 // Never write the depfile if an error was encountered.
170 // first check if the file dependencies exist:
171 // ->If it does exist
172 // check if any of the files mentioned in it have
173 // changed (done using a checksum).
175 // run latex once and
176 // remake the dependency file
177 // -> if not changed:
178 // just return there is nothing to do for us.
179 // ->if it doesn't exist
181 // run latex once (we need to run latex once anyway) and
182 // remake the dependency file.
185 bool had_depfile = depfile.exists();
186 bool run_bibtex = false;
187 FileName const aux_file(changeExtension(file.absFileName(), "aux"));
190 LYXERR(Debug::DEPEND, "Dependency file exists");
191 // Read the dep file:
192 had_depfile = head.read(depfile);
196 // Update the checksums
198 // Can't just check if anything has changed because it might
199 // have aborted on error last time... in which cas we need
200 // to re-run latex and collect the error messages
201 // (even if they are the same).
202 if (!output_file.exists()) {
203 LYXERR(Debug::DEPEND,
204 "re-running LaTeX because output file doesn't exist.");
205 } else if (!head.sumchange()) {
206 LYXERR(Debug::DEPEND, "return no_change");
209 LYXERR(Debug::DEPEND, "Dependency file has changed");
212 if (head.extchanged(".bib") || head.extchanged(".bst"))
215 LYXERR(Debug::DEPEND,
216 "Dependency file does not exist, or has wrong format");
218 /// We scan the aux file even when had_depfile = false,
219 /// because we can run pdflatex on the file after running latex on it,
220 /// in which case we will not need to run bibtex again.
221 vector<AuxInfo> bibtex_info_old;
223 bibtex_info_old = scanAuxFiles(aux_file);
226 LYXERR(Debug::LATEX, "Run #" << count);
227 message(runMessage(count));
230 scanres = scanLogFile(terr);
231 if (scanres & ERROR_RERUN) {
232 LYXERR(Debug::LATEX, "Rerunning LaTeX");
234 scanres = scanLogFile(terr);
237 if (scanres & ERRORS) {
238 deleteFilesOnError();
239 return scanres; // return on error
242 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
243 if (!run_bibtex && bibtex_info_old != bibtex_info)
246 // update the dependencies.
247 deplog(head); // reads the latex log
251 // At this point we must run external programs if needed.
252 // makeindex will be run if a .idx file changed or was generated.
253 // And if there were undefined citations or changes in references
254 // the .aux file is checked for signs of bibtex. Bibtex is then run
257 // memoir (at least) writes an empty *idx file in the first place.
258 // A second latex run is needed.
259 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
260 rerun = idxfile.exists() && idxfile.isFileEmpty();
263 if (head.haschanged(idxfile)) {
265 LYXERR(Debug::LATEX, "Running MakeIndex.");
266 message(_("Running Index Processor."));
267 // onlyFileName() is needed for cygwin
268 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
271 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
272 if (head.haschanged(nlofile))
273 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
274 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
275 if (head.haschanged(glofile))
276 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
278 // check if we're using biber instead of bibtex
279 // biber writes no info to the aux file, so we just check
280 // if a bcf file exists (and if it was updated)
281 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
282 bool const biber = head.exist(bcffile);
285 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
286 if (scanres & UNDEF_CIT || run_bibtex) {
287 // Here we must scan the .aux file and look for
288 // "\bibdata" and/or "\bibstyle". If one of those
289 // tags is found -> run bibtex and set rerun = true;
291 LYXERR(Debug::LATEX, "Running BibTeX.");
292 message(_("Running BibTeX."));
293 updateBibtexDependencies(head, bibtex_info, biber);
294 rerun |= runBibTeX(bibtex_info, runparams, biber);
296 // since biber writes no info to the aux file, we have
297 // to parse the blg file (which only exists after biber
299 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
300 if (blgfile.exists())
303 } else if (!had_depfile) {
304 /// If we run pdflatex on the file after running latex on it,
305 /// then we do not need to run bibtex, but we do need to
306 /// insert the .bib and .bst files into the .dep-pdf file.
307 updateBibtexDependencies(head, bibtex_info, biber);
311 // we know on this point that latex has been run once (or we just
312 // returned) and the question now is to decide if we need to run
313 // it any more. This is done by asking if any of the files in the
314 // dependency file has changed. (remember that the checksum for
315 // a given file is reported to have changed if it just was created)
316 // -> if changed or rerun == true:
317 // run latex once more and
318 // update the dependency structure
319 // -> if not changed:
320 // we do nothing at this point
322 if (rerun || head.sumchange()) {
325 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
326 LYXERR(Debug::LATEX, "Run #" << count);
327 message(runMessage(count));
329 scanres = scanLogFile(terr);
330 if (scanres & ERRORS) {
331 deleteFilesOnError();
332 return scanres; // return on error
335 // update the depedencies
336 deplog(head); // reads the latex log
339 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
344 // Complex bibliography packages such as Biblatex require
345 // an additional bibtex cycle sometimes.
346 if (scanres & UNDEF_CIT) {
347 // Here we must scan the .aux file and look for
348 // "\bibdata" and/or "\bibstyle". If one of those
349 // tags is found -> run bibtex and set rerun = true;
351 LYXERR(Debug::LATEX, "Running BibTeX.");
352 message(_("Running BibTeX."));
353 updateBibtexDependencies(head, bibtex_info, biber);
354 rerun |= runBibTeX(bibtex_info, runparams, biber);
358 // The inclusion of files generated by external programs such as
359 // makeindex or bibtex might have done changes to pagenumbering,
360 // etc. And because of this we must run the external programs
361 // again to make sure everything is redone correctly.
362 // Also there should be no need to run the external programs any
365 // run makeindex if the <file>.idx has changed or was generated.
366 if (head.haschanged(idxfile)) {
368 LYXERR(Debug::LATEX, "Running MakeIndex.");
369 message(_("Running Index Processor."));
370 // onlyFileName() is needed for cygwin
371 rerun = runMakeIndex(onlyFileName(changeExtension(
372 file.absFileName(), ".idx")), runparams);
375 // I am not pretty sure if need this twice.
376 if (head.haschanged(nlofile))
377 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
378 if (head.haschanged(glofile))
379 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
382 // we will only run latex more if the log file asks for it.
383 // or if the sumchange() is true.
384 // -> rerun asked for:
386 // remake the dependency file
387 // goto 2 or return if max runs are reached.
388 // -> rerun not asked for:
389 // just return (fall out of bottom of func)
391 while ((head.sumchange() || rerun || (scanres & RERUN))
392 && count < MAX_RUN) {
393 // Yes rerun until message goes away, or until
394 // MAX_RUNS are reached.
397 LYXERR(Debug::LATEX, "Run #" << count);
398 message(runMessage(count));
400 scanres = scanLogFile(terr);
401 if (scanres & ERRORS) {
402 deleteFilesOnError();
403 return scanres; // return on error
410 // Write the dependencies to file.
412 LYXERR(Debug::LATEX, "Done.");
417 int LaTeX::startscript()
419 // onlyFileName() is needed for cygwin
420 string tmp = cmd + ' '
421 + quoteName(onlyFileName(file.toFilesystemEncoding()))
422 + " > " + os::nulldev();
424 return one.startscript(Systemcall::Wait, tmp, path);
428 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
429 string const & params)
431 string tmp = runparams.use_japanese ?
432 lyxrc.jindex_command : lyxrc.index_command;
434 if (!runparams.index_command.empty())
435 tmp = runparams.index_command;
438 "idx file has been made, running index processor ("
439 << tmp << ") on file " << f);
441 tmp = subst(tmp, "$$lang", runparams.document_language);
442 if (runparams.use_indices) {
443 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
445 "Multiple indices. Using splitindex command: " << tmp);
451 one.startscript(Systemcall::Wait, tmp, path);
456 bool LaTeX::runMakeIndexNomencl(FileName const & file,
457 string const & nlo, string const & nls)
459 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
460 message(_("Running MakeIndex for nomencl."));
461 string tmp = lyxrc.nomencl_command + ' ';
462 // onlyFileName() is needed for cygwin
463 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
465 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
467 one.startscript(Systemcall::Wait, tmp, path);
472 vector<AuxInfo> const
473 LaTeX::scanAuxFiles(FileName const & file)
475 vector<AuxInfo> result;
477 result.push_back(scanAuxFile(file));
479 string const basename = removeExtension(file.absFileName());
480 for (int i = 1; i < 1000; ++i) {
481 FileName const file2(basename
482 + '.' + convert<string>(i)
486 result.push_back(scanAuxFile(file2));
492 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
495 result.aux_file = file;
496 scanAuxFile(file, result);
501 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
503 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
505 ifstream ifs(file.toFilesystemEncoding().c_str());
507 static regex const reg1("\\\\citation\\{([^}]+)\\}");
508 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
509 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
510 static regex const reg4("\\\\@input\\{([^}]+)\\}");
512 while (getline(ifs, token)) {
513 token = rtrim(token, "\r");
515 // FIXME UNICODE: We assume that citation keys and filenames
516 // in the aux file are in the file system encoding.
517 token = to_utf8(from_filesystem8bit(token));
518 if (regex_match(token, sub, reg1)) {
519 string data = sub.str(1);
520 while (!data.empty()) {
522 data = split(data, citation, ',');
523 LYXERR(Debug::LATEX, "Citation: " << 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: `" << database << '\'');
535 aux_info.databases.insert(database);
537 } else if (regex_match(token, sub, reg3)) {
538 string style = sub.str(1);
539 // token is now the style file
540 // pass it to the helper
541 style = changeExtension(style, "bst");
542 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
543 aux_info.styles.insert(style);
544 } else if (regex_match(token, sub, reg4)) {
545 string const file2 = sub.str(1);
546 scanAuxFile(makeAbsPath(file2), aux_info);
552 void LaTeX::updateBibtexDependencies(DepTable & dep,
553 vector<AuxInfo> const & bibtex_info,
556 // Since a run of Bibtex mandates more latex runs it is ok to
557 // remove all ".bib" and ".bst" files.
558 dep.remove_files_with_extension(".bib");
559 dep.remove_files_with_extension(".bst");
560 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
562 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
563 it != bibtex_info.end(); ++it) {
564 for (set<string>::const_iterator it2 = it->databases.begin();
565 it2 != it->databases.end(); ++it2) {
566 FileName const file = findtexfile(*it2, "bib");
568 dep.insert(file, true);
571 for (set<string>::const_iterator it2 = it->styles.begin();
572 it2 != it->styles.end(); ++it2) {
573 FileName const file = findtexfile(*it2, "bst");
575 dep.insert(file, true);
579 // biber writes nothing into the aux file.
580 // Instead, we have to scan the blg file
587 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
588 OutputParams const & runparams, bool biber)
591 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
592 it != bibtex_info.end(); ++it) {
593 if (!biber && it->databases.empty())
597 string tmp = runparams.use_japanese ?
598 lyxrc.jbibtex_command : lyxrc.bibtex_command;
600 if (!runparams.bibtex_command.empty())
601 tmp = runparams.bibtex_command;
603 // onlyFileName() is needed for cygwin
604 tmp += quoteName(onlyFileName(removeExtension(
605 it->aux_file.absFileName())));
607 one.startscript(Systemcall::Wait, tmp, path);
609 // Return whether bibtex was run
614 int LaTeX::scanLogFile(TeXErrors & terr)
618 int retval = NO_ERRORS;
620 onlyFileName(changeExtension(file.absFileName(), ".log"));
621 LYXERR(Debug::LATEX, "Log file: " << tmp);
622 FileName const fn = FileName(makeAbsPath(tmp));
623 ifstream ifs(fn.toFilesystemEncoding().c_str());
624 bool fle_style = false;
625 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
626 static regex child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
627 // Flag for 'File ended while scanning' message.
628 // We need to wait for subsequent processing.
629 string wait_for_error;
632 stack <pair<string, int> > child;
635 while (getline(ifs, token)) {
636 // MikTeX sometimes inserts \0 in the log file. They can't be
637 // removed directly with the existing string utility
638 // functions, so convert them first to \r, and remove all
639 // \r's afterwards, since we need to remove them anyway.
640 token = subst(token, '\0', '\r');
641 token = subst(token, "\r", "");
644 LYXERR(Debug::LATEX, "Log line: " << token);
649 // Track child documents
650 for (size_t i = 0; i < token.length(); ++i) {
651 if (token[i] == '(') {
653 size_t j = token.find('(', i + 1);
654 size_t len = j == string::npos
655 ? token.substr(i + 1).length()
657 if (regex_match(token.substr(i + 1, len),
659 string const name = sub.str(1);
660 child.push(make_pair(name, pnest));
663 } else if (token[i] == ')') {
665 && child.top().second == pnest)
670 child_name = child.empty() ? empty_string() : child.top().first;
672 if (contains(token, "file:line:error style messages enabled"))
675 if (prefixIs(token, "LaTeX Warning:") ||
676 prefixIs(token, "! pdfTeX warning")) {
677 // Here shall we handle different
679 retval |= LATEX_WARNING;
680 LYXERR(Debug::LATEX, "LaTeX Warning.");
681 if (contains(token, "Rerun to get cross-references")) {
683 LYXERR(Debug::LATEX, "We should rerun.");
684 // package clefval needs 2 latex runs before bibtex
685 } else if (contains(token, "Value of")
686 && contains(token, "on page")
687 && contains(token, "undefined")) {
688 retval |= ERROR_RERUN;
689 LYXERR(Debug::LATEX, "Force rerun.");
691 } else if (contains(token, "Etaremune labels have changed")) {
692 retval |= ERROR_RERUN;
693 LYXERR(Debug::LATEX, "Force rerun.");
694 } else if (contains(token, "Citation")
695 && contains(token, "on page")
696 && contains(token, "undefined")) {
699 } else if (prefixIs(token, "Package")) {
701 retval |= PACKAGE_WARNING;
702 if (contains(token, "natbib Warning:")) {
704 if (contains(token, "Citation")
705 && contains(token, "on page")
706 && contains(token, "undefined")) {
709 } else if (contains(token, "run BibTeX")) {
711 } else if (contains(token, "Rerun LaTeX") ||
712 contains(token, "Please rerun LaTeX") ||
713 contains(token, "Rerun to get")) {
714 // at least longtable.sty and bibtopic.sty
716 LYXERR(Debug::LATEX, "We should rerun.");
719 } else if (prefixIs(token, "LETTRE WARNING:")) {
720 if (contains(token, "veuillez recompiler")) {
722 LYXERR(Debug::LATEX, "We should rerun.");
725 } else if (token[0] == '(') {
726 if (contains(token, "Rerun LaTeX") ||
727 contains(token, "Rerun to get")) {
729 LYXERR(Debug::LATEX, "We should rerun.");
732 } else if (prefixIs(token, "! ")
734 && regex_match(token, sub, file_line_error)
735 && !contains(token, "pdfTeX warning"))) {
736 // Ok, we have something that looks like a TeX Error
737 // but what do we really have.
739 // Just get the error description:
741 if (prefixIs(token, "! "))
742 desc = string(token, 2);
745 if (contains(token, "LaTeX Error:"))
746 retval |= LATEX_ERROR;
748 if (prefixIs(token, "! File ended while scanning")){
749 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
750 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
751 retval |= ERROR_RERUN;
752 LYXERR(Debug::LATEX, "Force rerun.");
754 // bug 6445. At this point its not clear we finish with error.
755 wait_for_error = desc;
760 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
761 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
762 retval |= ERROR_RERUN;
763 LYXERR(Debug::LATEX, "Force rerun.");
766 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
767 retval |= LATEX_ERROR;
770 errstr = wait_for_error;
772 if (!getline(ifs, tmp))
774 tmp = rtrim(tmp, "\r");
775 errstr += "\n" + tmp;
778 } while (!contains(tmp, "(job aborted"));
781 from_local8bit("Emergency stop"),
782 from_local8bit(errstr),
790 if (!getline(ifs, tmp))
792 tmp = rtrim(tmp, "\r");
795 } while (!prefixIs(tmp, "l."));
796 if (prefixIs(tmp, "l.")) {
797 // we have a latex error
800 "Package babel Error: You haven't defined the language") ||
802 "Package babel Error: You haven't loaded the option"))
803 retval |= ERROR_RERUN;
804 // get the line number:
806 sscanf(tmp.c_str(), "l.%d", &line);
807 // get the rest of the message:
808 string errstr(tmp, tmp.find(' '));
811 tmp = rtrim(tmp, "\r");
812 while (!contains(errstr, "l.")
814 && !prefixIs(tmp, "! ")
815 && !contains(tmp, "(job aborted")) {
819 tmp = rtrim(tmp, "\r");
821 LYXERR(Debug::LATEX, "line: " << line << '\n'
822 << "Desc: " << desc << '\n' << "Text: " << errstr);
823 if (line == last_line)
829 if (line_count <= 5) {
831 // We have no idea what the encoding of
833 // It seems that the output from the
834 // latex compiler itself is pure ASCII,
835 // but it can include bits from the
836 // document, so whatever encoding we
837 // assume here it can be wrong.
838 terr.insertError(line,
839 from_local8bit(desc),
840 from_local8bit(errstr),
846 // information messages, TeX warnings and other
847 // warnings we have not caught earlier.
848 if (prefixIs(token, "Overfull ")) {
849 retval |= TEX_WARNING;
850 } else if (prefixIs(token, "Underfull ")) {
851 retval |= TEX_WARNING;
852 } else if (contains(token, "Rerun to get citations")) {
853 // Natbib seems to use this.
855 } else if (contains(token, "No pages of output")) {
856 // A dvi file was not created
858 } else if (contains(token, "That makes 100 errors")) {
859 // More than 100 errors were reprted
860 retval |= TOO_MANY_ERRORS;
861 } else if (prefixIs(token, "!pdfTeX error:")){
862 // otherwise we dont catch e.g.:
863 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
866 from_local8bit("pdfTeX Error"),
867 from_local8bit(token),
872 LYXERR(Debug::LATEX, "Log line: " << token);
879 bool insertIfExists(FileName const & absname, DepTable & head)
881 if (absname.exists() && !absname.isDirectory()) {
882 head.insert(absname, true);
889 bool handleFoundFile(string const & ff, DepTable & head)
891 // convert from native os path to unix path
892 string foundfile = os::internal_path(trim(ff));
894 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
896 // Ok now we found a file.
897 // Now we should make sure that this is a file that we can
898 // access through the normal paths.
899 // We will not try any fancy search methods to
902 // (1) foundfile is an
903 // absolute path and should
906 if (FileName::isAbsolute(foundfile)) {
907 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
908 // On initial insert we want to do the update at once
909 // since this file cannot be a file generated by
911 absname.set(foundfile);
912 if (!insertIfExists(absname, head)) {
914 string strippedfile = foundfile;
915 while (contains(strippedfile, " ")) {
916 // files with spaces are often enclosed in quotation
917 // marks; those have to be removed
918 string unquoted = subst(strippedfile, "\"", "");
919 absname.set(unquoted);
920 if (insertIfExists(absname, head))
922 // strip off part after last space and try again
923 string tmp = strippedfile;
924 string const stripoff =
925 rsplit(tmp, strippedfile, ' ');
926 absname.set(strippedfile);
927 if (insertIfExists(absname, head))
933 string onlyfile = onlyFileName(foundfile);
934 absname = makeAbsPath(onlyfile);
937 while (contains(foundfile, ' ')) {
938 if (absname.exists())
942 // files with spaces are often enclosed in quotation
943 // marks; those have to be removed
944 string unquoted = subst(foundfile, "\"", "");
945 absname = makeAbsPath(unquoted);
946 if (absname.exists())
948 // strip off part after last space and try again
950 string const stripoff =
951 rsplit(foundfile, strippedfile, ' ');
952 foundfile = strippedfile;
953 onlyfile = onlyFileName(strippedfile);
954 absname = makeAbsPath(onlyfile);
958 // (2) foundfile is in the tmpdir
959 // insert it into head
960 if (absname.exists() && !absname.isDirectory()) {
961 // FIXME: This regex contained glo, but glo is used by the old
962 // version of nomencl.sty. Do we need to put it back?
963 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
964 if (regex_match(onlyfile, unwanted)) {
965 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
966 << " in the dep file");
967 } else if (suffixIs(onlyfile, ".tex")) {
968 // This is a tex file generated by LyX
969 // and latex is not likely to change this
971 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
972 head.insert(absname, true);
974 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
975 head.insert(absname);
979 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
985 bool checkLineBreak(string const & ff, DepTable & head)
987 if (!contains(ff, '.'))
990 // if we have a dot, we let handleFoundFile decide
991 return handleFoundFile(ff, head);
997 void LaTeX::deplog(DepTable & head)
999 // This function reads the LaTeX log file end extracts all the
1000 // external files used by the LaTeX run. The files are then
1001 // entered into the dependency file.
1003 string const logfile =
1004 onlyFileName(changeExtension(file.absFileName(), ".log"));
1006 static regex const reg1("File: (.+).*");
1007 static regex const reg2("No file (.+)(.).*");
1008 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1009 // If an index should be created, MikTex does not write a line like
1010 // \openout# = 'sample.idx'.
1011 // but instead only a line like this into the log:
1012 // Writing index file sample.idx
1013 static regex const reg4("Writing index file (.+).*");
1014 // files also can be enclosed in <...>
1015 static regex const reg5("<([^>]+)(.).*");
1016 static regex const regoldnomencl("Writing glossary file (.+).*");
1017 static regex const regnomencl("Writing nomenclature file (.+).*");
1018 // If a toc should be created, MikTex does not write a line like
1019 // \openout# = `sample.toc'.
1020 // but only a line like this into the log:
1022 // This line is also written by tetex.
1023 // This line is not present if no toc should be created.
1024 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1025 static regex const reg6(".*\\([^)]+.*");
1027 FileName const fn = makeAbsPath(logfile);
1028 ifstream ifs(fn.toFilesystemEncoding().c_str());
1031 // Ok, the scanning of files here is not sufficient.
1032 // Sometimes files are named by "File:� xxx" only
1033 // So I think we should use some regexps to find files instead.
1034 // Note: all file names and paths might contains spaces.
1035 bool found_file = false;
1037 getline(ifs, token);
1038 // MikTeX sometimes inserts \0 in the log file. They can't be
1039 // removed directly with the existing string utility
1040 // functions, so convert them first to \r, and remove all
1041 // \r's afterwards, since we need to remove them anyway.
1042 token = subst(token, '\0', '\r');
1043 token = subst(token, "\r", "");
1044 if (token.empty() || token == ")") {
1045 lastline = string();
1049 // FIXME UNICODE: We assume that the file names in the log
1050 // file are in the file system encoding.
1051 token = to_utf8(from_filesystem8bit(token));
1053 // Sometimes, filenames are broken across lines.
1054 // We care for that and save suspicious lines.
1055 // Here we exclude some cases where we are sure
1056 // that there is no continued filename
1057 if (!lastline.empty()) {
1058 static regex const package_info("Package \\w+ Info: .*");
1059 static regex const package_warning("Package \\w+ Warning: .*");
1060 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1061 || prefixIs(token, "Package:")
1062 || prefixIs(token, "Language:")
1063 || prefixIs(token, "LaTeX Info:")
1064 || prefixIs(token, "LaTeX Font Info:")
1065 || prefixIs(token, "\\openout[")
1066 || prefixIs(token, "))")
1067 || regex_match(token, package_info)
1068 || regex_match(token, package_warning))
1069 lastline = string();
1072 if (!lastline.empty())
1073 // probably a continued filename from last line
1074 token = lastline + token;
1075 if (token.length() > 255) {
1076 // string too long. Cut off.
1077 token.erase(0, token.length() - 251);
1082 // (1) "File: file.ext"
1083 if (regex_match(token, sub, reg1)) {
1085 found_file = checkLineBreak(sub.str(1), head);
1087 if (suffixIs(token, ")"))
1088 // no line break for sure
1089 // pretend we've been successfully searching
1091 // (2) "No file file.ext"
1092 } else if (regex_match(token, sub, reg2)) {
1093 // file names must contains a dot, line ends with dot
1094 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1095 found_file = handleFoundFile(sub.str(1), head);
1097 // we suspect a line break
1099 // (3) "\openout<nr> = `file.ext'."
1100 } else if (regex_match(token, sub, reg3)) {
1101 // search for closing '. at the end of the line
1102 if (sub.str(2) == "\'.")
1103 found_file = handleFoundFile(sub.str(1), head);
1105 // probable line break
1107 // (4) "Writing index file file.ext"
1108 } else if (regex_match(token, sub, reg4))
1110 found_file = checkLineBreak(sub.str(1), head);
1112 else if (regex_match(token, sub, reg5)) {
1113 // search for closing '>' and dot ('*.*>') at the eol
1114 if (contains(sub.str(1), '.') && sub.str(2) == ">")
1115 found_file = handleFoundFile(sub.str(1), head);
1117 // probable line break
1119 // (6) "Writing nomenclature file file.ext"
1120 } else if (regex_match(token, sub, regnomencl) ||
1121 regex_match(token, sub, regoldnomencl))
1123 found_file = checkLineBreak(sub.str(1), head);
1124 // (7) "\tf@toc=\write<nr>" (for MikTeX)
1125 else if (regex_match(token, sub, miktexTocReg))
1126 found_file = handleFoundFile(onlyFileName(changeExtension(
1127 file.absFileName(), ".toc")), head);
1129 // not found, but we won't check further
1130 // pretend we've been successfully searching
1134 // note that we can have several of these on one line
1135 // this must be queried separated, because of
1136 // cases such as "File: file.ext (type eps)"
1137 // where "File: file.ext" would be skipped
1138 if (regex_match(token, sub, reg6)) {
1139 // search for strings in (...)
1140 static regex reg6_1("\\(([^()]+)(.)");
1142 string::const_iterator first = token.begin();
1143 string::const_iterator end = token.end();
1145 while (regex_search(first, end, what, reg6_1)) {
1146 // if we have a dot, try to handle as file
1147 if (contains(what.str(1), '.')) {
1148 first = what[0].second;
1149 if (what.str(2) == ")") {
1150 handleFoundFile(what.str(1), head);
1151 // since we had a closing bracket,
1152 // do not investigate further
1155 // if we have no closing bracket,
1156 // try to handle as file nevertheless
1157 found_file = handleFoundFile(
1158 what.str(1) + what.str(2), head);
1160 // if we do not have a dot, check if the line has
1161 // a closing bracket (else, we suspect a line break)
1162 else if (what.str(2) != ")") {
1163 first = what[0].second;
1166 // we have a closing bracket, so the content
1167 // is not a file name.
1168 // no need to investigate further
1169 // pretend we've been successfully searching
1170 first = what[0].second;
1177 // probable linebreak:
1181 // no linebreak: reset
1182 lastline = string();
1185 // Make sure that the main .tex file is in the dependency file.
1186 head.insert(file, true);
1190 void LaTeX::scanBlgFile(DepTable & dep)
1192 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1193 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1195 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1197 static regex const reg1(".*Found bibtex data file '([^']+).*");
1199 while (getline(ifs, token)) {
1200 token = rtrim(token, "\r");
1202 // FIXME UNICODE: We assume that citation keys and filenames
1203 // in the aux file are in the file system encoding.
1204 token = to_utf8(from_filesystem8bit(token));
1205 if (regex_match(token, sub, reg1)) {
1206 string data = sub.str(1);
1207 if (!data.empty()) {
1208 LYXERR(Debug::LATEX, "Found bib file: " << data);
1209 handleFoundFile(data, dep);