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"));
164 // Also remove the aux file
165 FileName const aux(changeExtension(file.absFileName(), ".aux"));
168 // Also remove the .out file (e.g. hyperref bookmarks) (#9963)
169 FileName const out(changeExtension(file.absFileName(), ".out"));
172 // Remove the output file, which is often generated even if error
173 output_file.removeFile();
177 int LaTeX::run(TeXErrors & terr)
178 // We know that this function will only be run if the lyx buffer
179 // has been changed. We also know that a newly written .tex file
180 // is always different from the previous one because of the date
181 // in it. However it seems safe to run latex (at least) one time
182 // each time the .tex file changes.
184 int scanres = NO_ERRORS;
185 int bscanres = NO_ERRORS;
186 unsigned int count = 0; // number of times run
187 num_errors = 0; // just to make sure.
188 unsigned int const MAX_RUN = 6;
189 DepTable head; // empty head
190 bool rerun = false; // rerun requested
192 // The class LaTeX does not know the temp path.
193 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
197 // first check if the file dependencies exist:
198 // ->If it does exist
199 // check if any of the files mentioned in it have
200 // changed (done using a checksum).
202 // run latex once and
203 // remake the dependency file
204 // -> if not changed:
205 // just return there is nothing to do for us.
206 // ->if it doesn't exist
208 // run latex once (we need to run latex once anyway) and
209 // remake the dependency file.
212 bool had_depfile = depfile.exists();
213 bool run_bibtex = false;
214 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
217 LYXERR(Debug::DEPEND, "Dependency file exists");
218 // Read the dep file:
219 had_depfile = head.read(depfile);
223 // Update the checksums
225 // Can't just check if anything has changed because it might
226 // have aborted on error last time... in which cas we need
227 // to re-run latex and collect the error messages
228 // (even if they are the same).
229 if (!output_file.exists()) {
230 LYXERR(Debug::DEPEND,
231 "re-running LaTeX because output file doesn't exist.");
232 } else if (!head.sumchange()) {
233 LYXERR(Debug::DEPEND, "return no_change");
236 LYXERR(Debug::DEPEND, "Dependency file has changed");
239 if (head.extchanged(".bib") || head.extchanged(".bst"))
242 LYXERR(Debug::DEPEND,
243 "Dependency file does not exist, or has wrong format");
245 /// We scan the aux file even when had_depfile = false,
246 /// because we can run pdflatex on the file after running latex on it,
247 /// in which case we will not need to run bibtex again.
248 vector<AuxInfo> bibtex_info_old;
250 bibtex_info_old = scanAuxFiles(aux_file, runparams.only_childbibs);
253 LYXERR(Debug::LATEX, "Run #" << count);
254 message(runMessage(count));
256 int exit_code = startscript();
257 if (exit_code == Systemcall::KILLED)
258 return Systemcall::KILLED;
260 scanres = scanLogFile(terr);
261 if (scanres & ERROR_RERUN) {
262 LYXERR(Debug::LATEX, "Rerunning LaTeX");
264 exit_code = startscript();
265 if (exit_code == Systemcall::KILLED)
266 return Systemcall::KILLED;
267 scanres = scanLogFile(terr);
270 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file, runparams.only_childbibs);
271 if (!run_bibtex && bibtex_info_old != bibtex_info)
274 // update the dependencies.
275 deplog(head); // reads the latex log
279 // At this point we must run external programs if needed.
280 // makeindex will be run if a .idx file changed or was generated.
281 // And if there were undefined citations or changes in references
282 // the .aux file is checked for signs of bibtex. Bibtex is then run
285 // memoir (at least) writes an empty *idx file in the first place.
286 // A second latex run is needed.
287 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
288 rerun = idxfile.exists() && idxfile.isFileEmpty();
291 if (head.haschanged(idxfile)) {
293 LYXERR(Debug::LATEX, "Running MakeIndex.");
294 message(_("Running Index Processor."));
295 // onlyFileName() is needed for cygwin
297 runMakeIndex(onlyFileName(idxfile.absFileName()), runparams);
298 if (ret == Systemcall::KILLED)
299 return Systemcall::KILLED;
303 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
304 // If all nomencl entries are removed, nomencl writes an empty nlo file.
305 // DepTable::hasChanged() returns false in this case, since it does not
306 // distinguish empty files from non-existing files. This is why we need
307 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
308 // FIXME: Sort out the real problem in DepTable.
309 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty())) {
310 int const ret = runMakeIndexNomencl(file, ".nlo", ".nls");
311 if (ret == Systemcall::KILLED)
312 return Systemcall::KILLED;
316 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
317 if (head.haschanged(glofile)) {
318 int const ret = runMakeIndexNomencl(file, ".glo", ".gls");
325 // check if we're using biber instead of bibtex
326 // biber writes no info to the aux file, so we just check
327 // if a bcf file exists (and if it was updated)
328 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
329 biber |= head.exist(bcffile);
332 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
333 if (scanres & UNDEF_CIT || run_bibtex) {
334 // Here we must scan the .aux file and look for
335 // "\bibdata" and/or "\bibstyle". If one of those
336 // tags is found -> run bibtex and set rerun = true;
338 LYXERR(Debug::LATEX, "Running BibTeX.");
339 message(_("Running BibTeX."));
340 updateBibtexDependencies(head, bibtex_info);
342 rerun |= runBibTeX(bibtex_info, runparams, exit_code);
343 if (exit_code == Systemcall::KILLED)
344 return Systemcall::KILLED;
345 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
346 if (blgfile.exists())
347 bscanres = scanBlgFile(head, terr);
348 } else if (!had_depfile) {
349 /// If we run pdflatex on the file after running latex on it,
350 /// then we do not need to run bibtex, but we do need to
351 /// insert the .bib and .bst files into the .dep-pdf file.
352 updateBibtexDependencies(head, bibtex_info);
356 // we know on this point that latex has been run once (or we just
357 // returned) and the question now is to decide if we need to run
358 // it any more. This is done by asking if any of the files in the
359 // dependency file has changed. (remember that the checksum for
360 // a given file is reported to have changed if it just was created)
361 // -> if changed or rerun == true:
362 // run latex once more and
363 // update the dependency structure
364 // -> if not changed:
365 // we do nothing at this point
367 if (rerun || head.sumchange()) {
370 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
371 LYXERR(Debug::LATEX, "Run #" << count);
372 message(runMessage(count));
373 int exit_code = startscript();
374 if (exit_code == Systemcall::KILLED)
375 return Systemcall::KILLED;
376 scanres = scanLogFile(terr);
378 // update the depedencies
379 deplog(head); // reads the latex log
382 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
387 // Complex bibliography packages such as Biblatex require
388 // an additional bibtex cycle sometimes.
389 if (scanres & UNDEF_CIT) {
390 // Here we must scan the .aux file and look for
391 // "\bibdata" and/or "\bibstyle". If one of those
392 // tags is found -> run bibtex and set rerun = true;
394 LYXERR(Debug::LATEX, "Running BibTeX.");
395 message(_("Running BibTeX."));
396 updateBibtexDependencies(head, bibtex_info);
398 rerun |= runBibTeX(bibtex_info, runparams, exit_code);
399 if (exit_code == Systemcall::KILLED)
400 return Systemcall::KILLED;
401 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
402 if (blgfile.exists())
403 bscanres = scanBlgFile(head, terr);
407 // The inclusion of files generated by external programs such as
408 // makeindex or bibtex might have done changes to pagenumbering,
409 // etc. And because of this we must run the external programs
410 // again to make sure everything is redone correctly.
411 // Also there should be no need to run the external programs any
414 // run makeindex if the <file>.idx has changed or was generated.
415 if (head.haschanged(idxfile)) {
417 LYXERR(Debug::LATEX, "Running MakeIndex.");
418 message(_("Running Index Processor."));
419 // onlyFileName() is needed for cygwin
420 int const ret = runMakeIndex(onlyFileName(changeExtension(
421 file.absFileName(), ".idx")), runparams);
422 if (ret == Systemcall::KILLED)
423 return Systemcall::KILLED;
427 // MSVC complains that bool |= int is unsafe. Not sure why.
428 if (head.haschanged(nlofile))
429 rerun |= (runMakeIndexNomencl(file, ".nlo", ".nls") != 0);
430 if (head.haschanged(glofile))
431 rerun |= (runMakeIndexNomencl(file, ".glo", ".gls") != 0);
434 // we will only run latex more if the log file asks for it.
435 // or if the sumchange() is true.
436 // -> rerun asked for:
438 // remake the dependency file
439 // goto 2 or return if max runs are reached.
440 // -> rerun not asked for:
441 // just return (fall out of bottom of func)
443 while ((head.sumchange() || rerun || (scanres & RERUN))
444 && count < MAX_RUN) {
445 // Yes rerun until message goes away, or until
446 // MAX_RUNS are reached.
449 LYXERR(Debug::LATEX, "Run #" << count);
450 message(runMessage(count));
452 scanres = scanLogFile(terr);
458 // Write the dependencies to file.
462 // add flag here, just before return, instead of when exit_code
463 // is defined because scanres is sometimes overwritten above
465 scanres |= NONZERO_ERROR;
468 LYXERR(Debug::LATEX, "Done.");
470 if (bscanres & ERRORS)
471 return bscanres; // return on error
477 int LaTeX::startscript()
479 // onlyFileName() is needed for cygwin
480 string tmp = cmd + ' '
481 + quoteName(onlyFileName(file.toFilesystemEncoding()))
482 + " > " + os::nulldev();
484 Systemcall::Starttype const starttype =
485 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
486 return one.startscript(starttype, tmp, path, lpath, true);
490 int LaTeX::runMakeIndex(string const & f, OutputParams const & rp,
491 string const & params)
493 string tmp = rp.use_japanese ?
494 lyxrc.jindex_command : lyxrc.index_command;
496 if (!rp.index_command.empty())
497 tmp = rp.index_command;
500 "idx file has been made, running index processor ("
501 << tmp << ") on file " << f);
503 tmp = subst(tmp, "$$lang", rp.document_language);
504 if (rp.use_indices) {
505 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
507 "Multiple indices. Using splitindex command: " << tmp);
513 Systemcall::Starttype const starttype =
514 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
515 return one.startscript(starttype, tmp, path, lpath, true);
519 int LaTeX::runMakeIndexNomencl(FileName const & fname,
520 string const & nlo, string const & nls)
522 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
523 message(_("Running MakeIndex for nomencl."));
524 string tmp = lyxrc.nomencl_command + ' ';
525 // onlyFileName() is needed for cygwin
526 tmp += quoteName(onlyFileName(changeExtension(fname.absFileName(), nlo)));
528 + onlyFileName(changeExtension(fname.toFilesystemEncoding(), nls));
530 Systemcall::Starttype const starttype =
531 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
532 return one.startscript(starttype, tmp, path, lpath, true);
536 vector<AuxInfo> const
537 LaTeX::scanAuxFiles(FileName const & fname, bool const only_childbibs)
539 vector<AuxInfo> result;
541 // With chapterbib, we have to bibtex all children's aux files
542 // but _not_ the master's!
543 if (only_childbibs) {
544 for (string const &s: children) {
546 makeAbsPath(s, fname.onlyPath().realPath());
547 fn.changeExtension("aux");
549 result.push_back(scanAuxFile(fn));
554 result.push_back(scanAuxFile(fname));
556 // This is for bibtopic
557 string const basename = removeExtension(fname.absFileName());
558 for (int i = 1; i < 1000; ++i) {
559 FileName const file2(basename
560 + '.' + convert<string>(i)
564 result.push_back(scanAuxFile(file2));
570 AuxInfo const LaTeX::scanAuxFile(FileName const & fname)
573 result.aux_file = fname;
574 scanAuxFile(fname, result);
579 void LaTeX::scanAuxFile(FileName const & fname, AuxInfo & aux_info)
581 LYXERR(Debug::LATEX, "Scanning aux file: " << fname);
583 ifstream ifs(fname.toFilesystemEncoding().c_str());
585 static regex const reg1("\\\\citation\\{([^}]+)\\}");
586 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
587 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
588 static regex const reg4("\\\\@input\\{([^}]+)\\}");
590 while (getline(ifs, token)) {
591 token = rtrim(token, "\r");
593 // FIXME UNICODE: We assume that citation keys and filenames
594 // in the aux file are in the file system encoding.
595 token = to_utf8(from_filesystem8bit(token));
596 if (regex_match(token, sub, reg1)) {
597 string data = sub.str(1);
598 while (!data.empty()) {
600 data = split(data, citation, ',');
601 LYXERR(Debug::LATEX, "Citation: " << citation);
602 aux_info.citations.insert(citation);
604 } else if (regex_match(token, sub, reg2)) {
605 string data = sub.str(1);
606 // data is now all the bib files separated by ','
607 // get them one by one and pass them to the helper
608 while (!data.empty()) {
610 data = split(data, database, ',');
611 database = changeExtension(database, "bib");
612 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
613 aux_info.databases.insert(database);
615 } else if (regex_match(token, sub, reg3)) {
616 string style = sub.str(1);
617 // token is now the style file
618 // pass it to the helper
619 style = changeExtension(style, "bst");
620 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
621 aux_info.styles.insert(style);
622 } else if (regex_match(token, sub, reg4)) {
623 string const file2 = sub.str(1);
624 scanAuxFile(makeAbsPath(file2), aux_info);
630 void LaTeX::updateBibtexDependencies(DepTable & dep,
631 vector<AuxInfo> const & bibtex_info)
633 // Since a run of Bibtex mandates more latex runs it is ok to
634 // remove all ".bib" and ".bst" files.
635 dep.remove_files_with_extension(".bib");
636 dep.remove_files_with_extension(".bst");
637 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
639 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
640 it != bibtex_info.end(); ++it) {
641 for (set<string>::const_iterator it2 = it->databases.begin();
642 it2 != it->databases.end(); ++it2) {
643 FileName const file = findtexfile(*it2, "bib");
645 dep.insert(file, true);
648 for (set<string>::const_iterator it2 = it->styles.begin();
649 it2 != it->styles.end(); ++it2) {
650 FileName const file = findtexfile(*it2, "bst");
652 dep.insert(file, true);
656 // biber writes nothing into the aux file.
657 // Instead, we have to scan the blg file
660 scanBlgFile(dep, terr);
665 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
666 OutputParams const & rp, int & exit_code)
670 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
671 it != bibtex_info.end(); ++it) {
672 if (!biber && it->databases.empty())
676 string tmp = rp.bibtex_command;
678 // onlyFileName() is needed for cygwin
679 tmp += quoteName(onlyFileName(removeExtension(
680 it->aux_file.absFileName())));
682 Systemcall::Starttype const starttype =
683 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
684 exit_code = one.startscript(starttype, tmp, path, lpath, true);
689 // Return whether bibtex was run
694 //helper func for scanLogFile; gets line number X from strings "... on input line X ..."
695 //returns 0 if none is found
696 int getLineNumber(const string &token){
697 string l = support::token(token, ' ', tokenPos(token,' ',"line") + 1);
698 return l.empty() ? 0 : convert<int>(l);
702 int LaTeX::scanLogFile(TeXErrors & terr)
706 int retval = NO_ERRORS;
708 onlyFileName(changeExtension(file.absFileName(), ".log"));
709 LYXERR(Debug::LATEX, "Log file: " << tmp);
710 FileName const fn = FileName(makeAbsPath(tmp));
711 // FIXME we should use an ifdocstream here and a docstring for token
712 // below. The encoding of the log file depends on the _output_ (font)
713 // encoding of the TeX file (T1, TU etc.). See #10728.
714 ifstream ifs(fn.toFilesystemEncoding().c_str());
715 bool fle_style = false;
716 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
717 static regex const child_file("[^0-9]*([0-9]+[A-Za-z]*_.+\\.tex).*");
718 // Flag for 'File ended while scanning' message.
719 // We need to wait for subsequent processing.
720 string wait_for_error;
723 stack <pair<string, int> > child;
729 while (getline(ifs, token)) {
730 // MikTeX sometimes inserts \0 in the log file. They can't be
731 // removed directly with the existing string utility
732 // functions, so convert them first to \r, and remove all
733 // \r's afterwards, since we need to remove them anyway.
734 token = subst(token, '\0', '\r');
735 token = subst(token, "\r", "");
738 LYXERR(Debug::LATEX, "Log line: " << token);
743 // Track child documents
744 for (size_t i = 0; i < token.length(); ++i) {
745 if (token[i] == '(') {
747 size_t j = token.find('(', i + 1);
748 size_t len = j == string::npos
749 ? token.substr(i + 1).length()
751 string const substr = token.substr(i + 1, len);
752 if (regex_match(substr, sub, child_file)) {
753 string const name = sub.str(1);
754 // Sometimes also masters have a name that matches
755 // (if their name starts with a number and _)
756 if (name != file.onlyFileName()) {
757 child.push(make_pair(name, pnest));
758 children.push_back(name);
762 } else if (token[i] == ')') {
764 && child.top().second == pnest)
769 child_name = child.empty() ? empty_string() : child.top().first;
771 if (contains(token, "file:line:error style messages enabled"))
774 //Handles both "LaTeX Warning:" & "Package natbib Warning:"
775 //Various handlers for missing citations below won't catch the problem if citation
776 //key is long (>~25chars), because pdflatex splits output at line length 80.
777 //TODO: TL 2020 engines will contain new commandline switch --cnf-line which we
778 //can use to set max_print_line variable for appropriate length and detect all
780 if (contains(token, "There were undefined citations."))
783 if (prefixIs(token, "LaTeX Warning:") ||
784 prefixIs(token, "! pdfTeX warning")) {
785 // Here shall we handle different
787 retval |= LATEX_WARNING;
788 LYXERR(Debug::LATEX, "LaTeX Warning.");
789 if (contains(token, "Rerun to get cross-references")) {
791 LYXERR(Debug::LATEX, "We should rerun.");
792 // package clefval needs 2 latex runs before bibtex
793 } else if (contains(token, "Value of")
794 && contains(token, "on page")
795 && contains(token, "undefined")) {
796 retval |= ERROR_RERUN;
797 LYXERR(Debug::LATEX, "Force rerun.");
799 } else if (contains(token, "Etaremune labels have changed")) {
800 retval |= ERROR_RERUN;
801 LYXERR(Debug::LATEX, "Force rerun.");
803 } else if (contains(token, "Endnotes may have changed. Rerun")) {
805 LYXERR(Debug::LATEX, "We should rerun.");
806 //"Citation `cit' on page X undefined on input line X."
807 } else if (contains(token, "Citation")
808 //&& contains(token, "on input line") //often split to newline
809 && contains(token, "undefined")) {
811 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
812 from_utf8(token), child_name);
813 //"Reference `X' on page Y undefined on input line Z."
814 } else if (contains(token, "Reference")
815 //&& contains(token, "on input line")) //often split to new line
816 && contains(token, "undefined")) {
818 terr.insertRef(getLineNumber(token), from_ascii("Reference undefined"),
819 from_utf8(token), child_name);
821 //If label is too long pdlaftex log line splitting will make the above fail
822 //so we catch at least this generic statement occuring for both CIT & REF.
823 } else if (contains(token, "There were undefined references.")) {
824 if (!(retval & UNDEF_CIT)) //if not handled already
828 } else if (prefixIs(token, "Package")) {
830 retval |= PACKAGE_WARNING;
831 if (contains(token, "natbib Warning:")) {
833 if (contains(token, "Citation")
834 && contains(token, "on page")
835 && contains(token, "undefined")) {
837 //Unf only keys up to ~6 chars will make it due to line splits
838 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
839 from_utf8(token), child_name);
841 } else if (contains(token, "run BibTeX")) {
843 } else if (contains(token, "run Biber")) {
846 } else if (contains(token, "Rerun LaTeX") ||
847 contains(token, "Please rerun LaTeX") ||
848 contains(token, "Rerun to get")) {
849 // at least longtable.sty and bibtopic.sty
851 LYXERR(Debug::LATEX, "We should rerun.");
854 } else if (prefixIs(token, "LETTRE WARNING:")) {
855 if (contains(token, "veuillez recompiler")) {
857 LYXERR(Debug::LATEX, "We should rerun.");
860 } else if (token[0] == '(') {
861 if (contains(token, "Rerun LaTeX") ||
862 contains(token, "Rerun to get")) {
864 LYXERR(Debug::LATEX, "We should rerun.");
867 } else if (prefixIs(token, "! ")
869 && regex_match(token, sub, file_line_error)
870 && !contains(token, "pdfTeX warning"))) {
871 // Ok, we have something that looks like a TeX Error
872 // but what do we really have.
874 // Just get the error description:
876 if (prefixIs(token, "! "))
877 desc = string(token, 2);
880 if (contains(token, "LaTeX Error:"))
881 retval |= LATEX_ERROR;
883 if (prefixIs(token, "! File ended while scanning")) {
884 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
885 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
886 retval |= ERROR_RERUN;
887 LYXERR(Debug::LATEX, "Force rerun.");
889 // bug 6445. At this point its not clear we finish with error.
890 wait_for_error = desc;
895 if (prefixIs(token, "! Incomplete \\if")) {
896 // bug 10666. At this point its not clear we finish with error.
897 wait_for_error = desc;
901 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
902 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
903 retval |= ERROR_RERUN;
904 LYXERR(Debug::LATEX, "Force rerun.");
907 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
908 retval |= LATEX_ERROR;
911 errstr = wait_for_error;
912 wait_for_error.clear();
914 if (!getline(ifs, tmp))
916 tmp = rtrim(tmp, "\r");
917 errstr += "\n" + tmp;
920 } while (!contains(tmp, "(job aborted"));
923 from_ascii("Emergency stop"),
924 from_local8bit(errstr),
931 if (!getline(ifs, tmp))
933 tmp = rtrim(tmp, "\r");
934 // 15 is somewhat arbitrarily chosen, based on practice.
935 // We used 10 for 14 years and increased it to 15 when we
939 } while (!prefixIs(tmp, "l."));
940 if (prefixIs(tmp, "l.")) {
941 // we have a latex error
944 "Package babel Error: You haven't defined the language")
946 "Package babel Error: You haven't loaded the option")
948 "Package babel Error: Unknown language"))
949 retval |= ERROR_RERUN;
950 // get the line number:
952 sscanf(tmp.c_str(), "l.%d", &line);
953 // get the rest of the message:
954 string errstr(tmp, tmp.find(' '));
957 tmp = rtrim(tmp, "\r");
958 while (!contains(errstr, "l.")
960 && !prefixIs(tmp, "! ")
961 && !contains(tmp, "(job aborted")) {
965 tmp = rtrim(tmp, "\r");
967 LYXERR(Debug::LATEX, "line: " << line << '\n'
968 << "Desc: " << desc << '\n' << "Text: " << errstr);
969 if (line == last_line)
975 if (line_count <= 5) {
977 // We have no idea what the encoding of
979 // It seems that the output from the
980 // latex compiler itself is pure ASCII,
981 // but it can include bits from the
982 // document, so whatever encoding we
983 // assume here it can be wrong.
984 terr.insertError(line,
985 from_local8bit(desc),
986 from_local8bit(errstr),
992 // information messages, TeX warnings and other
993 // warnings we have not caught earlier.
994 if (prefixIs(token, "Overfull ")) {
995 retval |= TEX_WARNING;
996 } else if (prefixIs(token, "Underfull ")) {
997 retval |= TEX_WARNING;
998 } else if (contains(token, "Rerun to get citations")) {
999 // Natbib seems to use this.
1000 retval |= UNDEF_CIT;
1001 } else if (contains(token, "No pages of output")
1002 || contains(token, "no pages of output")) {
1003 // No output file (e.g. the DVI or PDF) was created
1004 retval |= NO_OUTPUT;
1005 } else if (contains(token, "Error 256 (driver return code)")) {
1006 // This is a xdvipdfmx driver error reported by XeTeX.
1007 // We have to check whether an output PDF file was created.
1008 FileName pdffile = file;
1009 pdffile.changeExtension("pdf");
1010 if (!pdffile.exists())
1011 // No output PDF file was created (see #10076)
1012 retval |= NO_OUTPUT;
1013 } else if (contains(token, "That makes 100 errors")) {
1014 // More than 100 errors were reported
1015 retval |= TOO_MANY_ERRORS;
1016 } else if (prefixIs(token, "!pdfTeX error:")) {
1017 // otherwise we dont catch e.g.:
1018 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
1021 from_ascii("pdfTeX Error"),
1022 from_local8bit(token),
1024 } else if (!ignore_missing_glyphs
1025 && prefixIs(token, "Missing character: There is no ")
1026 && !contains(token, "nullfont")) {
1027 // Warning about missing glyph in selected font
1028 // may be dataloss (bug 9610)
1029 // but can be ignored for 'nullfont' (bug 10394).
1030 // as well as for ZERO WIDTH NON-JOINER (0x200C) which is
1031 // missing in many fonts and output for ligature break (bug 10727).
1032 // Since this error only occurs with utf8 output, we can safely assume
1033 // that the log file is utf8-encoded
1034 docstring const utoken = from_utf8(token);
1035 if (!contains(utoken, 0x200C)) {
1036 retval |= LATEX_ERROR;
1038 from_ascii("Missing glyphs!"),
1042 } else if (!wait_for_error.empty()) {
1043 // We collect information until we know we have an error.
1044 wait_for_error += token + '\n';
1048 LYXERR(Debug::LATEX, "Log line: " << token);
1055 bool insertIfExists(FileName const & absname, DepTable & head)
1057 if (absname.exists() && !absname.isDirectory()) {
1058 head.insert(absname, true);
1065 bool handleFoundFile(string const & ff, DepTable & head)
1067 // convert from native os path to unix path
1068 string foundfile = os::internal_path(trim(ff));
1070 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
1072 // Ok now we found a file.
1073 // Now we should make sure that this is a file that we can
1074 // access through the normal paths.
1075 // We will not try any fancy search methods to
1078 // (1) foundfile is an
1079 // absolute path and should
1082 if (FileName::isAbsolute(foundfile)) {
1083 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
1084 // On initial insert we want to do the update at once
1085 // since this file cannot be a file generated by
1087 absname.set(foundfile);
1088 if (!insertIfExists(absname, head)) {
1090 string strippedfile = foundfile;
1091 while (contains(strippedfile, " ")) {
1092 // files with spaces are often enclosed in quotation
1093 // marks; those have to be removed
1094 string unquoted = subst(strippedfile, "\"", "");
1095 absname.set(unquoted);
1096 if (insertIfExists(absname, head))
1098 // strip off part after last space and try again
1099 string tmp = strippedfile;
1100 rsplit(tmp, strippedfile, ' ');
1101 absname.set(strippedfile);
1102 if (insertIfExists(absname, head))
1108 string onlyfile = onlyFileName(foundfile);
1109 absname = makeAbsPath(onlyfile);
1112 while (contains(foundfile, ' ')) {
1113 if (absname.exists())
1117 // files with spaces are often enclosed in quotation
1118 // marks; those have to be removed
1119 string unquoted = subst(foundfile, "\"", "");
1120 absname = makeAbsPath(unquoted);
1121 if (absname.exists())
1123 // strip off part after last space and try again
1124 string strippedfile;
1125 rsplit(foundfile, strippedfile, ' ');
1126 foundfile = strippedfile;
1127 onlyfile = onlyFileName(strippedfile);
1128 absname = makeAbsPath(onlyfile);
1132 // (2) foundfile is in the tmpdir
1133 // insert it into head
1134 if (absname.exists() && !absname.isDirectory()) {
1135 // FIXME: This regex contained glo, but glo is used by the old
1136 // version of nomencl.sty. Do we need to put it back?
1137 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1138 if (regex_match(onlyfile, unwanted)) {
1139 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1140 << " in the dep file");
1141 } else if (suffixIs(onlyfile, ".tex")) {
1142 // This is a tex file generated by LyX
1143 // and latex is not likely to change this
1145 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1146 head.insert(absname, true);
1148 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1149 head.insert(absname);
1153 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1159 bool completeFilename(string const & ff, DepTable & head)
1161 // If we do not find a dot, we suspect
1162 // a fragmental file name
1163 if (!contains(ff, '.'))
1166 // if we have a dot, we let handleFoundFile decide
1167 return handleFoundFile(ff, head);
1171 int iterateLine(string const & token, regex const & reg, string const & opening,
1172 string const & closing, int fragment_pos, DepTable & head)
1175 string::const_iterator first = token.begin();
1176 string::const_iterator end = token.end();
1177 bool fragment = false;
1180 while (regex_search(first, end, what, reg)) {
1181 // if we have a dot, try to handle as file
1182 if (contains(what.str(1), '.')) {
1183 first = what[0].second;
1184 if (what.str(2) == closing) {
1185 handleFoundFile(what.str(1), head);
1186 // since we had a closing bracket,
1187 // do not investigate further
1189 } else if (what.str(2) == opening) {
1190 // if we have another opening bracket,
1191 // we might have a nested file chain
1192 // as is (file.ext (subfile.ext))
1193 fragment = !handleFoundFile(rtrim(what.str(1)), head);
1194 // decrease first position by one in order to
1195 // consider the opening delimiter on next iteration
1196 if (first > token.begin())
1199 // if we have no closing bracket,
1200 // try to handle as file nevertheless
1201 fragment = !handleFoundFile(
1202 what.str(1) + what.str(2), head);
1204 // if we do not have a dot, check if the line has
1205 // a closing bracket (else, we suspect a line break)
1206 else if (what.str(2) != closing) {
1207 first = what[0].second;
1210 // we have a closing bracket, so the content
1211 // is not a file name.
1212 // no need to investigate further
1213 first = what[0].second;
1216 last_match = what.str(1);
1219 // We need to consider the result from previous line iterations:
1220 // We might not find a fragment here, but another one might follow
1221 // E.g.: (filename.ext) <filenam
1222 // Vice versa, we consider the search completed if a real match
1223 // follows a potential fragment from a previous iteration.
1224 // E.g. <some text we considered a fragment (filename.ext)
1225 // result = -1 means we did not find a fragment!
1227 int last_match_pos = -1;
1228 if (!last_match.empty() && token.find(last_match) != string::npos)
1229 last_match_pos = int(token.find(last_match));
1231 if (last_match_pos > fragment_pos)
1232 result = last_match_pos;
1234 result = fragment_pos;
1236 if (last_match_pos < fragment_pos)
1237 result = fragment_pos;
1245 void LaTeX::deplog(DepTable & head)
1247 // This function reads the LaTeX log file end extracts all the
1248 // external files used by the LaTeX run. The files are then
1249 // entered into the dependency file.
1251 string const logfile =
1252 onlyFileName(changeExtension(file.absFileName(), ".log"));
1254 static regex const reg1("File: (.+).*");
1255 static regex const reg2("No file (.+)(.).*");
1256 static regex const reg3a("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1257 // LuaTeX has a slightly different output
1258 static regex const reg3b("\\\\openout[0-9]+.*=\\s*(.+)");
1259 // If an index should be created, MikTex does not write a line like
1260 // \openout# = 'sample.idx'.
1261 // but instead only a line like this into the log:
1262 // Writing index file sample.idx
1263 static regex const reg4("Writing index file (.+).*");
1264 static regex const regoldnomencl("Writing glossary file (.+).*");
1265 static regex const regnomencl(".*Writing nomenclature file (.+).*");
1266 // If a toc should be created, MikTex does not write a line like
1267 // \openout# = `sample.toc'.
1268 // but only a line like this into the log:
1270 // This line is also written by tetex.
1271 // This line is not present if no toc should be created.
1272 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1273 // file names can be enclosed in <...> (anywhere on the line)
1274 static regex const reg5(".*<[^>]+.*");
1275 // and also (...) anywhere on the line
1276 static regex const reg6(".*\\([^)]+.*");
1278 FileName const fn = makeAbsPath(logfile);
1279 ifstream ifs(fn.toFilesystemEncoding().c_str());
1282 // Ok, the scanning of files here is not sufficient.
1283 // Sometimes files are named by "File: xxx" only
1284 // Therefore we use some regexps to find files instead.
1285 // Note: all file names and paths might contains spaces.
1286 // Also, file names might be broken across lines. Therefore
1287 // we mark (potential) fragments and merge those lines.
1288 bool fragment = false;
1290 getline(ifs, token);
1291 // MikTeX sometimes inserts \0 in the log file. They can't be
1292 // removed directly with the existing string utility
1293 // functions, so convert them first to \r, and remove all
1294 // \r's afterwards, since we need to remove them anyway.
1295 token = subst(token, '\0', '\r');
1296 token = subst(token, "\r", "");
1297 if (token.empty() || token == ")") {
1298 lastline = string();
1302 // FIXME UNICODE: We assume that the file names in the log
1303 // file are in the file system encoding.
1304 token = to_utf8(from_filesystem8bit(token));
1306 // Sometimes, filenames are broken across lines.
1307 // We care for that and save suspicious lines.
1308 // Here we exclude some cases where we are sure
1309 // that there is no continued filename
1310 if (!lastline.empty()) {
1311 static regex const package_info("Package \\w+ Info: .*");
1312 static regex const package_warning("Package \\w+ Warning: .*");
1313 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1314 || prefixIs(token, "Package:")
1315 || prefixIs(token, "Language:")
1316 || prefixIs(token, "LaTeX Info:")
1317 || prefixIs(token, "LaTeX Font Info:")
1318 || prefixIs(token, "\\openout[")
1319 || prefixIs(token, "))")
1320 || regex_match(token, package_info)
1321 || regex_match(token, package_warning))
1322 lastline = string();
1325 if (!lastline.empty())
1326 // probably a continued filename from last line
1327 token = lastline + token;
1328 if (token.length() > 255) {
1329 // string too long. Cut off.
1330 token.erase(0, token.length() - 251);
1335 // (1) "File: file.ext"
1336 if (regex_match(token, sub, reg1)) {
1337 // is this a fragmental file name?
1338 fragment = !completeFilename(sub.str(1), head);
1340 if (suffixIs(token, ")"))
1341 // no fragment for sure
1343 // (2) "No file file.ext"
1344 } else if (regex_match(token, sub, reg2)) {
1345 // file names must contains a dot, line ends with dot
1346 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1347 fragment = !handleFoundFile(sub.str(1), head);
1349 // we suspect a line break
1351 // (3)(a) "\openout<nr> = `file.ext'."
1352 } else if (regex_match(token, sub, reg3a)) {
1353 // search for closing '. at the end of the line
1354 if (sub.str(2) == "\'.")
1355 fragment = !handleFoundFile(sub.str(1), head);
1357 // potential fragment
1359 // (3)(b) "\openout<nr> = file.ext" (LuaTeX)
1360 } else if (regex_match(token, sub, reg3b)) {
1361 // file names must contains a dot
1362 if (contains(sub.str(1), '.'))
1363 fragment = !handleFoundFile(sub.str(1), head);
1365 // potential fragment
1367 // (4) "Writing index file file.ext"
1368 } else if (regex_match(token, sub, reg4))
1369 // fragmential file name?
1370 fragment = !completeFilename(sub.str(1), head);
1371 // (5) "Writing nomenclature file file.ext"
1372 else if (regex_match(token, sub, regnomencl) ||
1373 regex_match(token, sub, regoldnomencl))
1374 // fragmental file name?
1375 fragment= !completeFilename(sub.str(1), head);
1376 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1377 else if (regex_match(token, sub, miktexTocReg))
1378 fragment = !handleFoundFile(onlyFileName(changeExtension(
1379 file.absFileName(), ".toc")), head);
1381 // not found, but we won't check further
1384 int fragment_pos = -1;
1386 // We can have several of these on one line
1387 // (and in addition to those above)
1388 if (regex_match(token, sub, reg5)) {
1389 // search for strings in <...>
1390 static regex const reg5_1("<([^>]+)(.)");
1391 fragment_pos = iterateLine(token, reg5_1, "<", ">",
1392 fragment_pos, head);
1393 fragment = (fragment_pos != -1);
1397 // We can have several of these on one line
1398 // this must be queried separated, because of
1399 // cases such as "File: file.ext (type eps)"
1400 // where "File: file.ext" would be skipped
1401 if (regex_match(token, sub, reg6)) {
1402 // search for strings in (...)
1403 static regex const reg6_1("\\(([^()]+)(.)");
1404 fragment_pos = iterateLine(token, reg6_1, "(", ")",
1405 fragment_pos, head);
1406 fragment = (fragment_pos != -1);
1410 // probable linebreak within file name:
1414 // no linebreak: reset
1415 lastline = string();
1418 // Make sure that the main .tex file is in the dependency file.
1419 head.insert(file, true);
1423 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1425 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1426 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1428 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1430 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1431 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1432 static regex const bibtexError2("^(.*---while reading file).*$");
1433 static regex const bibtexError3("(A bad cross reference---).*");
1434 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1435 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1436 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1437 int retval = NO_ERRORS;
1440 while (getline(ifs, token)) {
1441 token = rtrim(token, "\r");
1443 // FIXME UNICODE: We assume that citation keys and filenames
1444 // in the aux file are in the file system encoding.
1445 token = to_utf8(from_filesystem8bit(token));
1446 if (regex_match(token, sub, reg1)) {
1447 string data = sub.str(3);
1448 if (!data.empty()) {
1449 LYXERR(Debug::LATEX, "Found bib file: " << data);
1450 handleFoundFile(data, dep);
1453 else if (regex_match(token, sub, bibtexError)
1454 || regex_match(token, sub, bibtexError2)
1455 || regex_match(token, sub, bibtexError4)
1456 || regex_match(token, sub, bibtexError5)) {
1457 retval |= BIBTEX_ERROR;
1458 string errstr = N_("BibTeX error: ") + token;
1460 if ((prefixIs(token, "while executing---line")
1461 || prefixIs(token, "---line ")
1462 || prefixIs(token, "*Please notify the BibTeX"))
1463 && !prevtoken.empty()) {
1464 errstr = N_("BibTeX error: ") + prevtoken;
1465 msg = prevtoken + '\n';
1469 from_local8bit(errstr),
1470 from_local8bit(msg));
1471 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1472 retval |= BIBTEX_ERROR;
1473 string errstr = N_("BibTeX error: ") + prevtoken;
1474 string msg = prevtoken + '\n' + token;
1476 from_local8bit(errstr),
1477 from_local8bit(msg));
1478 } else if (regex_match(token, sub, biberError)) {
1479 retval |= BIBTEX_ERROR;
1480 string errstr = N_("Biber error: ") + sub.str(2);
1483 from_local8bit(errstr),
1484 from_local8bit(msg));