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."))
787 if (prefixIs(token, "LaTeX Warning:") ||
788 prefixIs(token, "! pdfTeX warning")) {
789 // Here shall we handle different
791 retval |= LATEX_WARNING;
792 LYXERR(Debug::LATEX, "LaTeX Warning.");
793 if (contains(token, "Rerun to get cross-references")) {
795 LYXERR(Debug::LATEX, "We should rerun.");
796 // package clefval needs 2 latex runs before bibtex
797 } else if (contains(token, "Value of")
798 && contains(token, "on page")
799 && contains(token, "undefined")) {
800 retval |= ERROR_RERUN;
801 LYXERR(Debug::LATEX, "Force rerun.");
803 } else if (contains(token, "Etaremune labels have changed")) {
804 retval |= ERROR_RERUN;
805 LYXERR(Debug::LATEX, "Force rerun.");
807 } else if (contains(token, "Endnotes may have changed. Rerun")) {
809 LYXERR(Debug::LATEX, "We should rerun.");
810 //"Citation `cit' on page X undefined on input line X."
811 } else if (contains(token, "Citation")
812 //&& contains(token, "on input line") //often split to newline
813 && contains(token, "undefined")) {
815 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
816 from_utf8(token), child_name);
817 //"Reference `X' on page Y undefined on input line Z."
818 } else if (contains(token, "Reference")
819 //&& contains(token, "on input line")) //often split to new line
820 && contains(token, "undefined")) {
822 terr.insertRef(getLineNumber(token), from_ascii("Reference undefined"),
823 from_utf8(token), child_name);
825 //If label is too long pdlaftex log line splitting will make the above fail
826 //so we catch at least this generic statement occuring for both CIT & REF.
827 } else if (contains(token, "There were undefined references.")) {
828 if (!(retval & UNDEF_CIT)) //if not handled already
832 } else if (prefixIs(token, "Package")) {
834 retval |= PACKAGE_WARNING;
835 if (contains(token, "natbib Warning:")) {
837 if (contains(token, "Citation")
838 && contains(token, "on page")
839 && contains(token, "undefined")) {
841 //Unf only keys up to ~6 chars will make it due to line splits
842 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
843 from_utf8(token), child_name);
845 } else if (contains(token, "run BibTeX")) {
847 } else if (contains(token, "run Biber")) {
850 } else if (contains(token, "Rerun LaTeX") ||
851 contains(token, "Please rerun LaTeX") ||
852 contains(token, "Rerun to get")) {
853 // at least longtable.sty and bibtopic.sty
855 LYXERR(Debug::LATEX, "We should rerun.");
858 } else if (prefixIs(token, "LETTRE WARNING:")) {
859 if (contains(token, "veuillez recompiler")) {
861 LYXERR(Debug::LATEX, "We should rerun.");
864 } else if (token[0] == '(') {
865 if (contains(token, "Rerun LaTeX") ||
866 contains(token, "Rerun to get")) {
868 LYXERR(Debug::LATEX, "We should rerun.");
871 } else if (prefixIs(token, "! ")
873 && regex_match(token, sub, file_line_error)
874 && !contains(token, "pdfTeX warning"))) {
875 // Ok, we have something that looks like a TeX Error
876 // but what do we really have.
878 // Just get the error description:
880 if (prefixIs(token, "! "))
881 desc = string(token, 2);
884 if (contains(token, "LaTeX Error:"))
885 retval |= LATEX_ERROR;
887 if (prefixIs(token, "! File ended while scanning")) {
888 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
889 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
890 retval |= ERROR_RERUN;
891 LYXERR(Debug::LATEX, "Force rerun.");
893 // bug 6445. At this point its not clear we finish with error.
894 wait_for_error = desc;
899 if (prefixIs(token, "! Incomplete \\if")) {
900 // bug 10666. At this point its not clear we finish with error.
901 wait_for_error = desc;
905 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
906 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
907 retval |= ERROR_RERUN;
908 LYXERR(Debug::LATEX, "Force rerun.");
911 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
912 retval |= LATEX_ERROR;
915 errstr = wait_for_error;
916 wait_for_error.clear();
918 if (!getline(ifs, tmp))
920 tmp = rtrim(tmp, "\r");
921 errstr += "\n" + tmp;
924 } while (!contains(tmp, "(job aborted"));
927 from_ascii("Emergency stop"),
928 from_local8bit(errstr),
935 if (!getline(ifs, tmp))
937 tmp = rtrim(tmp, "\r");
938 // 15 is somewhat arbitrarily chosen, based on practice.
939 // We used 10 for 14 years and increased it to 15 when we
943 } while (!prefixIs(tmp, "l."));
944 if (prefixIs(tmp, "l.")) {
945 // we have a latex error
948 "Package babel Error: You haven't defined the language")
950 "Package babel Error: You haven't loaded the option")
952 "Package babel Error: Unknown language"))
953 retval |= ERROR_RERUN;
954 // get the line number:
956 sscanf(tmp.c_str(), "l.%d", &line);
957 // get the rest of the message:
958 string errstr(tmp, tmp.find(' '));
961 tmp = rtrim(tmp, "\r");
962 while (!contains(errstr, "l.")
964 && !prefixIs(tmp, "! ")
965 && !contains(tmp, "(job aborted")) {
969 tmp = rtrim(tmp, "\r");
971 LYXERR(Debug::LATEX, "line: " << line << '\n'
972 << "Desc: " << desc << '\n' << "Text: " << errstr);
973 if (line == last_line)
979 if (line_count <= 5) {
981 // We have no idea what the encoding of
983 // It seems that the output from the
984 // latex compiler itself is pure ASCII,
985 // but it can include bits from the
986 // document, so whatever encoding we
987 // assume here it can be wrong.
988 terr.insertError(line,
989 from_local8bit(desc),
990 from_local8bit(errstr),
996 // information messages, TeX warnings and other
997 // warnings we have not caught earlier.
998 if (prefixIs(token, "Overfull ")) {
999 retval |= TEX_WARNING;
1000 } else if (prefixIs(token, "Underfull ")) {
1001 retval |= TEX_WARNING;
1002 } else if (contains(token, "Rerun to get citations")) {
1003 // Natbib seems to use this.
1004 retval |= UNDEF_CIT;
1005 } else if (contains(token, "No pages of output")
1006 || contains(token, "no pages of output")) {
1007 // No output file (e.g. the DVI or PDF) was created
1008 retval |= NO_OUTPUT;
1009 } else if (contains(token, "Error 256 (driver return code)")) {
1010 // This is a xdvipdfmx driver error reported by XeTeX.
1011 // We have to check whether an output PDF file was created.
1012 FileName pdffile = file;
1013 pdffile.changeExtension("pdf");
1014 if (!pdffile.exists())
1015 // No output PDF file was created (see #10076)
1016 retval |= NO_OUTPUT;
1017 } else if (contains(token, "That makes 100 errors")) {
1018 // More than 100 errors were reported
1019 retval |= TOO_MANY_ERRORS;
1020 } else if (prefixIs(token, "!pdfTeX error:")) {
1021 // otherwise we dont catch e.g.:
1022 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
1025 from_ascii("pdfTeX Error"),
1026 from_local8bit(token),
1028 } else if (!ignore_missing_glyphs
1029 && prefixIs(token, "Missing character: There is no ")
1030 && !contains(token, "nullfont")) {
1031 // Warning about missing glyph in selected font
1032 // may be dataloss (bug 9610)
1033 // but can be ignored for 'nullfont' (bug 10394).
1034 // as well as for ZERO WIDTH NON-JOINER (0x200C) which is
1035 // missing in many fonts and output for ligature break (bug 10727).
1036 // Since this error only occurs with utf8 output, we can safely assume
1037 // that the log file is utf8-encoded
1038 docstring const utoken = from_utf8(token);
1039 if (!contains(utoken, 0x200C)) {
1040 retval |= LATEX_ERROR;
1042 from_ascii("Missing glyphs!"),
1046 } else if (!wait_for_error.empty()) {
1047 // We collect information until we know we have an error.
1048 wait_for_error += token + '\n';
1052 LYXERR(Debug::LATEX, "Log line: " << token);
1059 bool insertIfExists(FileName const & absname, DepTable & head)
1061 if (absname.exists() && !absname.isDirectory()) {
1062 head.insert(absname, true);
1069 bool handleFoundFile(string const & ff, DepTable & head)
1071 // convert from native os path to unix path
1072 string foundfile = os::internal_path(trim(ff));
1074 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
1076 // Ok now we found a file.
1077 // Now we should make sure that this is a file that we can
1078 // access through the normal paths.
1079 // We will not try any fancy search methods to
1082 // (1) foundfile is an
1083 // absolute path and should
1086 if (FileName::isAbsolute(foundfile)) {
1087 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
1088 // On initial insert we want to do the update at once
1089 // since this file cannot be a file generated by
1091 absname.set(foundfile);
1092 if (!insertIfExists(absname, head)) {
1094 string strippedfile = foundfile;
1095 while (contains(strippedfile, " ")) {
1096 // files with spaces are often enclosed in quotation
1097 // marks; those have to be removed
1098 string unquoted = subst(strippedfile, "\"", "");
1099 absname.set(unquoted);
1100 if (insertIfExists(absname, head))
1102 // strip off part after last space and try again
1103 string tmp = strippedfile;
1104 rsplit(tmp, strippedfile, ' ');
1105 absname.set(strippedfile);
1106 if (insertIfExists(absname, head))
1112 string onlyfile = onlyFileName(foundfile);
1113 absname = makeAbsPath(onlyfile);
1116 while (contains(foundfile, ' ')) {
1117 if (absname.exists())
1121 // files with spaces are often enclosed in quotation
1122 // marks; those have to be removed
1123 string unquoted = subst(foundfile, "\"", "");
1124 absname = makeAbsPath(unquoted);
1125 if (absname.exists())
1127 // strip off part after last space and try again
1128 string strippedfile;
1129 rsplit(foundfile, strippedfile, ' ');
1130 foundfile = strippedfile;
1131 onlyfile = onlyFileName(strippedfile);
1132 absname = makeAbsPath(onlyfile);
1136 // (2) foundfile is in the tmpdir
1137 // insert it into head
1138 if (absname.exists() && !absname.isDirectory()) {
1139 // FIXME: This regex contained glo, but glo is used by the old
1140 // version of nomencl.sty. Do we need to put it back?
1141 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1142 if (regex_match(onlyfile, unwanted)) {
1143 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1144 << " in the dep file");
1145 } else if (suffixIs(onlyfile, ".tex")) {
1146 // This is a tex file generated by LyX
1147 // and latex is not likely to change this
1149 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1150 head.insert(absname, true);
1152 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1153 head.insert(absname);
1157 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1163 bool completeFilename(string const & ff, DepTable & head)
1165 // If we do not find a dot, we suspect
1166 // a fragmental file name
1167 if (!contains(ff, '.'))
1170 // if we have a dot, we let handleFoundFile decide
1171 return handleFoundFile(ff, head);
1175 int iterateLine(string const & token, regex const & reg, string const & opening,
1176 string const & closing, int fragment_pos, DepTable & head)
1179 string::const_iterator first = token.begin();
1180 string::const_iterator end = token.end();
1181 bool fragment = false;
1184 while (regex_search(first, end, what, reg)) {
1185 // if we have a dot, try to handle as file
1186 if (contains(what.str(1), '.')) {
1187 first = what[0].second;
1188 if (what.str(2) == closing) {
1189 handleFoundFile(what.str(1), head);
1190 // since we had a closing bracket,
1191 // do not investigate further
1193 } else if (what.str(2) == opening) {
1194 // if we have another opening bracket,
1195 // we might have a nested file chain
1196 // as is (file.ext (subfile.ext))
1197 fragment = !handleFoundFile(rtrim(what.str(1)), head);
1198 // decrease first position by one in order to
1199 // consider the opening delimiter on next iteration
1200 if (first > token.begin())
1203 // if we have no closing bracket,
1204 // try to handle as file nevertheless
1205 fragment = !handleFoundFile(
1206 what.str(1) + what.str(2), head);
1208 // if we do not have a dot, check if the line has
1209 // a closing bracket (else, we suspect a line break)
1210 else if (what.str(2) != closing) {
1211 first = what[0].second;
1214 // we have a closing bracket, so the content
1215 // is not a file name.
1216 // no need to investigate further
1217 first = what[0].second;
1220 last_match = what.str(1);
1223 // We need to consider the result from previous line iterations:
1224 // We might not find a fragment here, but another one might follow
1225 // E.g.: (filename.ext) <filenam
1226 // Vice versa, we consider the search completed if a real match
1227 // follows a potential fragment from a previous iteration.
1228 // E.g. <some text we considered a fragment (filename.ext)
1229 // result = -1 means we did not find a fragment!
1231 int last_match_pos = -1;
1232 if (!last_match.empty() && token.find(last_match) != string::npos)
1233 last_match_pos = int(token.find(last_match));
1235 if (last_match_pos > fragment_pos)
1236 result = last_match_pos;
1238 result = fragment_pos;
1240 if (last_match_pos < fragment_pos)
1241 result = fragment_pos;
1249 void LaTeX::deplog(DepTable & head)
1251 // This function reads the LaTeX log file end extracts all the
1252 // external files used by the LaTeX run. The files are then
1253 // entered into the dependency file.
1255 string const logfile =
1256 onlyFileName(changeExtension(file.absFileName(), ".log"));
1258 static regex const reg1("File: (.+).*");
1259 static regex const reg2("No file (.+)(.).*");
1260 static regex const reg3a("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1261 // LuaTeX has a slightly different output
1262 static regex const reg3b("\\\\openout[0-9]+.*=\\s*(.+)");
1263 // If an index should be created, MikTex does not write a line like
1264 // \openout# = 'sample.idx'.
1265 // but instead only a line like this into the log:
1266 // Writing index file sample.idx
1267 static regex const reg4("Writing index file (.+).*");
1268 static regex const regoldnomencl("Writing glossary file (.+).*");
1269 static regex const regnomencl(".*Writing nomenclature file (.+).*");
1270 // If a toc should be created, MikTex does not write a line like
1271 // \openout# = `sample.toc'.
1272 // but only a line like this into the log:
1274 // This line is also written by tetex.
1275 // This line is not present if no toc should be created.
1276 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1277 // file names can be enclosed in <...> (anywhere on the line)
1278 static regex const reg5(".*<[^>]+.*");
1279 // and also (...) anywhere on the line
1280 static regex const reg6(".*\\([^)]+.*");
1282 FileName const fn = makeAbsPath(logfile);
1283 ifstream ifs(fn.toFilesystemEncoding().c_str());
1286 // Ok, the scanning of files here is not sufficient.
1287 // Sometimes files are named by "File: xxx" only
1288 // Therefore we use some regexps to find files instead.
1289 // Note: all file names and paths might contains spaces.
1290 // Also, file names might be broken across lines. Therefore
1291 // we mark (potential) fragments and merge those lines.
1292 bool fragment = false;
1294 getline(ifs, token);
1295 // MikTeX sometimes inserts \0 in the log file. They can't be
1296 // removed directly with the existing string utility
1297 // functions, so convert them first to \r, and remove all
1298 // \r's afterwards, since we need to remove them anyway.
1299 token = subst(token, '\0', '\r');
1300 token = subst(token, "\r", "");
1301 if (token.empty() || token == ")") {
1302 lastline = string();
1306 // FIXME UNICODE: We assume that the file names in the log
1307 // file are in the file system encoding.
1308 token = to_utf8(from_filesystem8bit(token));
1310 // Sometimes, filenames are broken across lines.
1311 // We care for that and save suspicious lines.
1312 // Here we exclude some cases where we are sure
1313 // that there is no continued filename
1314 if (!lastline.empty()) {
1315 static regex const package_info("Package \\w+ Info: .*");
1316 static regex const package_warning("Package \\w+ Warning: .*");
1317 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1318 || prefixIs(token, "Package:")
1319 || prefixIs(token, "Language:")
1320 || prefixIs(token, "LaTeX Info:")
1321 || prefixIs(token, "LaTeX Font Info:")
1322 || prefixIs(token, "\\openout[")
1323 || prefixIs(token, "))")
1324 || regex_match(token, package_info)
1325 || regex_match(token, package_warning))
1326 lastline = string();
1329 if (!lastline.empty())
1330 // probably a continued filename from last line
1331 token = lastline + token;
1332 if (token.length() > 255) {
1333 // string too long. Cut off.
1334 token.erase(0, token.length() - 251);
1339 // (1) "File: file.ext"
1340 if (regex_match(token, sub, reg1)) {
1341 // is this a fragmental file name?
1342 fragment = !completeFilename(sub.str(1), head);
1344 if (suffixIs(token, ")"))
1345 // no fragment for sure
1347 // (2) "No file file.ext"
1348 } else if (regex_match(token, sub, reg2)) {
1349 // file names must contains a dot, line ends with dot
1350 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1351 fragment = !handleFoundFile(sub.str(1), head);
1353 // we suspect a line break
1355 // (3)(a) "\openout<nr> = `file.ext'."
1356 } else if (regex_match(token, sub, reg3a)) {
1357 // search for closing '. at the end of the line
1358 if (sub.str(2) == "\'.")
1359 fragment = !handleFoundFile(sub.str(1), head);
1361 // potential fragment
1363 // (3)(b) "\openout<nr> = file.ext" (LuaTeX)
1364 } else if (regex_match(token, sub, reg3b)) {
1365 // file names must contains a dot
1366 if (contains(sub.str(1), '.'))
1367 fragment = !handleFoundFile(sub.str(1), head);
1369 // potential fragment
1371 // (4) "Writing index file file.ext"
1372 } else if (regex_match(token, sub, reg4))
1373 // fragmential file name?
1374 fragment = !completeFilename(sub.str(1), head);
1375 // (5) "Writing nomenclature file file.ext"
1376 else if (regex_match(token, sub, regnomencl) ||
1377 regex_match(token, sub, regoldnomencl))
1378 // fragmental file name?
1379 fragment= !completeFilename(sub.str(1), head);
1380 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1381 else if (regex_match(token, sub, miktexTocReg))
1382 fragment = !handleFoundFile(onlyFileName(changeExtension(
1383 file.absFileName(), ".toc")), head);
1385 // not found, but we won't check further
1388 int fragment_pos = -1;
1390 // We can have several of these on one line
1391 // (and in addition to those above)
1392 if (regex_match(token, sub, reg5)) {
1393 // search for strings in <...>
1394 static regex const reg5_1("<([^>]+)(.)");
1395 fragment_pos = iterateLine(token, reg5_1, "<", ">",
1396 fragment_pos, head);
1397 fragment = (fragment_pos != -1);
1401 // We can have several of these on one line
1402 // this must be queried separated, because of
1403 // cases such as "File: file.ext (type eps)"
1404 // where "File: file.ext" would be skipped
1405 if (regex_match(token, sub, reg6)) {
1406 // search for strings in (...)
1407 static regex const reg6_1("\\(([^()]+)(.)");
1408 fragment_pos = iterateLine(token, reg6_1, "(", ")",
1409 fragment_pos, head);
1410 fragment = (fragment_pos != -1);
1414 // probable linebreak within file name:
1418 // no linebreak: reset
1419 lastline = string();
1422 // Make sure that the main .tex file is in the dependency file.
1423 head.insert(file, true);
1427 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1429 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1430 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1432 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1434 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1435 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1436 static regex const bibtexError2("^(.*---while reading file).*$");
1437 static regex const bibtexError3("(A bad cross reference---).*");
1438 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1439 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1440 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1441 int retval = NO_ERRORS;
1444 while (getline(ifs, token)) {
1445 token = rtrim(token, "\r");
1447 // FIXME UNICODE: We assume that citation keys and filenames
1448 // in the aux file are in the file system encoding.
1449 token = to_utf8(from_filesystem8bit(token));
1450 if (regex_match(token, sub, reg1)) {
1451 string data = sub.str(3);
1452 if (!data.empty()) {
1453 LYXERR(Debug::LATEX, "Found bib file: " << data);
1454 handleFoundFile(data, dep);
1457 else if (regex_match(token, sub, bibtexError)
1458 || regex_match(token, sub, bibtexError2)
1459 || regex_match(token, sub, bibtexError4)
1460 || regex_match(token, sub, bibtexError5)) {
1461 retval |= BIBTEX_ERROR;
1462 string errstr = N_("BibTeX error: ") + token;
1464 if ((prefixIs(token, "while executing---line")
1465 || prefixIs(token, "---line ")
1466 || prefixIs(token, "*Please notify the BibTeX"))
1467 && !prevtoken.empty()) {
1468 errstr = N_("BibTeX error: ") + prevtoken;
1469 msg = prevtoken + '\n';
1473 from_local8bit(errstr),
1474 from_local8bit(msg));
1475 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1476 retval |= BIBTEX_ERROR;
1477 string errstr = N_("BibTeX error: ") + prevtoken;
1478 string msg = prevtoken + '\n' + token;
1480 from_local8bit(errstr),
1481 from_local8bit(msg));
1482 } else if (regex_match(token, sub, biberError)) {
1483 retval |= BIBTEX_ERROR;
1484 string errstr = N_("Biber error: ") + sub.str(2);
1487 from_local8bit(errstr),
1488 from_local8bit(msg));