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"
24 #include "support/debug.h"
25 #include "support/convert.h"
26 #include "support/FileName.h"
27 #include "support/filetools.h"
28 #include "support/gettext.h"
29 #include "support/lstrings.h"
30 #include "support/Systemcall.h"
31 #include "support/os.h"
33 #include "support/regex.h"
40 using namespace lyx::support;
44 namespace os = support::os;
46 // TODO: in no particular order
47 // - get rid of the call to
48 // BufferList::updateIncludedTeXfiles, this should either
49 // be done before calling LaTeX::funcs or in a completely
51 // - the makeindex style files should be taken care of with
52 // the dependency mechanism.
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 void TeXErrors::insertRef(int line, docstring const & error_desc,
77 docstring const & error_text,
78 string const & child_name)
80 Error newerr(line, error_desc, error_text, child_name);
81 undef_ref.push_back(newerr);
85 bool operator==(AuxInfo const & a, AuxInfo const & o)
87 return a.aux_file == o.aux_file
88 && a.citations == o.citations
89 && a.databases == o.databases
90 && a.styles == o.styles;
94 bool operator!=(AuxInfo const & a, AuxInfo const & o)
104 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
105 FileName const & f, string const & p, string const & lp,
106 bool allow_cancellation, bool const clean_start)
107 : cmd(latex), file(f), path(p), lpath(lp), runparams(rp), biber(false),
108 allow_cancel(allow_cancellation)
111 // lualatex can still produce a DVI with --output-format=dvi. However,
112 // we do not use that internally (we use the "dvilualatex" command) so
113 // it would only happen from a custom converter. Thus, it is better to
114 // guess that lualatex produces a PDF than to guess a DVI.
115 // FIXME we should base the extension on the output format, which we should
116 // get in a robust way, e.g. from the converter.
117 if (prefixIs(cmd, "pdf") || prefixIs(cmd, "lualatex") || prefixIs(cmd, "xelatex")) {
118 depfile = FileName(file.absFileName() + ".dep-pdf");
120 FileName(changeExtension(file.absFileName(), ".pdf"));
122 depfile = FileName(file.absFileName() + ".dep");
124 FileName(changeExtension(file.absFileName(), ".dvi"));
127 removeAuxiliaryFiles();
131 void LaTeX::removeAuxiliaryFiles() const
133 // Note that we do not always call this function when there is an error.
134 // For example, if there is an error but an output file is produced we
135 // still would like to output (export/view) the file.
137 // What files do we have to delete?
139 // This will at least make latex do all the runs
140 depfile.removeFile();
142 // but the reason for the error might be in a generated file...
145 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
149 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
153 FileName const ind(changeExtension(file.absFileName(), ".ind"));
157 FileName const nls(changeExtension(file.absFileName(), ".nls"));
160 // nomencl file (old version of the package)
161 FileName const gls(changeExtension(file.absFileName(), ".gls"));
165 FileName const ent(changeExtension(file.absFileName(), ".ent"));
168 // Also remove the aux file
169 FileName const aux(changeExtension(file.absFileName(), ".aux"));
172 // Also remove the .out file (e.g. hyperref bookmarks) (#9963)
173 FileName const out(changeExtension(file.absFileName(), ".out"));
176 // Remove the output file, which is often generated even if error
177 output_file.removeFile();
181 int LaTeX::run(TeXErrors & terr)
182 // We know that this function will only be run if the lyx buffer
183 // has been changed. We also know that a newly written .tex file
184 // is always different from the previous one because of the date
185 // in it. However it seems safe to run latex (at least) one time
186 // each time the .tex file changes.
188 int scanres = NO_ERRORS;
189 int bscanres = NO_ERRORS;
190 unsigned int count = 0; // number of times run
191 num_errors = 0; // just to make sure.
192 unsigned int const MAX_RUN = 6;
193 DepTable head; // empty head
194 bool rerun = false; // rerun requested
196 // The class LaTeX does not know the temp path.
197 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
201 // first check if the file dependencies exist:
202 // ->If it does exist
203 // check if any of the files mentioned in it have
204 // changed (done using a checksum).
206 // run latex once and
207 // remake the dependency file
208 // -> if not changed:
209 // just return there is nothing to do for us.
210 // ->if it doesn't exist
212 // run latex once (we need to run latex once anyway) and
213 // remake the dependency file.
216 bool had_depfile = depfile.exists();
217 bool run_bibtex = false;
218 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
221 LYXERR(Debug::DEPEND, "Dependency file exists");
222 // Read the dep file:
223 had_depfile = head.read(depfile);
227 // Update the checksums
229 // Can't just check if anything has changed because it might
230 // have aborted on error last time... in which cas we need
231 // to re-run latex and collect the error messages
232 // (even if they are the same).
233 if (!output_file.exists()) {
234 LYXERR(Debug::DEPEND,
235 "re-running LaTeX because output file doesn't exist.");
236 } else if (!head.sumchange()) {
237 LYXERR(Debug::DEPEND, "return no_change");
240 LYXERR(Debug::DEPEND, "Dependency file has changed");
243 if (head.extchanged(".bib") || head.extchanged(".bst"))
246 LYXERR(Debug::DEPEND,
247 "Dependency file does not exist, or has wrong format");
249 /// We scan the aux file even when had_depfile = false,
250 /// because we can run pdflatex on the file after running latex on it,
251 /// in which case we will not need to run bibtex again.
252 vector<AuxInfo> bibtex_info_old;
254 bibtex_info_old = scanAuxFiles(aux_file, runparams.only_childbibs);
257 LYXERR(Debug::LATEX, "Run #" << count);
258 message(runMessage(count));
260 int exit_code = startscript();
261 if (exit_code == Systemcall::KILLED)
262 return Systemcall::KILLED;
264 scanres = scanLogFile(terr);
265 if (scanres & ERROR_RERUN) {
266 LYXERR(Debug::LATEX, "Rerunning LaTeX");
268 exit_code = startscript();
269 if (exit_code == Systemcall::KILLED)
270 return Systemcall::KILLED;
271 scanres = scanLogFile(terr);
274 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file, runparams.only_childbibs);
275 if (!run_bibtex && bibtex_info_old != bibtex_info)
278 // update the dependencies.
279 deplog(head); // reads the latex log
283 // At this point we must run external programs if needed.
284 // makeindex will be run if a .idx file changed or was generated.
285 // And if there were undefined citations or changes in references
286 // the .aux file is checked for signs of bibtex. Bibtex is then run
289 // memoir (at least) writes an empty *idx file in the first place.
290 // A second latex run is needed.
291 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
292 rerun = idxfile.exists() && idxfile.isFileEmpty();
295 if (head.haschanged(idxfile)) {
297 LYXERR(Debug::LATEX, "Running MakeIndex.");
298 message(_("Running Index Processor."));
299 // onlyFileName() is needed for cygwin
301 runMakeIndex(onlyFileName(idxfile.absFileName()), runparams);
302 if (ret == Systemcall::KILLED)
303 return Systemcall::KILLED;
307 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
308 // If all nomencl entries are removed, nomencl writes an empty nlo file.
309 // DepTable::hasChanged() returns false in this case, since it does not
310 // distinguish empty files from non-existing files. This is why we need
311 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
312 // FIXME: Sort out the real problem in DepTable.
313 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty())) {
314 int const ret = runMakeIndexNomencl(file, ".nlo", ".nls");
315 if (ret == Systemcall::KILLED)
316 return Systemcall::KILLED;
320 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
321 if (head.haschanged(glofile)) {
322 int const ret = runMakeIndexNomencl(file, ".glo", ".gls");
329 // check if we're using biber instead of bibtex
330 // biber writes no info to the aux file, so we just check
331 // if a bcf file exists (and if it was updated)
332 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
333 biber |= head.exist(bcffile);
336 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
337 if (scanres & UNDEF_CIT || run_bibtex) {
338 // Here we must scan the .aux file and look for
339 // "\bibdata" and/or "\bibstyle". If one of those
340 // tags is found -> run bibtex and set rerun = true;
342 LYXERR(Debug::LATEX, "Running BibTeX.");
343 message(_("Running BibTeX."));
344 updateBibtexDependencies(head, bibtex_info);
346 rerun |= runBibTeX(bibtex_info, runparams, exit_code);
347 if (exit_code == Systemcall::KILLED)
348 return Systemcall::KILLED;
349 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
350 if (blgfile.exists())
351 bscanres = scanBlgFile(head, terr);
352 } else if (!had_depfile) {
353 /// If we run pdflatex on the file after running latex on it,
354 /// then we do not need to run bibtex, but we do need to
355 /// insert the .bib and .bst files into the .dep-pdf file.
356 updateBibtexDependencies(head, bibtex_info);
360 // we know on this point that latex has been run once (or we just
361 // returned) and the question now is to decide if we need to run
362 // it any more. This is done by asking if any of the files in the
363 // dependency file has changed. (remember that the checksum for
364 // a given file is reported to have changed if it just was created)
365 // -> if changed or rerun == true:
366 // run latex once more and
367 // update the dependency structure
368 // -> if not changed:
369 // we do nothing at this point
371 if (rerun || head.sumchange()) {
374 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
375 LYXERR(Debug::LATEX, "Run #" << count);
376 message(runMessage(count));
377 int exit_code = startscript();
378 if (exit_code == Systemcall::KILLED)
379 return Systemcall::KILLED;
380 scanres = scanLogFile(terr);
382 // update the depedencies
383 deplog(head); // reads the latex log
386 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
391 // Complex bibliography packages such as Biblatex require
392 // an additional bibtex cycle sometimes.
393 if (scanres & UNDEF_CIT) {
394 // Here we must scan the .aux file and look for
395 // "\bibdata" and/or "\bibstyle". If one of those
396 // tags is found -> run bibtex and set rerun = true;
398 LYXERR(Debug::LATEX, "Running BibTeX.");
399 message(_("Running BibTeX."));
400 updateBibtexDependencies(head, bibtex_info);
402 rerun |= runBibTeX(bibtex_info, runparams, exit_code);
403 if (exit_code == Systemcall::KILLED)
404 return Systemcall::KILLED;
405 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
406 if (blgfile.exists())
407 bscanres = scanBlgFile(head, terr);
411 // The inclusion of files generated by external programs such as
412 // makeindex or bibtex might have done changes to pagenumbering,
413 // etc. And because of this we must run the external programs
414 // again to make sure everything is redone correctly.
415 // Also there should be no need to run the external programs any
418 // run makeindex if the <file>.idx has changed or was generated.
419 if (head.haschanged(idxfile)) {
421 LYXERR(Debug::LATEX, "Running MakeIndex.");
422 message(_("Running Index Processor."));
423 // onlyFileName() is needed for cygwin
424 int const ret = runMakeIndex(onlyFileName(changeExtension(
425 file.absFileName(), ".idx")), runparams);
426 if (ret == Systemcall::KILLED)
427 return Systemcall::KILLED;
431 // MSVC complains that bool |= int is unsafe. Not sure why.
432 if (head.haschanged(nlofile))
433 rerun |= (runMakeIndexNomencl(file, ".nlo", ".nls") != 0);
434 if (head.haschanged(glofile))
435 rerun |= (runMakeIndexNomencl(file, ".glo", ".gls") != 0);
438 // we will only run latex more if the log file asks for it.
439 // or if the sumchange() is true.
440 // -> rerun asked for:
442 // remake the dependency file
443 // goto 2 or return if max runs are reached.
444 // -> rerun not asked for:
445 // just return (fall out of bottom of func)
447 while ((head.sumchange() || rerun || (scanres & RERUN))
448 && count < MAX_RUN) {
449 // Yes rerun until message goes away, or until
450 // MAX_RUNS are reached.
453 LYXERR(Debug::LATEX, "Run #" << count);
454 message(runMessage(count));
456 scanres = scanLogFile(terr);
462 // Write the dependencies to file.
466 // add flag here, just before return, instead of when exit_code
467 // is defined because scanres is sometimes overwritten above
469 scanres |= NONZERO_ERROR;
472 LYXERR(Debug::LATEX, "Done.");
474 if (bscanres & ERRORS)
475 return bscanres; // return on error
481 int LaTeX::startscript()
483 // onlyFileName() is needed for cygwin
484 string tmp = cmd + ' '
485 + quoteName(onlyFileName(file.toFilesystemEncoding()))
486 + " > " + os::nulldev();
488 Systemcall::Starttype const starttype =
489 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
490 return one.startscript(starttype, tmp, path, lpath, true);
494 int LaTeX::runMakeIndex(string const & f, OutputParams const & rp,
495 string const & params)
497 string tmp = rp.use_japanese ?
498 lyxrc.jindex_command : lyxrc.index_command;
500 if (!rp.index_command.empty())
501 tmp = rp.index_command;
504 "idx file has been made, running index processor ("
505 << tmp << ") on file " << f);
507 tmp = subst(tmp, "$$lang", rp.document_language);
508 if (rp.use_indices) {
509 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
511 "Multiple indices. Using splitindex command: " << tmp);
517 Systemcall::Starttype const starttype =
518 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
519 return one.startscript(starttype, tmp, path, lpath, true);
523 int LaTeX::runMakeIndexNomencl(FileName const & fname,
524 string const & nlo, string const & nls)
526 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
527 message(_("Running MakeIndex for nomencl."));
528 string tmp = lyxrc.nomencl_command + ' ';
529 // onlyFileName() is needed for cygwin
530 tmp += quoteName(onlyFileName(changeExtension(fname.absFileName(), nlo)));
532 + onlyFileName(changeExtension(fname.toFilesystemEncoding(), nls));
534 Systemcall::Starttype const starttype =
535 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
536 return one.startscript(starttype, tmp, path, lpath, true);
540 vector<AuxInfo> const
541 LaTeX::scanAuxFiles(FileName const & fname, bool const only_childbibs)
543 vector<AuxInfo> result;
545 // With chapterbib, we have to bibtex all children's aux files
546 // but _not_ the master's!
547 if (only_childbibs) {
548 for (string const &s: children) {
550 makeAbsPath(s, fname.onlyPath().realPath());
551 fn.changeExtension("aux");
553 result.push_back(scanAuxFile(fn));
558 result.push_back(scanAuxFile(fname));
560 // This is for bibtopic
561 string const basename = removeExtension(fname.absFileName());
562 for (int i = 1; i < 1000; ++i) {
563 FileName const file2(basename
564 + '.' + convert<string>(i)
568 result.push_back(scanAuxFile(file2));
574 AuxInfo const LaTeX::scanAuxFile(FileName const & fname)
577 result.aux_file = fname;
578 scanAuxFile(fname, result);
583 void LaTeX::scanAuxFile(FileName const & fname, AuxInfo & aux_info)
585 LYXERR(Debug::LATEX, "Scanning aux file: " << fname);
587 ifstream ifs(fname.toFilesystemEncoding().c_str());
589 static regex const reg1("\\\\citation\\{([^}]+)\\}");
590 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
591 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
592 static regex const reg4("\\\\@input\\{([^}]+)\\}");
594 while (getline(ifs, token)) {
595 token = rtrim(token, "\r");
597 // FIXME UNICODE: We assume that citation keys and filenames
598 // in the aux file are in the file system encoding.
599 token = to_utf8(from_filesystem8bit(token));
600 if (regex_match(token, sub, reg1)) {
601 string data = sub.str(1);
602 while (!data.empty()) {
604 data = split(data, citation, ',');
605 LYXERR(Debug::LATEX, "Citation: " << citation);
606 aux_info.citations.insert(citation);
608 } else if (regex_match(token, sub, reg2)) {
609 string data = sub.str(1);
610 // data is now all the bib files separated by ','
611 // get them one by one and pass them to the helper
612 while (!data.empty()) {
614 data = split(data, database, ',');
615 database = changeExtension(database, "bib");
616 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
617 aux_info.databases.insert(database);
619 } else if (regex_match(token, sub, reg3)) {
620 string style = sub.str(1);
621 // token is now the style file
622 // pass it to the helper
623 style = changeExtension(style, "bst");
624 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
625 aux_info.styles.insert(style);
626 } else if (regex_match(token, sub, reg4)) {
627 string const file2 = sub.str(1);
628 scanAuxFile(makeAbsPath(file2), aux_info);
634 void LaTeX::updateBibtexDependencies(DepTable & dep,
635 vector<AuxInfo> const & bibtex_info)
637 // Since a run of Bibtex mandates more latex runs it is ok to
638 // remove all ".bib" and ".bst" files.
639 dep.remove_files_with_extension(".bib");
640 dep.remove_files_with_extension(".bst");
641 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
643 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
644 it != bibtex_info.end(); ++it) {
645 for (set<string>::const_iterator it2 = it->databases.begin();
646 it2 != it->databases.end(); ++it2) {
647 FileName const file = findtexfile(*it2, "bib");
649 dep.insert(file, true);
652 for (set<string>::const_iterator it2 = it->styles.begin();
653 it2 != it->styles.end(); ++it2) {
654 FileName const file = findtexfile(*it2, "bst");
656 dep.insert(file, true);
660 // biber writes nothing into the aux file.
661 // Instead, we have to scan the blg file
664 scanBlgFile(dep, terr);
669 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
670 OutputParams const & rp, int & exit_code)
674 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
675 it != bibtex_info.end(); ++it) {
676 if (!biber && it->databases.empty())
680 string tmp = rp.bibtex_command;
682 // onlyFileName() is needed for cygwin
683 tmp += quoteName(onlyFileName(removeExtension(
684 it->aux_file.absFileName())));
686 Systemcall::Starttype const starttype =
687 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
688 exit_code = one.startscript(starttype, tmp, path, lpath, true);
693 // Return whether bibtex was run
698 //helper func for scanLogFile; gets line number X from strings "... on input line X ..."
699 //returns 0 if none is found
700 int getLineNumber(const string &token){
701 string l = support::token(token, ' ', tokenPos(token,' ',"line") + 1);
702 return l.empty() ? 0 : convert<int>(l);
706 int LaTeX::scanLogFile(TeXErrors & terr)
710 int retval = NO_ERRORS;
712 onlyFileName(changeExtension(file.absFileName(), ".log"));
713 LYXERR(Debug::LATEX, "Log file: " << tmp);
714 FileName const fn = FileName(makeAbsPath(tmp));
715 // FIXME we should use an ifdocstream here and a docstring for token
716 // below. The encoding of the log file depends on the _output_ (font)
717 // encoding of the TeX file (T1, TU etc.). See #10728.
718 ifstream ifs(fn.toFilesystemEncoding().c_str());
719 bool fle_style = false;
720 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
721 static regex const child_file("[^0-9]*([0-9]+[A-Za-z]*_.+\\.tex).*");
722 // Flag for 'File ended while scanning' message.
723 // We need to wait for subsequent processing.
724 string wait_for_error;
727 stack <pair<string, int> > child;
733 while (getline(ifs, token)) {
734 // MikTeX sometimes inserts \0 in the log file. They can't be
735 // removed directly with the existing string utility
736 // functions, so convert them first to \r, and remove all
737 // \r's afterwards, since we need to remove them anyway.
738 token = subst(token, '\0', '\r');
739 token = subst(token, "\r", "");
742 LYXERR(Debug::LATEX, "Log line: " << token);
747 // Track child documents
748 for (size_t i = 0; i < token.length(); ++i) {
749 if (token[i] == '(') {
751 size_t j = token.find('(', i + 1);
752 size_t len = j == string::npos
753 ? token.substr(i + 1).length()
755 string const substr = token.substr(i + 1, len);
756 if (regex_match(substr, sub, child_file)) {
757 string const name = sub.str(1);
758 // Sometimes also masters have a name that matches
759 // (if their name starts with a number and _)
760 if (name != file.onlyFileName()) {
761 child.push(make_pair(name, pnest));
762 children.push_back(name);
766 } else if (token[i] == ')') {
768 && child.top().second == pnest)
773 child_name = child.empty() ? empty_string() : child.top().first;
775 if (contains(token, "file:line:error style messages enabled"))
778 //Handles both "LaTeX Warning:" & "Package natbib Warning:"
779 //Various handlers for missing citations below won't catch the problem if citation
780 //key is long (>~25chars), because pdflatex splits output at line length 80.
781 //TODO: TL 2020 engines will contain new commandline switch --cnf-line which we
782 //can use to set max_print_line variable for appropriate length and detect all
784 if (contains(token, "There were undefined citations.") ||
785 prefixIs(token, "Package biblatex Warning: The following entry could not be found"))
788 if (prefixIs(token, "LaTeX Warning:") ||
789 prefixIs(token, "! pdfTeX warning")) {
790 // Here shall we handle different
792 retval |= LATEX_WARNING;
793 LYXERR(Debug::LATEX, "LaTeX Warning.");
794 if (contains(token, "Rerun to get cross-references")) {
796 LYXERR(Debug::LATEX, "We should rerun.");
797 // package clefval needs 2 latex runs before bibtex
798 } else if (contains(token, "Value of")
799 && contains(token, "on page")
800 && contains(token, "undefined")) {
801 retval |= ERROR_RERUN;
802 LYXERR(Debug::LATEX, "Force rerun.");
804 } else if (contains(token, "Etaremune labels have changed")) {
805 retval |= ERROR_RERUN;
806 LYXERR(Debug::LATEX, "Force rerun.");
808 } else if (contains(token, "Endnotes may have changed. Rerun")) {
810 LYXERR(Debug::LATEX, "We should rerun.");
811 //"Citation `cit' on page X undefined on input line X."
812 } else if (contains(token, "Citation")
813 //&& contains(token, "on input line") //often split to newline
814 && contains(token, "undefined")) {
816 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
817 from_utf8(token), child_name);
818 //"Reference `X' on page Y undefined on input line Z."
819 } else if (contains(token, "Reference")
820 //&& contains(token, "on input line")) //often split to new line
821 && contains(token, "undefined")) {
823 terr.insertRef(getLineNumber(token), from_ascii("Reference undefined"),
824 from_utf8(token), child_name);
826 //If label is too long pdlaftex log line splitting will make the above fail
827 //so we catch at least this generic statement occuring for both CIT & REF.
828 } else if (contains(token, "There were undefined references.")) {
829 if (!(retval & UNDEF_CIT)) //if not handled already
833 } else if (prefixIs(token, "Package")) {
835 retval |= PACKAGE_WARNING;
836 if (contains(token, "natbib Warning:")) {
838 if (contains(token, "Citation")
839 && contains(token, "on page")
840 && contains(token, "undefined")) {
842 //Unf only keys up to ~6 chars will make it due to line splits
843 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
844 from_utf8(token), child_name);
846 } else if (contains(token, "run BibTeX")) {
848 } else if (contains(token, "run Biber")) {
851 } else if (contains(token, "Rerun LaTeX") ||
852 contains(token, "Please rerun LaTeX") ||
853 contains(token, "Rerun to get")) {
854 // at least longtable.sty and bibtopic.sty
856 LYXERR(Debug::LATEX, "We should rerun.");
859 } else if (prefixIs(token, "LETTRE WARNING:")) {
860 if (contains(token, "veuillez recompiler")) {
862 LYXERR(Debug::LATEX, "We should rerun.");
865 } else if (token[0] == '(') {
866 if (contains(token, "Rerun LaTeX") ||
867 contains(token, "Rerun to get")) {
869 LYXERR(Debug::LATEX, "We should rerun.");
872 } else if (prefixIs(token, "! ")
874 && regex_match(token, sub, file_line_error)
875 && !contains(token, "pdfTeX warning"))) {
876 // Ok, we have something that looks like a TeX Error
877 // but what do we really have.
879 // Just get the error description:
881 if (prefixIs(token, "! "))
882 desc = string(token, 2);
885 if (contains(token, "LaTeX Error:"))
886 retval |= LATEX_ERROR;
888 if (prefixIs(token, "! File ended while scanning")) {
889 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
890 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
891 retval |= ERROR_RERUN;
892 LYXERR(Debug::LATEX, "Force rerun.");
894 // bug 6445. At this point its not clear we finish with error.
895 wait_for_error = desc;
900 if (prefixIs(token, "! Incomplete \\if")) {
901 // bug 10666. At this point its not clear we finish with error.
902 wait_for_error = desc;
906 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
907 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
908 retval |= ERROR_RERUN;
909 LYXERR(Debug::LATEX, "Force rerun.");
912 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
913 retval |= LATEX_ERROR;
916 errstr = wait_for_error;
917 wait_for_error.clear();
919 if (!getline(ifs, tmp))
921 tmp = rtrim(tmp, "\r");
922 errstr += "\n" + tmp;
925 } while (!contains(tmp, "(job aborted"));
928 from_ascii("Emergency stop"),
929 from_local8bit(errstr),
936 if (!getline(ifs, tmp))
938 tmp = rtrim(tmp, "\r");
939 // 15 is somewhat arbitrarily chosen, based on practice.
940 // We used 10 for 14 years and increased it to 15 when we
944 } while (!prefixIs(tmp, "l."));
945 if (prefixIs(tmp, "l.")) {
946 // we have a latex error
949 "Package babel Error: You haven't defined the language")
951 "Package babel Error: You haven't loaded the option")
953 "Package babel Error: Unknown language"))
954 retval |= ERROR_RERUN;
955 // get the line number:
957 sscanf(tmp.c_str(), "l.%d", &line);
958 // get the rest of the message:
959 string errstr(tmp, tmp.find(' '));
962 tmp = rtrim(tmp, "\r");
963 while (!contains(errstr, "l.")
965 && !prefixIs(tmp, "! ")
966 && !contains(tmp, "(job aborted")) {
970 tmp = rtrim(tmp, "\r");
972 LYXERR(Debug::LATEX, "line: " << line << '\n'
973 << "Desc: " << desc << '\n' << "Text: " << errstr);
974 if (line == last_line)
980 if (line_count <= 5) {
982 // We have no idea what the encoding of
984 // It seems that the output from the
985 // latex compiler itself is pure ASCII,
986 // but it can include bits from the
987 // document, so whatever encoding we
988 // assume here it can be wrong.
989 terr.insertError(line,
990 from_local8bit(desc),
991 from_local8bit(errstr),
997 // information messages, TeX warnings and other
998 // warnings we have not caught earlier.
999 if (prefixIs(token, "Overfull ")) {
1000 retval |= TEX_WARNING;
1001 } else if (prefixIs(token, "Underfull ")) {
1002 retval |= TEX_WARNING;
1003 } else if (contains(token, "Rerun to get citations")) {
1004 // Natbib seems to use this.
1005 retval |= UNDEF_CIT;
1006 } else if (contains(token, "No pages of output")
1007 || contains(token, "no pages of output")) {
1008 // No output file (e.g. the DVI or PDF) was created
1009 retval |= NO_OUTPUT;
1010 } else if (contains(token, "Error 256 (driver return code)")) {
1011 // This is a xdvipdfmx driver error reported by XeTeX.
1012 // We have to check whether an output PDF file was created.
1013 FileName pdffile = file;
1014 pdffile.changeExtension("pdf");
1015 if (!pdffile.exists())
1016 // No output PDF file was created (see #10076)
1017 retval |= NO_OUTPUT;
1018 } else if (contains(token, "That makes 100 errors")) {
1019 // More than 100 errors were reported
1020 retval |= TOO_MANY_ERRORS;
1021 } else if (prefixIs(token, "!pdfTeX error:")) {
1022 // otherwise we dont catch e.g.:
1023 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
1026 from_ascii("pdfTeX Error"),
1027 from_local8bit(token),
1029 } else if (!ignore_missing_glyphs
1030 && prefixIs(token, "Missing character: There is no ")
1031 && !contains(token, "nullfont")) {
1032 // Warning about missing glyph in selected font
1033 // may be dataloss (bug 9610)
1034 // but can be ignored for 'nullfont' (bug 10394).
1035 // as well as for ZERO WIDTH NON-JOINER (0x200C) which is
1036 // missing in many fonts and output for ligature break (bug 10727).
1037 // Since this error only occurs with utf8 output, we can safely assume
1038 // that the log file is utf8-encoded
1039 docstring const utoken = from_utf8(token);
1040 if (!contains(utoken, 0x200C)) {
1041 retval |= LATEX_ERROR;
1043 from_ascii("Missing glyphs!"),
1047 } else if (!wait_for_error.empty()) {
1048 // We collect information until we know we have an error.
1049 wait_for_error += token + '\n';
1053 LYXERR(Debug::LATEX, "Log line: " << token);
1060 bool insertIfExists(FileName const & absname, DepTable & head)
1062 if (absname.exists() && !absname.isDirectory()) {
1063 head.insert(absname, true);
1070 bool handleFoundFile(string const & ff, DepTable & head)
1072 // convert from native os path to unix path
1073 string foundfile = os::internal_path(trim(ff));
1075 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
1077 // Ok now we found a file.
1078 // Now we should make sure that this is a file that we can
1079 // access through the normal paths.
1080 // We will not try any fancy search methods to
1083 // (1) foundfile is an
1084 // absolute path and should
1087 if (FileName::isAbsolute(foundfile)) {
1088 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
1089 // On initial insert we want to do the update at once
1090 // since this file cannot be a file generated by
1092 absname.set(foundfile);
1093 if (!insertIfExists(absname, head)) {
1095 string strippedfile = foundfile;
1096 while (contains(strippedfile, " ")) {
1097 // files with spaces are often enclosed in quotation
1098 // marks; those have to be removed
1099 string unquoted = subst(strippedfile, "\"", "");
1100 absname.set(unquoted);
1101 if (insertIfExists(absname, head))
1103 // strip off part after last space and try again
1104 string tmp = strippedfile;
1105 rsplit(tmp, strippedfile, ' ');
1106 absname.set(strippedfile);
1107 if (insertIfExists(absname, head))
1113 string onlyfile = onlyFileName(foundfile);
1114 absname = makeAbsPath(onlyfile);
1117 while (contains(foundfile, ' ')) {
1118 if (absname.exists())
1122 // files with spaces are often enclosed in quotation
1123 // marks; those have to be removed
1124 string unquoted = subst(foundfile, "\"", "");
1125 absname = makeAbsPath(unquoted);
1126 if (absname.exists())
1128 // strip off part after last space and try again
1129 string strippedfile;
1130 rsplit(foundfile, strippedfile, ' ');
1131 foundfile = strippedfile;
1132 onlyfile = onlyFileName(strippedfile);
1133 absname = makeAbsPath(onlyfile);
1137 // (2) foundfile is in the tmpdir
1138 // insert it into head
1139 if (absname.exists() && !absname.isDirectory()) {
1140 // FIXME: This regex contained glo, but glo is used by the old
1141 // version of nomencl.sty. Do we need to put it back?
1142 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1143 if (regex_match(onlyfile, unwanted)) {
1144 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1145 << " in the dep file");
1146 } else if (suffixIs(onlyfile, ".tex")) {
1147 // This is a tex file generated by LyX
1148 // and latex is not likely to change this
1150 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1151 head.insert(absname, true);
1153 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1154 head.insert(absname);
1158 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1164 bool completeFilename(string const & ff, DepTable & head)
1166 // If we do not find a dot, we suspect
1167 // a fragmental file name
1168 if (!contains(ff, '.'))
1171 // if we have a dot, we let handleFoundFile decide
1172 return handleFoundFile(ff, head);
1176 int iterateLine(string const & token, regex const & reg, string const & opening,
1177 string const & closing, int fragment_pos, DepTable & head)
1180 string::const_iterator first = token.begin();
1181 string::const_iterator end = token.end();
1182 bool fragment = false;
1185 while (regex_search(first, end, what, reg)) {
1186 // if we have a dot, try to handle as file
1187 if (contains(what.str(1), '.')) {
1188 first = what[0].second;
1189 if (what.str(2) == closing) {
1190 handleFoundFile(what.str(1), head);
1191 // since we had a closing bracket,
1192 // do not investigate further
1194 } else if (what.str(2) == opening) {
1195 // if we have another opening bracket,
1196 // we might have a nested file chain
1197 // as is (file.ext (subfile.ext))
1198 fragment = !handleFoundFile(rtrim(what.str(1)), head);
1199 // decrease first position by one in order to
1200 // consider the opening delimiter on next iteration
1201 if (first > token.begin())
1204 // if we have no closing bracket,
1205 // try to handle as file nevertheless
1206 fragment = !handleFoundFile(
1207 what.str(1) + what.str(2), head);
1209 // if we do not have a dot, check if the line has
1210 // a closing bracket (else, we suspect a line break)
1211 else if (what.str(2) != closing) {
1212 first = what[0].second;
1215 // we have a closing bracket, so the content
1216 // is not a file name.
1217 // no need to investigate further
1218 first = what[0].second;
1221 last_match = what.str(1);
1224 // We need to consider the result from previous line iterations:
1225 // We might not find a fragment here, but another one might follow
1226 // E.g.: (filename.ext) <filenam
1227 // Vice versa, we consider the search completed if a real match
1228 // follows a potential fragment from a previous iteration.
1229 // E.g. <some text we considered a fragment (filename.ext)
1230 // result = -1 means we did not find a fragment!
1232 int last_match_pos = -1;
1233 if (!last_match.empty() && token.find(last_match) != string::npos)
1234 last_match_pos = int(token.find(last_match));
1236 if (last_match_pos > fragment_pos)
1237 result = last_match_pos;
1239 result = fragment_pos;
1241 if (last_match_pos < fragment_pos)
1242 result = fragment_pos;
1250 void LaTeX::deplog(DepTable & head)
1252 // This function reads the LaTeX log file end extracts all the
1253 // external files used by the LaTeX run. The files are then
1254 // entered into the dependency file.
1256 string const logfile =
1257 onlyFileName(changeExtension(file.absFileName(), ".log"));
1259 static regex const reg1("File: (.+).*");
1260 static regex const reg2("No file (.+)(.).*");
1261 static regex const reg3a("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1262 // LuaTeX has a slightly different output
1263 static regex const reg3b("\\\\openout[0-9]+.*=\\s*(.+)");
1264 // If an index should be created, MikTex does not write a line like
1265 // \openout# = 'sample.idx'.
1266 // but instead only a line like this into the log:
1267 // Writing index file sample.idx
1268 static regex const reg4("Writing index file (.+).*");
1269 static regex const regoldnomencl("Writing glossary file (.+).*");
1270 static regex const regnomencl(".*Writing nomenclature file (.+).*");
1271 // If a toc should be created, MikTex does not write a line like
1272 // \openout# = `sample.toc'.
1273 // but only a line like this into the log:
1275 // This line is also written by tetex.
1276 // This line is not present if no toc should be created.
1277 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1278 // file names can be enclosed in <...> (anywhere on the line)
1279 static regex const reg5(".*<[^>]+.*");
1280 // and also (...) anywhere on the line
1281 static regex const reg6(".*\\([^)]+.*");
1283 FileName const fn = makeAbsPath(logfile);
1284 ifstream ifs(fn.toFilesystemEncoding().c_str());
1287 // Ok, the scanning of files here is not sufficient.
1288 // Sometimes files are named by "File: xxx" only
1289 // Therefore we use some regexps to find files instead.
1290 // Note: all file names and paths might contains spaces.
1291 // Also, file names might be broken across lines. Therefore
1292 // we mark (potential) fragments and merge those lines.
1293 bool fragment = false;
1295 getline(ifs, token);
1296 // MikTeX sometimes inserts \0 in the log file. They can't be
1297 // removed directly with the existing string utility
1298 // functions, so convert them first to \r, and remove all
1299 // \r's afterwards, since we need to remove them anyway.
1300 token = subst(token, '\0', '\r');
1301 token = subst(token, "\r", "");
1302 if (token.empty() || token == ")") {
1303 lastline = string();
1307 // FIXME UNICODE: We assume that the file names in the log
1308 // file are in the file system encoding.
1309 token = to_utf8(from_filesystem8bit(token));
1311 // Sometimes, filenames are broken across lines.
1312 // We care for that and save suspicious lines.
1313 // Here we exclude some cases where we are sure
1314 // that there is no continued filename
1315 if (!lastline.empty()) {
1316 static regex const package_info("Package \\w+ Info: .*");
1317 static regex const package_warning("Package \\w+ Warning: .*");
1318 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1319 || prefixIs(token, "Package:")
1320 || prefixIs(token, "Language:")
1321 || prefixIs(token, "LaTeX Info:")
1322 || prefixIs(token, "LaTeX Font Info:")
1323 || prefixIs(token, "\\openout[")
1324 || prefixIs(token, "))")
1325 || regex_match(token, package_info)
1326 || regex_match(token, package_warning))
1327 lastline = string();
1330 if (!lastline.empty())
1331 // probably a continued filename from last line
1332 token = lastline + token;
1333 if (token.length() > 255) {
1334 // string too long. Cut off.
1335 token.erase(0, token.length() - 251);
1340 // (1) "File: file.ext"
1341 if (regex_match(token, sub, reg1)) {
1342 // is this a fragmental file name?
1343 fragment = !completeFilename(sub.str(1), head);
1345 if (suffixIs(token, ")"))
1346 // no fragment for sure
1348 // (2) "No file file.ext"
1349 } else if (regex_match(token, sub, reg2)) {
1350 // file names must contains a dot, line ends with dot
1351 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1352 fragment = !handleFoundFile(sub.str(1), head);
1354 // we suspect a line break
1356 // (3)(a) "\openout<nr> = `file.ext'."
1357 } else if (regex_match(token, sub, reg3a)) {
1358 // search for closing '. at the end of the line
1359 if (sub.str(2) == "\'.")
1360 fragment = !handleFoundFile(sub.str(1), head);
1362 // potential fragment
1364 // (3)(b) "\openout<nr> = file.ext" (LuaTeX)
1365 } else if (regex_match(token, sub, reg3b)) {
1366 // file names must contains a dot
1367 if (contains(sub.str(1), '.'))
1368 fragment = !handleFoundFile(sub.str(1), head);
1370 // potential fragment
1372 // (4) "Writing index file file.ext"
1373 } else if (regex_match(token, sub, reg4))
1374 // fragmential file name?
1375 fragment = !completeFilename(sub.str(1), head);
1376 // (5) "Writing nomenclature file file.ext"
1377 else if (regex_match(token, sub, regnomencl) ||
1378 regex_match(token, sub, regoldnomencl))
1379 // fragmental file name?
1380 fragment= !completeFilename(sub.str(1), head);
1381 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1382 else if (regex_match(token, sub, miktexTocReg))
1383 fragment = !handleFoundFile(onlyFileName(changeExtension(
1384 file.absFileName(), ".toc")), head);
1386 // not found, but we won't check further
1389 int fragment_pos = -1;
1391 // We can have several of these on one line
1392 // (and in addition to those above)
1393 if (regex_match(token, sub, reg5)) {
1394 // search for strings in <...>
1395 static regex const reg5_1("<([^>]+)(.)");
1396 fragment_pos = iterateLine(token, reg5_1, "<", ">",
1397 fragment_pos, head);
1398 fragment = (fragment_pos != -1);
1402 // We can have several of these on one line
1403 // this must be queried separated, because of
1404 // cases such as "File: file.ext (type eps)"
1405 // where "File: file.ext" would be skipped
1406 if (regex_match(token, sub, reg6)) {
1407 // search for strings in (...)
1408 static regex const reg6_1("\\(([^()]+)(.)");
1409 fragment_pos = iterateLine(token, reg6_1, "(", ")",
1410 fragment_pos, head);
1411 fragment = (fragment_pos != -1);
1415 // probable linebreak within file name:
1419 // no linebreak: reset
1420 lastline = string();
1423 // Make sure that the main .tex file is in the dependency file.
1424 head.insert(file, true);
1428 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1430 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1431 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1433 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1435 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1436 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1437 static regex const bibtexError2("^(.*---while reading file).*$");
1438 static regex const bibtexError3("(A bad cross reference---).*");
1439 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1440 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1441 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1442 int retval = NO_ERRORS;
1445 while (getline(ifs, token)) {
1446 token = rtrim(token, "\r");
1448 // FIXME UNICODE: We assume that citation keys and filenames
1449 // in the aux file are in the file system encoding.
1450 token = to_utf8(from_filesystem8bit(token));
1451 if (regex_match(token, sub, reg1)) {
1452 string data = sub.str(3);
1453 if (!data.empty()) {
1454 LYXERR(Debug::LATEX, "Found bib file: " << data);
1455 handleFoundFile(data, dep);
1458 else if (regex_match(token, sub, bibtexError)
1459 || regex_match(token, sub, bibtexError2)
1460 || regex_match(token, sub, bibtexError4)
1461 || regex_match(token, sub, bibtexError5)) {
1462 retval |= BIBTEX_ERROR;
1463 string errstr = N_("BibTeX error: ") + token;
1465 if ((prefixIs(token, "while executing---line")
1466 || prefixIs(token, "---line ")
1467 || prefixIs(token, "*Please notify the BibTeX"))
1468 && !prevtoken.empty()) {
1469 errstr = N_("BibTeX error: ") + prevtoken;
1470 msg = prevtoken + '\n';
1474 from_local8bit(errstr),
1475 from_local8bit(msg));
1476 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1477 retval |= BIBTEX_ERROR;
1478 string errstr = N_("BibTeX error: ") + prevtoken;
1479 string msg = prevtoken + '\n' + token;
1481 from_local8bit(errstr),
1482 from_local8bit(msg));
1483 } else if (regex_match(token, sub, biberError)) {
1484 retval |= BIBTEX_ERROR;
1485 string errstr = N_("Biber error: ") + sub.str(2);
1488 from_local8bit(errstr),
1489 from_local8bit(msg));