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 ind(changeExtension(file.absFileName(), ".ind"));
130 FileName const nls(changeExtension(file.absFileName(), ".nls"));
133 // nomencl file (old version of the package)
134 FileName const gls(changeExtension(file.absFileName(), ".gls"));
137 // Also remove the aux file
138 FileName const aux(changeExtension(file.absFileName(), ".aux"));
143 int LaTeX::run(TeXErrors & terr)
144 // We know that this function will only be run if the lyx buffer
145 // has been changed. We also know that a newly written .tex file
146 // is always different from the previous one because of the date
147 // in it. However it seems safe to run latex (at least) one time
148 // each time the .tex file changes.
150 int scanres = NO_ERRORS;
151 unsigned int count = 0; // number of times run
152 num_errors = 0; // just to make sure.
153 unsigned int const MAX_RUN = 6;
154 DepTable head; // empty head
155 bool rerun = false; // rerun requested
157 // The class LaTeX does not know the temp path.
158 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
161 // Never write the depfile if an error was encountered.
164 // first check if the file dependencies exist:
165 // ->If it does exist
166 // check if any of the files mentioned in it have
167 // changed (done using a checksum).
169 // run latex once and
170 // remake the dependency file
171 // -> if not changed:
172 // just return there is nothing to do for us.
173 // ->if it doesn't exist
175 // run latex once (we need to run latex once anyway) and
176 // remake the dependency file.
179 bool had_depfile = depfile.exists();
180 bool run_bibtex = false;
181 FileName const aux_file(changeExtension(file.absFileName(), "aux"));
184 LYXERR(Debug::DEPEND, "Dependency file exists");
185 // Read the dep file:
186 had_depfile = head.read(depfile);
190 // Update the checksums
192 // Can't just check if anything has changed because it might
193 // have aborted on error last time... in which cas we need
194 // to re-run latex and collect the error messages
195 // (even if they are the same).
196 if (!output_file.exists()) {
197 LYXERR(Debug::DEPEND,
198 "re-running LaTeX because output file doesn't exist.");
199 } else if (!head.sumchange()) {
200 LYXERR(Debug::DEPEND, "return no_change");
203 LYXERR(Debug::DEPEND, "Dependency file has changed");
206 if (head.extchanged(".bib") || head.extchanged(".bst"))
209 LYXERR(Debug::DEPEND,
210 "Dependency file does not exist, or has wrong format");
212 /// We scan the aux file even when had_depfile = false,
213 /// because we can run pdflatex on the file after running latex on it,
214 /// in which case we will not need to run bibtex again.
215 vector<AuxInfo> bibtex_info_old;
217 bibtex_info_old = scanAuxFiles(aux_file);
220 LYXERR(Debug::LATEX, "Run #" << count);
221 message(runMessage(count));
224 scanres = scanLogFile(terr);
225 if (scanres & ERROR_RERUN) {
226 LYXERR(Debug::LATEX, "Rerunning LaTeX");
228 scanres = scanLogFile(terr);
231 if (scanres & ERRORS) {
232 deleteFilesOnError();
233 return scanres; // return on error
236 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
237 if (!run_bibtex && bibtex_info_old != bibtex_info)
240 // update the dependencies.
241 deplog(head); // reads the latex log
245 // At this point we must run external programs if needed.
246 // makeindex will be run if a .idx file changed or was generated.
247 // And if there were undefined citations or changes in references
248 // the .aux file is checked for signs of bibtex. Bibtex is then run
251 // memoir (at least) writes an empty *idx file in the first place.
252 // A second latex run is needed.
253 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
254 rerun = idxfile.exists() && idxfile.isFileEmpty();
257 if (head.haschanged(idxfile)) {
259 LYXERR(Debug::LATEX, "Running MakeIndex.");
260 message(_("Running Index Processor."));
261 // onlyFileName() is needed for cygwin
262 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
265 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
266 if (head.haschanged(nlofile))
267 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
268 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
269 if (head.haschanged(glofile))
270 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
273 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
274 if (scanres & UNDEF_CIT || run_bibtex) {
275 // Here we must scan the .aux file and look for
276 // "\bibdata" and/or "\bibstyle". If one of those
277 // tags is found -> run bibtex and set rerun = true;
279 LYXERR(Debug::LATEX, "Running BibTeX.");
280 message(_("Running BibTeX."));
281 updateBibtexDependencies(head, bibtex_info);
282 rerun |= runBibTeX(bibtex_info, runparams);
283 } else if (!had_depfile) {
284 /// If we run pdflatex on the file after running latex on it,
285 /// then we do not need to run bibtex, but we do need to
286 /// insert the .bib and .bst files into the .dep-pdf file.
287 updateBibtexDependencies(head, bibtex_info);
291 // we know on this point that latex has been run once (or we just
292 // returned) and the question now is to decide if we need to run
293 // it any more. This is done by asking if any of the files in the
294 // dependency file has changed. (remember that the checksum for
295 // a given file is reported to have changed if it just was created)
296 // -> if changed or rerun == true:
297 // run latex once more and
298 // update the dependency structure
299 // -> if not changed:
300 // we do nothing at this point
302 if (rerun || head.sumchange()) {
305 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
306 LYXERR(Debug::LATEX, "Run #" << count);
307 message(runMessage(count));
309 scanres = scanLogFile(terr);
310 if (scanres & ERRORS) {
311 deleteFilesOnError();
312 return scanres; // return on error
315 // update the depedencies
316 deplog(head); // reads the latex log
319 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
324 // Complex bibliography packages such as Biblatex require
325 // an additional bibtex cycle sometimes.
326 if (scanres & UNDEF_CIT) {
327 // Here we must scan the .aux file and look for
328 // "\bibdata" and/or "\bibstyle". If one of those
329 // tags is found -> run bibtex and set rerun = true;
331 LYXERR(Debug::LATEX, "Running BibTeX.");
332 message(_("Running BibTeX."));
333 updateBibtexDependencies(head, bibtex_info);
334 rerun |= runBibTeX(bibtex_info, runparams);
338 // The inclusion of files generated by external programs such as
339 // makeindex or bibtex might have done changes to pagenumbering,
340 // etc. And because of this we must run the external programs
341 // again to make sure everything is redone correctly.
342 // Also there should be no need to run the external programs any
345 // run makeindex if the <file>.idx has changed or was generated.
346 if (head.haschanged(idxfile)) {
348 LYXERR(Debug::LATEX, "Running MakeIndex.");
349 message(_("Running Index Processor."));
350 // onlyFileName() is needed for cygwin
351 rerun = runMakeIndex(onlyFileName(changeExtension(
352 file.absFileName(), ".idx")), runparams);
355 // I am not pretty sure if need this twice.
356 if (head.haschanged(nlofile))
357 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
358 if (head.haschanged(glofile))
359 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
362 // we will only run latex more if the log file asks for it.
363 // or if the sumchange() is true.
364 // -> rerun asked for:
366 // remake the dependency file
367 // goto 2 or return if max runs are reached.
368 // -> rerun not asked for:
369 // just return (fall out of bottom of func)
371 while ((head.sumchange() || rerun || (scanres & RERUN))
372 && count < MAX_RUN) {
373 // Yes rerun until message goes away, or until
374 // MAX_RUNS are reached.
377 LYXERR(Debug::LATEX, "Run #" << count);
378 message(runMessage(count));
380 scanres = scanLogFile(terr);
381 if (scanres & ERRORS) {
382 deleteFilesOnError();
383 return scanres; // return on error
390 // Write the dependencies to file.
392 LYXERR(Debug::LATEX, "Done.");
397 int LaTeX::startscript()
399 // onlyFileName() is needed for cygwin
400 string tmp = cmd + ' '
401 + quoteName(onlyFileName(file.toFilesystemEncoding()))
402 + " > " + os::nulldev();
404 return one.startscript(Systemcall::Wait, tmp);
408 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
409 string const & params)
411 string tmp = runparams.use_japanese ?
412 lyxrc.jindex_command : lyxrc.index_command;
414 if (!runparams.index_command.empty())
415 tmp = runparams.index_command;
418 "idx file has been made, running index processor ("
419 << tmp << ") on file " << f);
421 tmp = subst(tmp, "$$lang", runparams.document_language);
422 if (runparams.use_indices) {
423 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
425 "Multiple indices. Using splitindex command: " << tmp);
431 one.startscript(Systemcall::Wait, tmp);
436 bool LaTeX::runMakeIndexNomencl(FileName const & file,
437 string const & nlo, string const & nls)
439 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
440 message(_("Running MakeIndex for nomencl."));
441 string tmp = lyxrc.nomencl_command + ' ';
442 // onlyFileName() is needed for cygwin
443 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
445 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
447 one.startscript(Systemcall::Wait, tmp);
452 vector<AuxInfo> const
453 LaTeX::scanAuxFiles(FileName const & file)
455 vector<AuxInfo> result;
457 result.push_back(scanAuxFile(file));
459 string const basename = removeExtension(file.absFileName());
460 for (int i = 1; i < 1000; ++i) {
461 FileName const file2(basename
462 + '.' + convert<string>(i)
466 result.push_back(scanAuxFile(file2));
472 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
475 result.aux_file = file;
476 scanAuxFile(file, result);
481 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
483 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
485 ifstream ifs(file.toFilesystemEncoding().c_str());
487 static regex const reg1("\\\\citation\\{([^}]+)\\}");
488 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
489 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
490 static regex const reg4("\\\\@input\\{([^}]+)\\}");
492 while (getline(ifs, token)) {
493 token = rtrim(token, "\r");
495 // FIXME UNICODE: We assume that citation keys and filenames
496 // in the aux file are in the file system encoding.
497 token = to_utf8(from_filesystem8bit(token));
498 if (regex_match(token, sub, reg1)) {
499 string data = sub.str(1);
500 while (!data.empty()) {
502 data = split(data, citation, ',');
503 LYXERR(Debug::LATEX, "Citation: " << citation);
504 aux_info.citations.insert(citation);
506 } else if (regex_match(token, sub, reg2)) {
507 string data = sub.str(1);
508 // data is now all the bib files separated by ','
509 // get them one by one and pass them to the helper
510 while (!data.empty()) {
512 data = split(data, database, ',');
513 database = changeExtension(database, "bib");
514 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
515 aux_info.databases.insert(database);
517 } else if (regex_match(token, sub, reg3)) {
518 string style = sub.str(1);
519 // token is now the style file
520 // pass it to the helper
521 style = changeExtension(style, "bst");
522 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
523 aux_info.styles.insert(style);
524 } else if (regex_match(token, sub, reg4)) {
525 string const file2 = sub.str(1);
526 scanAuxFile(makeAbsPath(file2), aux_info);
532 void LaTeX::updateBibtexDependencies(DepTable & dep,
533 vector<AuxInfo> const & bibtex_info)
535 // Since a run of Bibtex mandates more latex runs it is ok to
536 // remove all ".bib" and ".bst" files.
537 dep.remove_files_with_extension(".bib");
538 dep.remove_files_with_extension(".bst");
539 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
541 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
542 it != bibtex_info.end(); ++it) {
543 for (set<string>::const_iterator it2 = it->databases.begin();
544 it2 != it->databases.end(); ++it2) {
545 FileName const file = findtexfile(*it2, "bib");
547 dep.insert(file, true);
550 for (set<string>::const_iterator it2 = it->styles.begin();
551 it2 != it->styles.end(); ++it2) {
552 FileName const file = findtexfile(*it2, "bst");
554 dep.insert(file, true);
560 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
561 OutputParams const & runparams)
564 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
565 it != bibtex_info.end(); ++it) {
566 if (it->databases.empty())
570 string tmp = runparams.use_japanese ?
571 lyxrc.jbibtex_command : lyxrc.bibtex_command;
573 if (!runparams.bibtex_command.empty())
574 tmp = runparams.bibtex_command;
576 // onlyFileName() is needed for cygwin
577 tmp += quoteName(onlyFileName(removeExtension(
578 it->aux_file.absFileName())));
580 one.startscript(Systemcall::Wait, tmp);
582 // Return whether bibtex was run
587 int LaTeX::scanLogFile(TeXErrors & terr)
591 int retval = NO_ERRORS;
593 onlyFileName(changeExtension(file.absFileName(), ".log"));
594 LYXERR(Debug::LATEX, "Log file: " << tmp);
595 FileName const fn = FileName(makeAbsPath(tmp));
596 ifstream ifs(fn.toFilesystemEncoding().c_str());
597 bool fle_style = false;
598 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
599 // Flag for 'File ended while scanning' message.
600 // We need to wait for subsequent processing.
601 string wait_for_error;
604 while (getline(ifs, token)) {
605 // MikTeX sometimes inserts \0 in the log file. They can't be
606 // removed directly with the existing string utility
607 // functions, so convert them first to \r, and remove all
608 // \r's afterwards, since we need to remove them anyway.
609 token = subst(token, '\0', '\r');
610 token = subst(token, "\r", "");
613 LYXERR(Debug::LATEX, "Log line: " << token);
618 if (contains(token, "file:line:error style messages enabled"))
621 if (prefixIs(token, "LaTeX Warning:") ||
622 prefixIs(token, "! pdfTeX warning")) {
623 // Here shall we handle different
625 retval |= LATEX_WARNING;
626 LYXERR(Debug::LATEX, "LaTeX Warning.");
627 if (contains(token, "Rerun to get cross-references")) {
629 LYXERR(Debug::LATEX, "We should rerun.");
630 // package clefval needs 2 latex runs before bibtex
631 } else if (contains(token, "Value of")
632 && contains(token, "on page")
633 && contains(token, "undefined")) {
634 retval |= ERROR_RERUN;
635 LYXERR(Debug::LATEX, "Force rerun.");
637 } else if (contains(token, "Etaremune labels have changed")) {
638 retval |= ERROR_RERUN;
639 LYXERR(Debug::LATEX, "Force rerun.");
640 } else if (contains(token, "Citation")
641 && contains(token, "on page")
642 && contains(token, "undefined")) {
645 } else if (prefixIs(token, "Package")) {
647 retval |= PACKAGE_WARNING;
648 if (contains(token, "natbib Warning:")) {
650 if (contains(token, "Citation")
651 && contains(token, "on page")
652 && contains(token, "undefined")) {
655 } else if (contains(token, "run BibTeX")) {
657 } else if (contains(token, "Rerun LaTeX") ||
658 contains(token, "Please rerun LaTeX") ||
659 contains(token, "Rerun to get")) {
660 // at least longtable.sty and bibtopic.sty
662 LYXERR(Debug::LATEX, "We should rerun.");
665 } else if (prefixIs(token, "LETTRE WARNING:")) {
666 if (contains(token, "veuillez recompiler")) {
668 LYXERR(Debug::LATEX, "We should rerun.");
671 } else if (token[0] == '(') {
672 if (contains(token, "Rerun LaTeX") ||
673 contains(token, "Rerun to get")) {
675 LYXERR(Debug::LATEX, "We should rerun.");
678 } else if (prefixIs(token, "! ")
680 && regex_match(token, sub, file_line_error)
681 && !contains(token, "pdfTeX warning"))) {
682 // Ok, we have something that looks like a TeX Error
683 // but what do we really have.
685 // Just get the error description:
687 if (prefixIs(token, "! "))
688 desc = string(token, 2);
691 if (contains(token, "LaTeX Error:"))
692 retval |= LATEX_ERROR;
694 // bug 6445. At this point its not clear we finish with error.
695 if (prefixIs(token, "! File ended while scanning")){
696 wait_for_error = desc;
699 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
700 retval |= LATEX_ERROR;
703 errstr = wait_for_error;
705 if (!getline(ifs, tmp))
707 errstr += "\n" + tmp;
710 } while (!contains(tmp, "(job aborted"));
713 from_local8bit("Emergency stop"),
714 from_local8bit(errstr));
721 if (!getline(ifs, tmp))
725 } while (!prefixIs(tmp, "l."));
726 if (prefixIs(tmp, "l.")) {
727 // we have a latex error
730 "Package babel Error: You haven't defined the language") ||
732 "Package babel Error: You haven't loaded the option"))
733 retval |= ERROR_RERUN;
734 // get the line number:
736 sscanf(tmp.c_str(), "l.%d", &line);
737 // get the rest of the message:
738 string errstr(tmp, tmp.find(' '));
741 while (!contains(errstr, "l.")
743 && !prefixIs(tmp, "! ")
744 && !contains(tmp, "(job aborted")) {
749 LYXERR(Debug::LATEX, "line: " << line << '\n'
750 << "Desc: " << desc << '\n' << "Text: " << errstr);
751 if (line == last_line)
757 if (line_count <= 5) {
759 // We have no idea what the encoding of
761 // It seems that the output from the
762 // latex compiler itself is pure ASCII,
763 // but it can include bits from the
764 // document, so whatever encoding we
765 // assume here it can be wrong.
766 terr.insertError(line,
767 from_local8bit(desc),
768 from_local8bit(errstr));
773 // information messages, TeX warnings and other
774 // warnings we have not caught earlier.
775 if (prefixIs(token, "Overfull ")) {
776 retval |= TEX_WARNING;
777 } else if (prefixIs(token, "Underfull ")) {
778 retval |= TEX_WARNING;
779 } else if (contains(token, "Rerun to get citations")) {
780 // Natbib seems to use this.
782 } else if (contains(token, "No pages of output")) {
783 // A dvi file was not created
785 } else if (contains(token, "That makes 100 errors")) {
786 // More than 100 errors were reprted
787 retval |= TOO_MANY_ERRORS;
788 } else if (prefixIs(token, "!pdfTeX error:")){
789 // otherwise we dont catch e.g.:
790 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
793 from_local8bit("pdfTeX Error"),
794 from_local8bit(token));
798 LYXERR(Debug::LATEX, "Log line: " << token);
805 bool insertIfExists(FileName const & absname, DepTable & head)
807 if (absname.exists() && !absname.isDirectory()) {
808 head.insert(absname, true);
815 bool handleFoundFile(string const & ff, DepTable & head)
817 // convert from native os path to unix path
818 string foundfile = os::internal_path(trim(ff));
820 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
822 // Ok now we found a file.
823 // Now we should make sure that this is a file that we can
824 // access through the normal paths.
825 // We will not try any fancy search methods to
828 // (1) foundfile is an
829 // absolute path and should
832 if (FileName::isAbsolute(foundfile)) {
833 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
834 // On initial insert we want to do the update at once
835 // since this file cannot be a file generated by
837 absname.set(foundfile);
838 if (!insertIfExists(absname, head)) {
840 string strippedfile = foundfile;
841 while (contains(strippedfile, " ")) {
842 // files with spaces are often enclosed in quotation
843 // marks; those have to be removed
844 string unquoted = subst(strippedfile, "\"", "");
845 absname.set(unquoted);
846 if (insertIfExists(absname, head))
848 // strip off part after last space and try again
849 string tmp = strippedfile;
850 string const stripoff =
851 rsplit(tmp, strippedfile, ' ');
852 absname.set(strippedfile);
853 if (insertIfExists(absname, head))
859 string onlyfile = onlyFileName(foundfile);
860 absname = makeAbsPath(onlyfile);
863 while (contains(foundfile, ' ')) {
864 if (absname.exists())
868 // files with spaces are often enclosed in quotation
869 // marks; those have to be removed
870 string unquoted = subst(foundfile, "\"", "");
871 absname = makeAbsPath(unquoted);
872 if (absname.exists())
874 // strip off part after last space and try again
876 string const stripoff =
877 rsplit(foundfile, strippedfile, ' ');
878 foundfile = strippedfile;
879 onlyfile = onlyFileName(strippedfile);
880 absname = makeAbsPath(onlyfile);
884 // (2) foundfile is in the tmpdir
885 // insert it into head
886 if (absname.exists() && !absname.isDirectory()) {
887 // FIXME: This regex contained glo, but glo is used by the old
888 // version of nomencl.sty. Do we need to put it back?
889 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
890 if (regex_match(onlyfile, unwanted)) {
891 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
892 << " in the dep file");
893 } else if (suffixIs(onlyfile, ".tex")) {
894 // This is a tex file generated by LyX
895 // and latex is not likely to change this
897 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
898 head.insert(absname, true);
900 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
901 head.insert(absname);
905 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
911 bool checkLineBreak(string const & ff, DepTable & head)
913 if (!contains(ff, '.'))
916 // if we have a dot, we let handleFoundFile decide
917 return handleFoundFile(ff, head);
923 void LaTeX::deplog(DepTable & head)
925 // This function reads the LaTeX log file end extracts all the
926 // external files used by the LaTeX run. The files are then
927 // entered into the dependency file.
929 string const logfile =
930 onlyFileName(changeExtension(file.absFileName(), ".log"));
932 static regex const reg1("File: (.+).*");
933 static regex const reg2("No file (.+)(.).*");
934 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
935 // If an index should be created, MikTex does not write a line like
936 // \openout# = 'sample.idx'.
937 // but instead only a line like this into the log:
938 // Writing index file sample.idx
939 static regex const reg4("Writing index file (.+).*");
940 // files also can be enclosed in <...>
941 static regex const reg5("<([^>]+)(.).*");
942 static regex const regoldnomencl("Writing glossary file (.+).*");
943 static regex const regnomencl("Writing nomenclature file (.+).*");
944 // If a toc should be created, MikTex does not write a line like
945 // \openout# = `sample.toc'.
946 // but only a line like this into the log:
948 // This line is also written by tetex.
949 // This line is not present if no toc should be created.
950 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
951 static regex const reg6(".*\\([^)]+.*");
953 FileName const fn = makeAbsPath(logfile);
954 ifstream ifs(fn.toFilesystemEncoding().c_str());
957 // Ok, the scanning of files here is not sufficient.
958 // Sometimes files are named by "File:� xxx" only
959 // So I think we should use some regexps to find files instead.
960 // Note: all file names and paths might contains spaces.
961 bool found_file = false;
964 // MikTeX sometimes inserts \0 in the log file. They can't be
965 // removed directly with the existing string utility
966 // functions, so convert them first to \r, and remove all
967 // \r's afterwards, since we need to remove them anyway.
968 token = subst(token, '\0', '\r');
969 token = subst(token, "\r", "");
970 if (token.empty() || token == ")") {
975 // Sometimes, filenames are broken across lines.
976 // We care for that and save suspicious lines.
977 // Here we exclude some cases where we are sure
978 // that there is no continued filename
979 if (!lastline.empty()) {
980 static regex const package_info("Package \\w+ Info: .*");
981 static regex const package_warning("Package \\w+ Warning: .*");
982 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
983 || prefixIs(token, "Package:")
984 || prefixIs(token, "Language:")
985 || prefixIs(token, "LaTeX Info:")
986 || prefixIs(token, "LaTeX Font Info:")
987 || prefixIs(token, "\\openout[")
988 || prefixIs(token, "))")
989 || regex_match(token, package_info)
990 || regex_match(token, package_warning))
994 if (!lastline.empty())
995 // probably a continued filename from last line
996 token = lastline + token;
997 if (token.length() > 255) {
998 // string too long. Cut off.
999 token.erase(0, token.length() - 251);
1004 // FIXME UNICODE: We assume that the file names in the log
1005 // file are in the file system encoding.
1006 token = to_utf8(from_filesystem8bit(token));
1008 // (1) "File: file.ext"
1009 if (regex_match(token, sub, reg1)) {
1011 found_file = checkLineBreak(sub.str(1), head);
1013 if (suffixIs(token, ")"))
1014 // no line break for sure
1015 // pretend we've been successfully searching
1017 // (2) "No file file.ext"
1018 } else if (regex_match(token, sub, reg2)) {
1019 // file names must contains a dot, line ends with dot
1020 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1021 found_file = handleFoundFile(sub.str(1), head);
1023 // we suspect a line break
1025 // (3) "\openout<nr> = `file.ext'."
1026 } else if (regex_match(token, sub, reg3)) {
1027 // search for closing '. at the end of the line
1028 if (sub.str(2) == "\'.")
1029 found_file = handleFoundFile(sub.str(1), head);
1031 // probable line break
1033 // (4) "Writing index file file.ext"
1034 } else if (regex_match(token, sub, reg4))
1036 found_file = checkLineBreak(sub.str(1), head);
1038 else if (regex_match(token, sub, reg5)) {
1039 // search for closing '>' and dot ('*.*>') at the eol
1040 if (contains(sub.str(1), '.') && sub.str(2) == ">")
1041 found_file = handleFoundFile(sub.str(1), head);
1043 // probable line break
1045 // (6) "Writing nomenclature file file.ext"
1046 } else if (regex_match(token, sub, regnomencl) ||
1047 regex_match(token, sub, regoldnomencl))
1049 found_file = checkLineBreak(sub.str(1), head);
1050 // (7) "\tf@toc=\write<nr>" (for MikTeX)
1051 else if (regex_match(token, sub, miktexTocReg))
1052 found_file = handleFoundFile(onlyFileName(changeExtension(
1053 file.absFileName(), ".toc")), head);
1055 // not found, but we won't check further
1056 // pretend we've been successfully searching
1060 // note that we can have several of these on one line
1061 // this must be queried separated, because of
1062 // cases such as "File: file.ext (type eps)"
1063 // where "File: file.ext" would be skipped
1064 if (regex_match(token, sub, reg6)) {
1065 // search for strings in (...)
1066 static regex reg6_1("\\(([^()]+)(.)");
1068 string::const_iterator first = token.begin();
1069 string::const_iterator end = token.end();
1071 while (regex_search(first, end, what, reg6_1)) {
1072 // if we have a dot, try to handle as file
1073 if (contains(what.str(1), '.')) {
1074 first = what[0].second;
1075 if (what.str(2) == ")") {
1076 handleFoundFile(what.str(1), head);
1077 // since we had a closing bracket,
1078 // do not investigate further
1081 // if we have no closing bracket,
1082 // try to handle as file nevertheless
1083 found_file = handleFoundFile(
1084 what.str(1) + what.str(2), head);
1086 // if we do not have a dot, check if the line has
1087 // a closing bracket (else, we suspect a line break)
1088 else if (what.str(2) != ")") {
1089 first = what[0].second;
1092 // we have a closing bracket, so the content
1093 // is not a file name.
1094 // no need to investigate further
1095 // pretend we've been successfully searching
1096 first = what[0].second;
1103 // probable linebreak:
1107 // no linebreak: reset
1108 lastline = string();
1111 // Make sure that the main .tex file is in the dependency file.
1112 head.insert(file, true);