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.
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,
68 string const & child_name)
70 Error newerr(line, error_desc, error_text, child_name);
71 errors.push_back(newerr);
75 bool operator==(AuxInfo const & a, AuxInfo const & o)
77 return a.aux_file == o.aux_file
78 && a.citations == o.citations
79 && a.databases == o.databases
80 && a.styles == o.styles;
84 bool operator!=(AuxInfo const & a, AuxInfo const & o)
94 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
95 FileName const & f, string const & p, string const & lp,
96 bool const clean_start)
97 : cmd(latex), file(f), path(p), lpath(lp), runparams(rp), biber(false)
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"));
110 removeAuxiliaryFiles();
114 void LaTeX::removeAuxiliaryFiles() const
116 // Note that we do not always call this function when there is an error.
117 // For example, if there is an error but an output file is produced we
118 // still would like to output (export/view) the file.
120 // What files do we have to delete?
122 // This will at least make latex do all the runs
123 depfile.removeFile();
125 // but the reason for the error might be in a generated file...
128 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
132 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
136 FileName const ind(changeExtension(file.absFileName(), ".ind"));
140 FileName const nls(changeExtension(file.absFileName(), ".nls"));
143 // nomencl file (old version of the package)
144 FileName const gls(changeExtension(file.absFileName(), ".gls"));
147 // Also remove the aux file
148 FileName const aux(changeExtension(file.absFileName(), ".aux"));
151 // Also remove the .out file (e.g. hyperref bookmarks) (#9963)
152 FileName const out(changeExtension(file.absFileName(), ".out"));
155 // Remove the output file, which is often generated even if error
156 output_file.removeFile();
160 int LaTeX::run(TeXErrors & terr)
161 // We know that this function will only be run if the lyx buffer
162 // has been changed. We also know that a newly written .tex file
163 // is always different from the previous one because of the date
164 // in it. However it seems safe to run latex (at least) one time
165 // each time the .tex file changes.
167 int scanres = NO_ERRORS;
168 int bscanres = NO_ERRORS;
169 unsigned int count = 0; // number of times run
170 num_errors = 0; // just to make sure.
171 unsigned int const MAX_RUN = 6;
172 DepTable head; // empty head
173 bool rerun = false; // rerun requested
175 // The class LaTeX does not know the temp path.
176 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
180 // first check if the file dependencies exist:
181 // ->If it does exist
182 // check if any of the files mentioned in it have
183 // changed (done using a checksum).
185 // run latex once and
186 // remake the dependency file
187 // -> if not changed:
188 // just return there is nothing to do for us.
189 // ->if it doesn't exist
191 // run latex once (we need to run latex once anyway) and
192 // remake the dependency file.
195 bool had_depfile = depfile.exists();
196 bool run_bibtex = false;
197 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
200 LYXERR(Debug::DEPEND, "Dependency file exists");
201 // Read the dep file:
202 had_depfile = head.read(depfile);
206 // Update the checksums
208 // Can't just check if anything has changed because it might
209 // have aborted on error last time... in which cas we need
210 // to re-run latex and collect the error messages
211 // (even if they are the same).
212 if (!output_file.exists()) {
213 LYXERR(Debug::DEPEND,
214 "re-running LaTeX because output file doesn't exist.");
215 } else if (!head.sumchange()) {
216 LYXERR(Debug::DEPEND, "return no_change");
219 LYXERR(Debug::DEPEND, "Dependency file has changed");
222 if (head.extchanged(".bib") || head.extchanged(".bst"))
225 LYXERR(Debug::DEPEND,
226 "Dependency file does not exist, or has wrong format");
228 /// We scan the aux file even when had_depfile = false,
229 /// because we can run pdflatex on the file after running latex on it,
230 /// in which case we will not need to run bibtex again.
231 vector<AuxInfo> bibtex_info_old;
233 bibtex_info_old = scanAuxFiles(aux_file);
236 LYXERR(Debug::LATEX, "Run #" << count);
237 message(runMessage(count));
239 int exit_code = startscript();
241 scanres = scanLogFile(terr);
242 if (scanres & ERROR_RERUN) {
243 LYXERR(Debug::LATEX, "Rerunning LaTeX");
245 exit_code = startscript();
246 scanres = scanLogFile(terr);
249 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
250 if (!run_bibtex && bibtex_info_old != bibtex_info)
253 // update the dependencies.
254 deplog(head); // reads the latex log
258 // At this point we must run external programs if needed.
259 // makeindex will be run if a .idx file changed or was generated.
260 // And if there were undefined citations or changes in references
261 // the .aux file is checked for signs of bibtex. Bibtex is then run
264 // memoir (at least) writes an empty *idx file in the first place.
265 // A second latex run is needed.
266 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
267 rerun = idxfile.exists() && idxfile.isFileEmpty();
270 if (head.haschanged(idxfile)) {
272 LYXERR(Debug::LATEX, "Running MakeIndex.");
273 message(_("Running Index Processor."));
274 // onlyFileName() is needed for cygwin
275 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
278 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
279 // If all nomencl entries are removed, nomencl writes an empty nlo file.
280 // DepTable::hasChanged() returns false in this case, since it does not
281 // distinguish empty files from non-existing files. This is why we need
282 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
283 // FIXME: Sort out the real problem in DepTable.
284 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
285 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
286 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
287 if (head.haschanged(glofile))
288 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
290 // check if we're using biber instead of bibtex
291 // biber writes no info to the aux file, so we just check
292 // if a bcf file exists (and if it was updated)
293 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
294 biber |= head.exist(bcffile);
297 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
298 if (scanres & UNDEF_CIT || run_bibtex) {
299 // Here we must scan the .aux file and look for
300 // "\bibdata" and/or "\bibstyle". If one of those
301 // tags is found -> run bibtex and set rerun = true;
303 LYXERR(Debug::LATEX, "Running BibTeX.");
304 message(_("Running BibTeX."));
305 updateBibtexDependencies(head, bibtex_info);
306 rerun |= runBibTeX(bibtex_info, runparams);
307 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
308 if (blgfile.exists())
309 bscanres = scanBlgFile(head, terr);
310 } else if (!had_depfile) {
311 /// If we run pdflatex on the file after running latex on it,
312 /// then we do not need to run bibtex, but we do need to
313 /// insert the .bib and .bst files into the .dep-pdf file.
314 updateBibtexDependencies(head, bibtex_info);
318 // we know on this point that latex has been run once (or we just
319 // returned) and the question now is to decide if we need to run
320 // it any more. This is done by asking if any of the files in the
321 // dependency file has changed. (remember that the checksum for
322 // a given file is reported to have changed if it just was created)
323 // -> if changed or rerun == true:
324 // run latex once more and
325 // update the dependency structure
326 // -> if not changed:
327 // we do nothing at this point
329 if (rerun || head.sumchange()) {
332 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
333 LYXERR(Debug::LATEX, "Run #" << count);
334 message(runMessage(count));
336 scanres = scanLogFile(terr);
338 // update the depedencies
339 deplog(head); // reads the latex log
342 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
347 // Complex bibliography packages such as Biblatex require
348 // an additional bibtex cycle sometimes.
349 if (scanres & UNDEF_CIT) {
350 // Here we must scan the .aux file and look for
351 // "\bibdata" and/or "\bibstyle". If one of those
352 // tags is found -> run bibtex and set rerun = true;
354 LYXERR(Debug::LATEX, "Running BibTeX.");
355 message(_("Running BibTeX."));
356 updateBibtexDependencies(head, bibtex_info);
357 rerun |= runBibTeX(bibtex_info, runparams);
358 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
359 if (blgfile.exists())
360 bscanres = scanBlgFile(head, terr);
364 // The inclusion of files generated by external programs such as
365 // makeindex or bibtex might have done changes to pagenumbering,
366 // etc. And because of this we must run the external programs
367 // again to make sure everything is redone correctly.
368 // Also there should be no need to run the external programs any
371 // run makeindex if the <file>.idx has changed or was generated.
372 if (head.haschanged(idxfile)) {
374 LYXERR(Debug::LATEX, "Running MakeIndex.");
375 message(_("Running Index Processor."));
376 // onlyFileName() is needed for cygwin
377 rerun = runMakeIndex(onlyFileName(changeExtension(
378 file.absFileName(), ".idx")), runparams);
381 // I am not pretty sure if need this twice.
382 if (head.haschanged(nlofile))
383 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
384 if (head.haschanged(glofile))
385 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
388 // we will only run latex more if the log file asks for it.
389 // or if the sumchange() is true.
390 // -> rerun asked for:
392 // remake the dependency file
393 // goto 2 or return if max runs are reached.
394 // -> rerun not asked for:
395 // just return (fall out of bottom of func)
397 while ((head.sumchange() || rerun || (scanres & RERUN))
398 && count < MAX_RUN) {
399 // Yes rerun until message goes away, or until
400 // MAX_RUNS are reached.
403 LYXERR(Debug::LATEX, "Run #" << count);
404 message(runMessage(count));
406 scanres = scanLogFile(terr);
412 // Write the dependencies to file.
416 // add flag here, just before return, instead of when exit_code
417 // is defined because scanres is sometimes overwritten above
419 scanres |= NONZERO_ERROR;
422 LYXERR(Debug::LATEX, "Done.");
424 if (bscanres & ERRORS)
425 return bscanres; // return on error
431 int LaTeX::startscript()
433 // onlyFileName() is needed for cygwin
434 string tmp = cmd + ' '
435 + quoteName(onlyFileName(file.toFilesystemEncoding()))
436 + " > " + os::nulldev();
438 return one.startscript(Systemcall::Wait, tmp, path, lpath);
442 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
443 string const & params)
445 string tmp = runparams.use_japanese ?
446 lyxrc.jindex_command : lyxrc.index_command;
448 if (!runparams.index_command.empty())
449 tmp = runparams.index_command;
452 "idx file has been made, running index processor ("
453 << tmp << ") on file " << f);
455 tmp = subst(tmp, "$$lang", runparams.document_language);
456 if (runparams.use_indices) {
457 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
459 "Multiple indices. Using splitindex command: " << tmp);
465 one.startscript(Systemcall::Wait, tmp, path, lpath);
470 bool LaTeX::runMakeIndexNomencl(FileName const & file,
471 string const & nlo, string const & nls)
473 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
474 message(_("Running MakeIndex for nomencl."));
475 string tmp = lyxrc.nomencl_command + ' ';
476 // onlyFileName() is needed for cygwin
477 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
479 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
481 one.startscript(Systemcall::Wait, tmp, path, lpath);
486 vector<AuxInfo> const
487 LaTeX::scanAuxFiles(FileName const & file)
489 vector<AuxInfo> result;
491 result.push_back(scanAuxFile(file));
493 string const basename = removeExtension(file.absFileName());
494 for (int i = 1; i < 1000; ++i) {
495 FileName const file2(basename
496 + '.' + convert<string>(i)
500 result.push_back(scanAuxFile(file2));
506 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
509 result.aux_file = file;
510 scanAuxFile(file, result);
515 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
517 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
519 ifstream ifs(file.toFilesystemEncoding().c_str());
521 static regex const reg1("\\\\citation\\{([^}]+)\\}");
522 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
523 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
524 static regex const reg4("\\\\@input\\{([^}]+)\\}");
526 while (getline(ifs, token)) {
527 token = rtrim(token, "\r");
529 // FIXME UNICODE: We assume that citation keys and filenames
530 // in the aux file are in the file system encoding.
531 token = to_utf8(from_filesystem8bit(token));
532 if (regex_match(token, sub, reg1)) {
533 string data = sub.str(1);
534 while (!data.empty()) {
536 data = split(data, citation, ',');
537 LYXERR(Debug::LATEX, "Citation: " << citation);
538 aux_info.citations.insert(citation);
540 } else if (regex_match(token, sub, reg2)) {
541 string data = sub.str(1);
542 // data is now all the bib files separated by ','
543 // get them one by one and pass them to the helper
544 while (!data.empty()) {
546 data = split(data, database, ',');
547 database = changeExtension(database, "bib");
548 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
549 aux_info.databases.insert(database);
551 } else if (regex_match(token, sub, reg3)) {
552 string style = sub.str(1);
553 // token is now the style file
554 // pass it to the helper
555 style = changeExtension(style, "bst");
556 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
557 aux_info.styles.insert(style);
558 } else if (regex_match(token, sub, reg4)) {
559 string const file2 = sub.str(1);
560 scanAuxFile(makeAbsPath(file2), aux_info);
566 void LaTeX::updateBibtexDependencies(DepTable & dep,
567 vector<AuxInfo> const & bibtex_info)
569 // Since a run of Bibtex mandates more latex runs it is ok to
570 // remove all ".bib" and ".bst" files.
571 dep.remove_files_with_extension(".bib");
572 dep.remove_files_with_extension(".bst");
573 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
575 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
576 it != bibtex_info.end(); ++it) {
577 for (set<string>::const_iterator it2 = it->databases.begin();
578 it2 != it->databases.end(); ++it2) {
579 FileName const file = findtexfile(*it2, "bib");
581 dep.insert(file, true);
584 for (set<string>::const_iterator it2 = it->styles.begin();
585 it2 != it->styles.end(); ++it2) {
586 FileName const file = findtexfile(*it2, "bst");
588 dep.insert(file, true);
592 // biber writes nothing into the aux file.
593 // Instead, we have to scan the blg file
596 scanBlgFile(dep, terr);
601 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
602 OutputParams const & runparams)
605 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
606 it != bibtex_info.end(); ++it) {
607 if (!biber && it->databases.empty())
611 string tmp = runparams.use_japanese ?
612 lyxrc.jbibtex_command : lyxrc.bibtex_command;
614 if (!runparams.bibtex_command.empty())
615 tmp = runparams.bibtex_command;
617 // onlyFileName() is needed for cygwin
618 tmp += quoteName(onlyFileName(removeExtension(
619 it->aux_file.absFileName())));
621 one.startscript(Systemcall::Wait, tmp, path, lpath);
623 // Return whether bibtex was run
628 int LaTeX::scanLogFile(TeXErrors & terr)
632 int retval = NO_ERRORS;
634 onlyFileName(changeExtension(file.absFileName(), ".log"));
635 LYXERR(Debug::LATEX, "Log file: " << tmp);
636 FileName const fn = FileName(makeAbsPath(tmp));
637 ifstream ifs(fn.toFilesystemEncoding().c_str());
638 bool fle_style = false;
639 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
640 static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
641 // Flag for 'File ended while scanning' message.
642 // We need to wait for subsequent processing.
643 string wait_for_error;
646 stack <pair<string, int> > child;
649 while (getline(ifs, token)) {
650 // MikTeX sometimes inserts \0 in the log file. They can't be
651 // removed directly with the existing string utility
652 // functions, so convert them first to \r, and remove all
653 // \r's afterwards, since we need to remove them anyway.
654 token = subst(token, '\0', '\r');
655 token = subst(token, "\r", "");
658 LYXERR(Debug::LATEX, "Log line: " << token);
663 // Track child documents
664 for (size_t i = 0; i < token.length(); ++i) {
665 if (token[i] == '(') {
667 size_t j = token.find('(', i + 1);
668 size_t len = j == string::npos
669 ? token.substr(i + 1).length()
671 string const substr = token.substr(i + 1, len);
672 if (regex_match(substr, sub, child_file)) {
673 string const name = sub.str(1);
674 child.push(make_pair(name, pnest));
677 } else if (token[i] == ')') {
679 && child.top().second == pnest)
684 child_name = child.empty() ? empty_string() : child.top().first;
686 if (contains(token, "file:line:error style messages enabled"))
689 if (prefixIs(token, "LaTeX Warning:") ||
690 prefixIs(token, "! pdfTeX warning")) {
691 // Here shall we handle different
693 retval |= LATEX_WARNING;
694 LYXERR(Debug::LATEX, "LaTeX Warning.");
695 if (contains(token, "Rerun to get cross-references")) {
697 LYXERR(Debug::LATEX, "We should rerun.");
698 // package clefval needs 2 latex runs before bibtex
699 } else if (contains(token, "Value of")
700 && contains(token, "on page")
701 && contains(token, "undefined")) {
702 retval |= ERROR_RERUN;
703 LYXERR(Debug::LATEX, "Force rerun.");
705 } else if (contains(token, "Etaremune labels have changed")) {
706 retval |= ERROR_RERUN;
707 LYXERR(Debug::LATEX, "Force rerun.");
708 } else if (contains(token, "Citation")
709 && contains(token, "on page")
710 && contains(token, "undefined")) {
712 } else if (contains(token, "Citation")
713 && contains(token, "on input line")
714 && contains(token, "undefined")) {
717 } else if (prefixIs(token, "Package")) {
719 retval |= PACKAGE_WARNING;
720 if (contains(token, "natbib Warning:")) {
722 if (contains(token, "Citation")
723 && contains(token, "on page")
724 && contains(token, "undefined")) {
727 } else if (contains(token, "run BibTeX")) {
729 } else if (contains(token, "run Biber")) {
732 } else if (contains(token, "Rerun LaTeX") ||
733 contains(token, "Please rerun LaTeX") ||
734 contains(token, "Rerun to get")) {
735 // at least longtable.sty and bibtopic.sty
737 LYXERR(Debug::LATEX, "We should rerun.");
740 } else if (prefixIs(token, "LETTRE WARNING:")) {
741 if (contains(token, "veuillez recompiler")) {
743 LYXERR(Debug::LATEX, "We should rerun.");
746 } else if (token[0] == '(') {
747 if (contains(token, "Rerun LaTeX") ||
748 contains(token, "Rerun to get")) {
750 LYXERR(Debug::LATEX, "We should rerun.");
753 } else if (prefixIs(token, "! ")
755 && regex_match(token, sub, file_line_error)
756 && !contains(token, "pdfTeX warning"))) {
757 // Ok, we have something that looks like a TeX Error
758 // but what do we really have.
760 // Just get the error description:
762 if (prefixIs(token, "! "))
763 desc = string(token, 2);
766 if (contains(token, "LaTeX Error:"))
767 retval |= LATEX_ERROR;
769 if (prefixIs(token, "! File ended while scanning")){
770 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
771 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
772 retval |= ERROR_RERUN;
773 LYXERR(Debug::LATEX, "Force rerun.");
775 // bug 6445. At this point its not clear we finish with error.
776 wait_for_error = desc;
781 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
782 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
783 retval |= ERROR_RERUN;
784 LYXERR(Debug::LATEX, "Force rerun.");
787 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
788 retval |= LATEX_ERROR;
791 errstr = wait_for_error;
793 if (!getline(ifs, tmp))
795 tmp = rtrim(tmp, "\r");
796 errstr += "\n" + tmp;
799 } while (!contains(tmp, "(job aborted"));
802 from_local8bit("Emergency stop"),
803 from_local8bit(errstr),
811 if (!getline(ifs, tmp))
813 tmp = rtrim(tmp, "\r");
814 // 15 is somewhat arbitrarily chosen, based on practice.
815 // We used 10 for 14 years and increased it to 15 when we
819 } while (!prefixIs(tmp, "l."));
820 if (prefixIs(tmp, "l.")) {
821 // we have a latex error
824 "Package babel Error: You haven't defined the language")
826 "Package babel Error: You haven't loaded the option")
828 "Package babel Error: Unknown language"))
829 retval |= ERROR_RERUN;
830 // get the line number:
832 sscanf(tmp.c_str(), "l.%d", &line);
833 // get the rest of the message:
834 string errstr(tmp, tmp.find(' '));
837 tmp = rtrim(tmp, "\r");
838 while (!contains(errstr, "l.")
840 && !prefixIs(tmp, "! ")
841 && !contains(tmp, "(job aborted")) {
845 tmp = rtrim(tmp, "\r");
847 LYXERR(Debug::LATEX, "line: " << line << '\n'
848 << "Desc: " << desc << '\n' << "Text: " << errstr);
849 if (line == last_line)
855 if (line_count <= 5) {
857 // We have no idea what the encoding of
859 // It seems that the output from the
860 // latex compiler itself is pure ASCII,
861 // but it can include bits from the
862 // document, so whatever encoding we
863 // assume here it can be wrong.
864 terr.insertError(line,
865 from_local8bit(desc),
866 from_local8bit(errstr),
872 // information messages, TeX warnings and other
873 // warnings we have not caught earlier.
874 if (prefixIs(token, "Overfull ")) {
875 retval |= TEX_WARNING;
876 } else if (prefixIs(token, "Underfull ")) {
877 retval |= TEX_WARNING;
878 } else if (contains(token, "Rerun to get citations")) {
879 // Natbib seems to use this.
881 } else if (contains(token, "No pages of output")) {
882 // A dvi file was not created
884 } else if (contains(token, "That makes 100 errors")) {
885 // More than 100 errors were reprted
886 retval |= TOO_MANY_ERRORS;
887 } else if (prefixIs(token, "!pdfTeX error:")) {
888 // otherwise we dont catch e.g.:
889 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
892 from_local8bit("pdfTeX Error"),
893 from_local8bit(token),
895 } else if (prefixIs(token, "Missing character: There is no ")
896 && !contains(token, "nullfont")) {
897 // Warning about missing glyph in selected font
898 // may be dataloss (bug 9610)
899 // but can be ignored for 'nullfont' (bug 10394).
900 retval |= LATEX_ERROR;
902 from_local8bit("Missing glyphs!"),
903 from_local8bit(token),
908 LYXERR(Debug::LATEX, "Log line: " << token);
915 bool insertIfExists(FileName const & absname, DepTable & head)
917 if (absname.exists() && !absname.isDirectory()) {
918 head.insert(absname, true);
925 bool handleFoundFile(string const & ff, DepTable & head)
927 // convert from native os path to unix path
928 string foundfile = os::internal_path(trim(ff));
930 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
932 // Ok now we found a file.
933 // Now we should make sure that this is a file that we can
934 // access through the normal paths.
935 // We will not try any fancy search methods to
938 // (1) foundfile is an
939 // absolute path and should
942 if (FileName::isAbsolute(foundfile)) {
943 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
944 // On initial insert we want to do the update at once
945 // since this file cannot be a file generated by
947 absname.set(foundfile);
948 if (!insertIfExists(absname, head)) {
950 string strippedfile = foundfile;
951 while (contains(strippedfile, " ")) {
952 // files with spaces are often enclosed in quotation
953 // marks; those have to be removed
954 string unquoted = subst(strippedfile, "\"", "");
955 absname.set(unquoted);
956 if (insertIfExists(absname, head))
958 // strip off part after last space and try again
959 string tmp = strippedfile;
960 string const stripoff =
961 rsplit(tmp, strippedfile, ' ');
962 absname.set(strippedfile);
963 if (insertIfExists(absname, head))
969 string onlyfile = onlyFileName(foundfile);
970 absname = makeAbsPath(onlyfile);
973 while (contains(foundfile, ' ')) {
974 if (absname.exists())
978 // files with spaces are often enclosed in quotation
979 // marks; those have to be removed
980 string unquoted = subst(foundfile, "\"", "");
981 absname = makeAbsPath(unquoted);
982 if (absname.exists())
984 // strip off part after last space and try again
986 string const stripoff =
987 rsplit(foundfile, strippedfile, ' ');
988 foundfile = strippedfile;
989 onlyfile = onlyFileName(strippedfile);
990 absname = makeAbsPath(onlyfile);
994 // (2) foundfile is in the tmpdir
995 // insert it into head
996 if (absname.exists() && !absname.isDirectory()) {
997 // FIXME: This regex contained glo, but glo is used by the old
998 // version of nomencl.sty. Do we need to put it back?
999 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1000 if (regex_match(onlyfile, unwanted)) {
1001 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1002 << " in the dep file");
1003 } else if (suffixIs(onlyfile, ".tex")) {
1004 // This is a tex file generated by LyX
1005 // and latex is not likely to change this
1007 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1008 head.insert(absname, true);
1010 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1011 head.insert(absname);
1015 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1021 bool completeFilename(string const & ff, DepTable & head)
1023 // If we do not find a dot, we suspect
1024 // a fragmental file name
1025 if (!contains(ff, '.'))
1028 // if we have a dot, we let handleFoundFile decide
1029 return handleFoundFile(ff, head);
1033 int iterateLine(string const & token, regex const & reg, string const & closing,
1034 int fragment_pos, DepTable & head)
1037 string::const_iterator first = token.begin();
1038 string::const_iterator end = token.end();
1039 bool fragment = false;
1042 while (regex_search(first, end, what, reg)) {
1043 // if we have a dot, try to handle as file
1044 if (contains(what.str(1), '.')) {
1045 first = what[0].second;
1046 if (what.str(2) == closing) {
1047 handleFoundFile(what.str(1), head);
1048 // since we had a closing bracket,
1049 // do not investigate further
1052 // if we have no closing bracket,
1053 // try to handle as file nevertheless
1054 fragment = !handleFoundFile(
1055 what.str(1) + what.str(2), head);
1057 // if we do not have a dot, check if the line has
1058 // a closing bracket (else, we suspect a line break)
1059 else if (what.str(2) != closing) {
1060 first = what[0].second;
1063 // we have a closing bracket, so the content
1064 // is not a file name.
1065 // no need to investigate further
1066 first = what[0].second;
1069 last_match = what.str(1);
1072 // We need to consider the result from previous line iterations:
1073 // We might not find a fragment here, but another one might follow
1074 // E.g.: (filename.ext) <filenam
1075 // Vice versa, we consider the search completed if a real match
1076 // follows a potential fragment from a previous iteration.
1077 // E.g. <some text we considered a fragment (filename.ext)
1078 // result = -1 means we did not find a fragment!
1080 int last_match_pos = -1;
1081 if (!last_match.empty() && token.find(last_match) != string::npos)
1082 last_match_pos = int(token.find(last_match));
1084 if (last_match_pos > fragment_pos)
1085 result = last_match_pos;
1087 result = fragment_pos;
1089 if (last_match_pos < fragment_pos)
1090 result = fragment_pos;
1098 void LaTeX::deplog(DepTable & head)
1100 // This function reads the LaTeX log file end extracts all the
1101 // external files used by the LaTeX run. The files are then
1102 // entered into the dependency file.
1104 string const logfile =
1105 onlyFileName(changeExtension(file.absFileName(), ".log"));
1107 static regex const reg1("File: (.+).*");
1108 static regex const reg2("No file (.+)(.).*");
1109 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1110 // If an index should be created, MikTex does not write a line like
1111 // \openout# = 'sample.idx'.
1112 // but instead only a line like this into the log:
1113 // Writing index file sample.idx
1114 static regex const reg4("Writing index file (.+).*");
1115 static regex const regoldnomencl("Writing glossary file (.+).*");
1116 static regex const regnomencl("Writing nomenclature file (.+).*");
1117 // If a toc should be created, MikTex does not write a line like
1118 // \openout# = `sample.toc'.
1119 // but only a line like this into the log:
1121 // This line is also written by tetex.
1122 // This line is not present if no toc should be created.
1123 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1124 // file names can be enclosed in <...> (anywhere on the line)
1125 static regex const reg5(".*<[^>]+.*");
1126 // and also (...) anywhere on the line
1127 static regex const reg6(".*\\([^)]+.*");
1129 FileName const fn = makeAbsPath(logfile);
1130 ifstream ifs(fn.toFilesystemEncoding().c_str());
1133 // Ok, the scanning of files here is not sufficient.
1134 // Sometimes files are named by "File: xxx" only
1135 // Therefore we use some regexps to find files instead.
1136 // Note: all file names and paths might contains spaces.
1137 // Also, file names might be broken across lines. Therefore
1138 // we mark (potential) fragments and merge those lines.
1139 bool fragment = false;
1141 getline(ifs, token);
1142 // MikTeX sometimes inserts \0 in the log file. They can't be
1143 // removed directly with the existing string utility
1144 // functions, so convert them first to \r, and remove all
1145 // \r's afterwards, since we need to remove them anyway.
1146 token = subst(token, '\0', '\r');
1147 token = subst(token, "\r", "");
1148 if (token.empty() || token == ")") {
1149 lastline = string();
1153 // FIXME UNICODE: We assume that the file names in the log
1154 // file are in the file system encoding.
1155 token = to_utf8(from_filesystem8bit(token));
1157 // Sometimes, filenames are broken across lines.
1158 // We care for that and save suspicious lines.
1159 // Here we exclude some cases where we are sure
1160 // that there is no continued filename
1161 if (!lastline.empty()) {
1162 static regex const package_info("Package \\w+ Info: .*");
1163 static regex const package_warning("Package \\w+ Warning: .*");
1164 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1165 || prefixIs(token, "Package:")
1166 || prefixIs(token, "Language:")
1167 || prefixIs(token, "LaTeX Info:")
1168 || prefixIs(token, "LaTeX Font Info:")
1169 || prefixIs(token, "\\openout[")
1170 || prefixIs(token, "))")
1171 || regex_match(token, package_info)
1172 || regex_match(token, package_warning))
1173 lastline = string();
1176 if (!lastline.empty())
1177 // probably a continued filename from last line
1178 token = lastline + token;
1179 if (token.length() > 255) {
1180 // string too long. Cut off.
1181 token.erase(0, token.length() - 251);
1186 // (1) "File: file.ext"
1187 if (regex_match(token, sub, reg1)) {
1188 // is this a fragmental file name?
1189 fragment = !completeFilename(sub.str(1), head);
1191 if (suffixIs(token, ")"))
1192 // no fragment for sure
1194 // (2) "No file file.ext"
1195 } else if (regex_match(token, sub, reg2)) {
1196 // file names must contains a dot, line ends with dot
1197 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1198 fragment = !handleFoundFile(sub.str(1), head);
1200 // we suspect a line break
1202 // (3) "\openout<nr> = `file.ext'."
1203 } else if (regex_match(token, sub, reg3)) {
1204 // search for closing '. at the end of the line
1205 if (sub.str(2) == "\'.")
1206 fragment = !handleFoundFile(sub.str(1), head);
1208 // potential fragment
1210 // (4) "Writing index file file.ext"
1211 } else if (regex_match(token, sub, reg4))
1212 // fragmential file name?
1213 fragment = !completeFilename(sub.str(1), head);
1214 // (5) "Writing nomenclature file file.ext"
1215 else if (regex_match(token, sub, regnomencl) ||
1216 regex_match(token, sub, regoldnomencl))
1217 // fragmental file name?
1218 fragment= !completeFilename(sub.str(1), head);
1219 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1220 else if (regex_match(token, sub, miktexTocReg))
1221 fragment = !handleFoundFile(onlyFileName(changeExtension(
1222 file.absFileName(), ".toc")), head);
1224 // not found, but we won't check further
1227 int fragment_pos = -1;
1229 // We can have several of these on one line
1230 // (and in addition to those above)
1231 if (regex_match(token, sub, reg5)) {
1232 // search for strings in <...>
1233 static regex const reg5_1("<([^>]+)(.)");
1234 fragment_pos = iterateLine(token, reg5_1, ">",
1235 fragment_pos, head);
1236 fragment = (fragment_pos != -1);
1240 // We can have several of these on one line
1241 // this must be queried separated, because of
1242 // cases such as "File: file.ext (type eps)"
1243 // where "File: file.ext" would be skipped
1244 if (regex_match(token, sub, reg6)) {
1245 // search for strings in (...)
1246 static regex const reg6_1("\\(([^()]+)(.)");
1247 fragment_pos = iterateLine(token, reg6_1, ")",
1248 fragment_pos, head);
1249 fragment = (fragment_pos != -1);
1253 // probable linebreak within file name:
1257 // no linebreak: reset
1258 lastline = string();
1261 // Make sure that the main .tex file is in the dependency file.
1262 head.insert(file, true);
1266 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1268 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1269 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1271 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1273 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1274 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1275 static regex const bibtexError2("^(.*---while reading file).*$");
1276 static regex const bibtexError3("(A bad cross reference---).*");
1277 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1278 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1279 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1280 int retval = NO_ERRORS;
1283 while (getline(ifs, token)) {
1284 token = rtrim(token, "\r");
1286 // FIXME UNICODE: We assume that citation keys and filenames
1287 // in the aux file are in the file system encoding.
1288 token = to_utf8(from_filesystem8bit(token));
1289 if (regex_match(token, sub, reg1)) {
1290 string data = sub.str(3);
1291 if (!data.empty()) {
1292 LYXERR(Debug::LATEX, "Found bib file: " << data);
1293 handleFoundFile(data, dep);
1296 else if (regex_match(token, sub, bibtexError)
1297 || regex_match(token, sub, bibtexError2)
1298 || regex_match(token, sub, bibtexError4)
1299 || regex_match(token, sub, bibtexError5)) {
1300 retval |= BIBTEX_ERROR;
1301 string errstr = N_("BibTeX error: ") + token;
1303 if ((prefixIs(token, "while executing---line")
1304 || prefixIs(token, "---line ")
1305 || prefixIs(token, "*Please notify the BibTeX"))
1306 && !prevtoken.empty()) {
1307 errstr = N_("BibTeX error: ") + prevtoken;
1308 message = prevtoken + '\n';
1312 from_local8bit(errstr),
1313 from_local8bit(message));
1314 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1315 retval |= BIBTEX_ERROR;
1316 string errstr = N_("BibTeX error: ") + prevtoken;
1317 string message = prevtoken + '\n' + token;
1319 from_local8bit(errstr),
1320 from_local8bit(message));
1321 } else if (regex_match(token, sub, biberError)) {
1322 retval |= BIBTEX_ERROR;
1323 string errstr = N_("Biber error: ") + sub.str(2);
1324 string message = token;
1326 from_local8bit(errstr),
1327 from_local8bit(message));