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"
25 #include "support/debug.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/Systemcall.h"
32 #include "support/os.h"
34 #include "support/regex.h"
41 using namespace lyx::support;
45 namespace os = support::os;
47 // TODO: in no particular order
48 // - get rid of the call to
49 // BufferList::updateIncludedTeXfiles, this should either
50 // be done before calling LaTeX::funcs or in a completely
52 // - the makeindex style files should be taken care of with
53 // the dependency mechanism.
57 docstring runMessage(unsigned int count)
59 return bformat(_("Waiting for LaTeX run number %1$d"), count);
68 void TeXErrors::insertError(int line, docstring const & error_desc,
69 docstring const & error_text,
70 string const & child_name)
72 Error newerr(line, error_desc, error_text, child_name);
73 errors.push_back(newerr);
77 void TeXErrors::insertRef(int line, docstring const & error_desc,
78 docstring const & error_text,
79 string const & child_name)
81 Error newerr(line, error_desc, error_text, child_name);
82 undef_ref.push_back(newerr);
86 bool operator==(AuxInfo const & a, AuxInfo const & o)
88 return a.aux_file == o.aux_file
89 && a.citations == o.citations
90 && a.databases == o.databases
91 && a.styles == o.styles;
95 bool operator!=(AuxInfo const & a, AuxInfo const & o)
105 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
106 FileName const & f, string const & p, string const & lp,
107 bool allow_cancellation, bool const clean_start)
108 : cmd(latex), file(f), path(p), lpath(lp), runparams(rp), biber(false),
109 allow_cancel(allow_cancellation)
112 // lualatex can still produce a DVI with --output-format=dvi. However,
113 // we do not use that internally (we use the "dvilualatex" command) so
114 // it would only happen from a custom converter. Thus, it is better to
115 // guess that lualatex produces a PDF than to guess a DVI.
116 // FIXME we should base the extension on the output format, which we should
117 // get in a robust way, e.g. from the converter.
118 if (prefixIs(cmd, "pdf") || prefixIs(cmd, "lualatex") || prefixIs(cmd, "xelatex")) {
119 depfile = FileName(file.absFileName() + ".dep-pdf");
121 FileName(changeExtension(file.absFileName(), ".pdf"));
123 depfile = FileName(file.absFileName() + ".dep");
125 FileName(changeExtension(file.absFileName(), ".dvi"));
128 removeAuxiliaryFiles();
132 void LaTeX::removeAuxiliaryFiles() const
134 // Note that we do not always call this function when there is an error.
135 // For example, if there is an error but an output file is produced we
136 // still would like to output (export/view) the file.
138 // What files do we have to delete?
140 // This will at least make latex do all the runs
141 depfile.removeFile();
143 // but the reason for the error might be in a generated file...
146 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
150 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
154 FileName const ind(changeExtension(file.absFileName(), ".ind"));
158 FileName const nls(changeExtension(file.absFileName(), ".nls"));
161 // nomencl file (old version of the package)
162 FileName const gls(changeExtension(file.absFileName(), ".gls"));
166 FileName const ent(changeExtension(file.absFileName(), ".ent"));
169 // Also remove the aux file
170 FileName const aux(changeExtension(file.absFileName(), ".aux"));
173 // Also remove the .out file (e.g. hyperref bookmarks) (#9963)
174 FileName const out(changeExtension(file.absFileName(), ".out"));
177 // Remove the output file, which is often generated even if error
178 output_file.removeFile();
182 int LaTeX::run(TeXErrors & terr)
183 // We know that this function will only be run if the lyx buffer
184 // has been changed. We also know that a newly written .tex file
185 // is always different from the previous one because of the date
186 // in it. However it seems safe to run latex (at least) one time
187 // each time the .tex file changes.
189 int scanres = NO_ERRORS;
190 int bscanres = NO_ERRORS;
191 int iscanres = NO_ERRORS;
192 unsigned int count = 0; // number of times run
193 num_errors = 0; // just to make sure.
194 unsigned int const MAX_RUN = 6;
195 DepTable head; // empty head
196 bool rerun = false; // rerun requested
198 // The class LaTeX does not know the temp path.
199 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
203 // first check if the file dependencies exist:
204 // ->If it does exist
205 // check if any of the files mentioned in it have
206 // changed (done using a checksum).
208 // run latex once and
209 // remake the dependency file
210 // -> if not changed:
211 // just return there is nothing to do for us.
212 // ->if it doesn't exist
214 // run latex once (we need to run latex once anyway) and
215 // remake the dependency file.
218 bool had_depfile = depfile.exists();
219 bool run_bibtex = false;
220 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
223 LYXERR(Debug::DEPEND, "Dependency file exists");
224 // Read the dep file:
225 had_depfile = head.read(depfile);
229 // Update the checksums
231 // Can't just check if anything has changed because it might
232 // have aborted on error last time... in which cas we need
233 // to re-run latex and collect the error messages
234 // (even if they are the same).
235 if (!output_file.exists()) {
236 LYXERR(Debug::DEPEND,
237 "re-running LaTeX because output file doesn't exist.");
238 } else if (!head.sumchange()) {
239 LYXERR(Debug::DEPEND, "return no_change");
242 LYXERR(Debug::DEPEND, "Dependency file has changed");
245 if (head.extchanged(".bib") || head.extchanged(".bst"))
248 LYXERR(Debug::DEPEND,
249 "Dependency file does not exist, or has wrong format");
251 /// We scan the aux file even when had_depfile = false,
252 /// because we can run pdflatex on the file after running latex on it,
253 /// in which case we will not need to run bibtex again.
254 vector<AuxInfo> bibtex_info_old;
256 bibtex_info_old = scanAuxFiles(aux_file, runparams.only_childbibs);
259 LYXERR(Debug::LATEX, "Run #" << count);
260 message(runMessage(count));
262 int exit_code = startscript();
263 if (exit_code == Systemcall::KILLED)
264 return Systemcall::KILLED;
266 scanres = scanLogFile(terr);
267 if (scanres & ERROR_RERUN) {
268 LYXERR(Debug::LATEX, "Rerunning LaTeX");
270 exit_code = startscript();
271 if (exit_code == Systemcall::KILLED)
272 return Systemcall::KILLED;
273 scanres = scanLogFile(terr);
276 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file, runparams.only_childbibs);
277 if (!run_bibtex && bibtex_info_old != bibtex_info)
280 // update the dependencies.
281 deplog(head); // reads the latex log
285 // At this point we must run external programs if needed.
286 // makeindex will be run if a .idx file changed or was generated.
287 // And if there were undefined citations or changes in references
288 // the .aux file is checked for signs of bibtex. Bibtex is then run
291 // memoir (at least) writes an empty *idx file in the first place.
292 // A second latex run is needed.
293 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
294 rerun = idxfile.exists() && idxfile.isFileEmpty();
297 if (head.haschanged(idxfile)) {
299 LYXERR(Debug::LATEX, "Running MakeIndex.");
300 message(_("Running Index Processor."));
301 // onlyFileName() is needed for cygwin
303 runMakeIndex(onlyFileName(idxfile.absFileName()), runparams);
304 if (ret == Systemcall::KILLED)
305 return Systemcall::KILLED;
306 FileName const ilgfile(changeExtension(file.absFileName(), ".ilg"));
307 if (ilgfile.exists())
308 iscanres = scanIlgFile(terr);
312 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
313 // If all nomencl entries are removed, nomencl writes an empty nlo file.
314 // DepTable::hasChanged() returns false in this case, since it does not
315 // distinguish empty files from non-existing files. This is why we need
316 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
317 // FIXME: Sort out the real problem in DepTable.
318 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty())) {
319 int const ret = runMakeIndexNomencl(file, ".nlo", ".nls");
320 if (ret == Systemcall::KILLED)
321 return Systemcall::KILLED;
325 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
326 if (head.haschanged(glofile)) {
327 int const ret = runMakeIndexNomencl(file, ".glo", ".gls");
334 // check if we're using biber instead of bibtex
335 // biber writes no info to the aux file, so we just check
336 // if a bcf file exists (and if it was updated)
337 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
338 biber |= head.exist(bcffile);
341 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
342 if (scanres & UNDEF_CIT || run_bibtex) {
343 // Here we must scan the .aux file and look for
344 // "\bibdata" and/or "\bibstyle". If one of those
345 // tags is found -> run bibtex and set rerun = true;
347 LYXERR(Debug::LATEX, "Running BibTeX.");
348 message(_("Running BibTeX."));
349 updateBibtexDependencies(head, bibtex_info);
351 rerun |= runBibTeX(bibtex_info, runparams, exit_code);
352 if (exit_code == Systemcall::KILLED)
353 return Systemcall::KILLED;
354 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
355 if (blgfile.exists())
356 bscanres = scanBlgFile(head, terr);
357 } else if (!had_depfile) {
358 /// If we run pdflatex on the file after running latex on it,
359 /// then we do not need to run bibtex, but we do need to
360 /// insert the .bib and .bst files into the .dep-pdf file.
361 updateBibtexDependencies(head, bibtex_info);
365 // we know on this point that latex has been run once (or we just
366 // returned) and the question now is to decide if we need to run
367 // it any more. This is done by asking if any of the files in the
368 // dependency file has changed. (remember that the checksum for
369 // a given file is reported to have changed if it just was created)
370 // -> if changed or rerun == true:
371 // run latex once more and
372 // update the dependency structure
373 // -> if not changed:
374 // we do nothing at this point
376 if (rerun || head.sumchange()) {
379 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
380 LYXERR(Debug::LATEX, "Run #" << count);
381 message(runMessage(count));
382 int exit_code = startscript();
383 if (exit_code == Systemcall::KILLED)
384 return Systemcall::KILLED;
385 scanres = scanLogFile(terr);
387 // update the depedencies
388 deplog(head); // reads the latex log
391 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
396 // Complex bibliography packages such as Biblatex require
397 // an additional bibtex cycle sometimes.
398 if (scanres & UNDEF_CIT) {
399 // Here we must scan the .aux file and look for
400 // "\bibdata" and/or "\bibstyle". If one of those
401 // tags is found -> run bibtex and set rerun = true;
403 LYXERR(Debug::LATEX, "Running BibTeX.");
404 message(_("Running BibTeX."));
405 updateBibtexDependencies(head, bibtex_info);
407 rerun |= runBibTeX(bibtex_info, runparams, exit_code);
408 if (exit_code == Systemcall::KILLED)
409 return Systemcall::KILLED;
410 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
411 if (blgfile.exists())
412 bscanres = scanBlgFile(head, terr);
416 // The inclusion of files generated by external programs such as
417 // makeindex or bibtex might have done changes to pagenumbering,
418 // etc. And because of this we must run the external programs
419 // again to make sure everything is redone correctly.
420 // Also there should be no need to run the external programs any
423 // run makeindex if the <file>.idx has changed or was generated.
424 if (head.haschanged(idxfile)) {
426 LYXERR(Debug::LATEX, "Running MakeIndex.");
427 message(_("Running Index Processor."));
428 // onlyFileName() is needed for cygwin
429 int const ret = runMakeIndex(onlyFileName(changeExtension(
430 file.absFileName(), ".idx")), runparams);
431 if (ret == Systemcall::KILLED)
432 return Systemcall::KILLED;
433 FileName const ilgfile(changeExtension(file.absFileName(), ".ilg"));
434 if (ilgfile.exists())
435 iscanres = scanIlgFile(terr);
439 // MSVC complains that bool |= int is unsafe. Not sure why.
440 if (head.haschanged(nlofile))
441 rerun |= (runMakeIndexNomencl(file, ".nlo", ".nls") != 0);
442 if (head.haschanged(glofile))
443 rerun |= (runMakeIndexNomencl(file, ".glo", ".gls") != 0);
446 // we will only run latex more if the log file asks for it.
447 // or if the sumchange() is true.
448 // -> rerun asked for:
450 // remake the dependency file
451 // goto 2 or return if max runs are reached.
452 // -> rerun not asked for:
453 // just return (fall out of bottom of func)
455 while ((head.sumchange() || rerun || (scanres & RERUN))
456 && count < MAX_RUN) {
457 // Yes rerun until message goes away, or until
458 // MAX_RUNS are reached.
461 LYXERR(Debug::LATEX, "Run #" << count);
462 message(runMessage(count));
464 scanres = scanLogFile(terr);
470 // Write the dependencies to file.
474 // add flag here, just before return, instead of when exit_code
475 // is defined because scanres is sometimes overwritten above
477 scanres |= NONZERO_ERROR;
480 LYXERR(Debug::LATEX, "Done.");
482 if (bscanres & ERRORS)
483 return bscanres; // return on error
485 if (iscanres & ERRORS)
486 return iscanres; // return on error
492 int LaTeX::startscript()
494 // onlyFileName() is needed for cygwin
495 string tmp = cmd + ' '
496 + quoteName(onlyFileName(file.toFilesystemEncoding()))
497 + " > " + os::nulldev();
499 Systemcall::Starttype const starttype =
500 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
501 return one.startscript(starttype, tmp, path, lpath, true);
505 int LaTeX::runMakeIndex(string const & f, OutputParams const & rp,
506 string const & params)
508 string tmp = rp.use_japanese ?
509 lyxrc.jindex_command : lyxrc.index_command;
511 if (!rp.index_command.empty())
512 tmp = rp.index_command;
514 if (contains(tmp, "$$x")) {
515 // This adds appropriate [te]xindy options
516 // such as language and codepage (for the
517 // main document language/encoding)
518 string xdyopts = rp.xindy_language;
519 if (!xdyopts.empty())
520 xdyopts = "-L " + xdyopts;
521 if (rp.encoding->iconvName() == "UTF-8") {
522 if (!xdyopts.empty())
524 xdyopts += "-C utf8";
526 tmp = subst(tmp, "$$x", xdyopts);
529 if (contains(tmp, "$$b")) {
530 // advise xindy to write a log file
531 tmp = subst(tmp, "$$b", removeExtension(f));
535 "idx file has been made, running index processor ("
536 << tmp << ") on file " << f);
538 tmp = subst(tmp, "$$lang", rp.document_language);
539 if (rp.use_indices) {
540 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
542 "Multiple indices. Using splitindex command: " << tmp);
548 Systemcall::Starttype const starttype =
549 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
550 return one.startscript(starttype, tmp, path, lpath, true);
554 int LaTeX::runMakeIndexNomencl(FileName const & fname,
555 string const & nlo, string const & nls)
557 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
558 message(_("Running MakeIndex for nomencl."));
559 string tmp = lyxrc.nomencl_command + ' ';
560 // onlyFileName() is needed for cygwin
561 tmp += quoteName(onlyFileName(changeExtension(fname.absFileName(), nlo)));
563 + onlyFileName(changeExtension(fname.toFilesystemEncoding(), nls));
565 Systemcall::Starttype const starttype =
566 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
567 return one.startscript(starttype, tmp, path, lpath, true);
571 vector<AuxInfo> const
572 LaTeX::scanAuxFiles(FileName const & fname, bool const only_childbibs)
574 vector<AuxInfo> result;
576 // With chapterbib, we have to bibtex all children's aux files
577 // but _not_ the master's!
578 if (only_childbibs) {
579 for (string const &s: children) {
581 makeAbsPath(s, fname.onlyPath().realPath());
582 fn.changeExtension("aux");
584 result.push_back(scanAuxFile(fn));
589 result.push_back(scanAuxFile(fname));
591 // This is for bibtopic
592 string const basename = removeExtension(fname.absFileName());
593 for (int i = 1; i < 1000; ++i) {
594 FileName const file2(basename
595 + '.' + convert<string>(i)
599 result.push_back(scanAuxFile(file2));
605 AuxInfo const LaTeX::scanAuxFile(FileName const & fname)
608 result.aux_file = fname;
609 scanAuxFile(fname, result);
614 void LaTeX::scanAuxFile(FileName const & fname, AuxInfo & aux_info)
616 LYXERR(Debug::LATEX, "Scanning aux file: " << fname);
618 ifstream ifs(fname.toFilesystemEncoding().c_str());
620 static regex const reg1("\\\\citation\\{([^}]+)\\}");
621 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
622 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
623 static regex const reg4("\\\\@input\\{([^}]+)\\}");
625 while (getline(ifs, token)) {
626 token = rtrim(token, "\r");
628 // FIXME UNICODE: We assume that citation keys and filenames
629 // in the aux file are in the file system encoding.
630 token = to_utf8(from_filesystem8bit(token));
631 if (regex_match(token, sub, reg1)) {
632 string data = sub.str(1);
633 while (!data.empty()) {
635 data = split(data, citation, ',');
636 LYXERR(Debug::LATEX, "Citation: " << citation);
637 aux_info.citations.insert(citation);
639 } else if (regex_match(token, sub, reg2)) {
640 string data = sub.str(1);
641 // data is now all the bib files separated by ','
642 // get them one by one and pass them to the helper
643 while (!data.empty()) {
645 data = split(data, database, ',');
646 database = changeExtension(database, "bib");
647 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
648 aux_info.databases.insert(database);
650 } else if (regex_match(token, sub, reg3)) {
651 string style = sub.str(1);
652 // token is now the style file
653 // pass it to the helper
654 style = changeExtension(style, "bst");
655 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
656 aux_info.styles.insert(style);
657 } else if (regex_match(token, sub, reg4)) {
658 string const file2 = sub.str(1);
659 scanAuxFile(makeAbsPath(file2), aux_info);
665 void LaTeX::updateBibtexDependencies(DepTable & dep,
666 vector<AuxInfo> const & bibtex_info)
668 // Since a run of Bibtex mandates more latex runs it is ok to
669 // remove all ".bib" and ".bst" files.
670 dep.remove_files_with_extension(".bib");
671 dep.remove_files_with_extension(".bst");
672 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
674 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
675 it != bibtex_info.end(); ++it) {
676 for (set<string>::const_iterator it2 = it->databases.begin();
677 it2 != it->databases.end(); ++it2) {
678 FileName const file = findtexfile(*it2, "bib");
680 dep.insert(file, true);
683 for (set<string>::const_iterator it2 = it->styles.begin();
684 it2 != it->styles.end(); ++it2) {
685 FileName const file = findtexfile(*it2, "bst");
687 dep.insert(file, true);
691 // biber writes nothing into the aux file.
692 // Instead, we have to scan the blg file
695 scanBlgFile(dep, terr);
700 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
701 OutputParams const & rp, int & exit_code)
705 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
706 it != bibtex_info.end(); ++it) {
707 if (!biber && it->databases.empty())
711 string tmp = rp.bibtex_command;
713 // onlyFileName() is needed for cygwin
714 tmp += quoteName(onlyFileName(removeExtension(
715 it->aux_file.absFileName())));
717 Systemcall::Starttype const starttype =
718 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
719 exit_code = one.startscript(starttype, tmp, path, lpath, true);
724 // Return whether bibtex was run
729 //helper func for scanLogFile; gets line number X from strings "... on input line X ..."
730 //returns 0 if none is found
731 int getLineNumber(const string &token){
732 string l = support::token(token, ' ', tokenPos(token,' ',"line") + 1);
733 return l.empty() ? 0 : convert<int>(l);
737 int LaTeX::scanLogFile(TeXErrors & terr)
741 int retval = NO_ERRORS;
743 onlyFileName(changeExtension(file.absFileName(), ".log"));
744 LYXERR(Debug::LATEX, "Log file: " << tmp);
745 FileName const fn = FileName(makeAbsPath(tmp));
746 // FIXME we should use an ifdocstream here and a docstring for token
747 // below. The encoding of the log file depends on the _output_ (font)
748 // encoding of the TeX file (T1, TU etc.). See #10728.
749 ifstream ifs(fn.toFilesystemEncoding().c_str());
750 bool fle_style = false;
751 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
752 static regex const child_file("[^0-9]*([0-9]+[A-Za-z]*_.+\\.tex).*");
753 // Flag for 'File ended while scanning' message.
754 // We need to wait for subsequent processing.
755 string wait_for_error;
758 stack <pair<string, int> > child;
764 while (getline(ifs, token)) {
765 // MikTeX sometimes inserts \0 in the log file. They can't be
766 // removed directly with the existing string utility
767 // functions, so convert them first to \r, and remove all
768 // \r's afterwards, since we need to remove them anyway.
769 token = subst(token, '\0', '\r');
770 token = subst(token, "\r", "");
773 LYXERR(Debug::LATEX, "Log line: " << token);
778 // Track child documents
779 for (size_t i = 0; i < token.length(); ++i) {
780 if (token[i] == '(') {
782 size_t j = token.find('(', i + 1);
783 size_t len = j == string::npos
784 ? token.substr(i + 1).length()
786 string const substr = token.substr(i + 1, len);
787 if (regex_match(substr, sub, child_file)) {
788 string const name = sub.str(1);
789 // Sometimes also masters have a name that matches
790 // (if their name starts with a number and _)
791 if (name != file.onlyFileName()) {
792 child.push(make_pair(name, pnest));
793 children.push_back(name);
797 } else if (token[i] == ')') {
799 && child.top().second == pnest)
804 child_name = child.empty() ? empty_string() : child.top().first;
806 if (contains(token, "file:line:error style messages enabled"))
809 //Handles both "LaTeX Warning:" & "Package natbib Warning:"
810 //Various handlers for missing citations below won't catch the problem if citation
811 //key is long (>~25chars), because pdflatex splits output at line length 80.
812 //TODO: TL 2020 engines will contain new commandline switch --cnf-line which we
813 //can use to set max_print_line variable for appropriate length and detect all
815 if (contains(token, "There were undefined citations.") ||
816 prefixIs(token, "Package biblatex Warning: The following entry could not be found"))
819 if (prefixIs(token, "LaTeX Warning:") ||
820 prefixIs(token, "! pdfTeX warning")) {
821 // Here shall we handle different
823 retval |= LATEX_WARNING;
824 LYXERR(Debug::LATEX, "LaTeX Warning.");
825 if (contains(token, "Rerun to get cross-references")) {
827 LYXERR(Debug::LATEX, "We should rerun.");
828 // package clefval needs 2 latex runs before bibtex
829 } else if (contains(token, "Value of")
830 && contains(token, "on page")
831 && contains(token, "undefined")) {
832 retval |= ERROR_RERUN;
833 LYXERR(Debug::LATEX, "Force rerun.");
835 } else if (contains(token, "Etaremune labels have changed")) {
836 retval |= ERROR_RERUN;
837 LYXERR(Debug::LATEX, "Force rerun.");
839 } else if (contains(token, "Endnotes may have changed. Rerun")) {
841 LYXERR(Debug::LATEX, "We should rerun.");
842 //"Citation `cit' on page X undefined on input line X."
843 } else if (contains(token, "Citation")
844 //&& contains(token, "on input line") //often split to newline
845 && contains(token, "undefined")) {
847 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
848 from_utf8(token), child_name);
849 //"Reference `X' on page Y undefined on input line Z."
850 } else if (contains(token, "Reference")
851 //&& contains(token, "on input line")) //often split to new line
852 && contains(token, "undefined")) {
854 terr.insertRef(getLineNumber(token), from_ascii("Reference undefined"),
855 from_utf8(token), child_name);
857 //If label is too long pdlaftex log line splitting will make the above fail
858 //so we catch at least this generic statement occuring for both CIT & REF.
859 } else if (contains(token, "There were undefined references.")) {
860 if (!(retval & UNDEF_CIT)) //if not handled already
864 } else if (prefixIs(token, "Package")) {
866 retval |= PACKAGE_WARNING;
867 if (contains(token, "natbib Warning:")) {
869 if (contains(token, "Citation")
870 && contains(token, "on page")
871 && contains(token, "undefined")) {
873 //Unf only keys up to ~6 chars will make it due to line splits
874 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
875 from_utf8(token), child_name);
877 } else if (contains(token, "run BibTeX")) {
879 } else if (contains(token, "run Biber")) {
882 } else if (contains(token, "Rerun LaTeX") ||
883 contains(token, "Please rerun LaTeX") ||
884 contains(token, "Rerun to get")) {
885 // at least longtable.sty and bibtopic.sty
887 LYXERR(Debug::LATEX, "We should rerun.");
890 } else if (prefixIs(token, "LETTRE WARNING:")) {
891 if (contains(token, "veuillez recompiler")) {
893 LYXERR(Debug::LATEX, "We should rerun.");
896 } else if (token[0] == '(') {
897 if (contains(token, "Rerun LaTeX") ||
898 contains(token, "Rerun to get")) {
900 LYXERR(Debug::LATEX, "We should rerun.");
903 } else if (prefixIs(token, "! ")
905 && regex_match(token, sub, file_line_error)
906 && !contains(token, "pdfTeX warning"))) {
907 // Ok, we have something that looks like a TeX Error
908 // but what do we really have.
910 // Just get the error description:
912 if (prefixIs(token, "! "))
913 desc = string(token, 2);
916 if (contains(token, "LaTeX Error:"))
917 retval |= LATEX_ERROR;
919 if (prefixIs(token, "! File ended while scanning")) {
920 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
921 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
922 retval |= ERROR_RERUN;
923 LYXERR(Debug::LATEX, "Force rerun.");
925 // bug 6445. At this point its not clear we finish with error.
926 wait_for_error = desc;
931 if (prefixIs(token, "! Incomplete \\if")) {
932 // bug 10666. At this point its not clear we finish with error.
933 wait_for_error = desc;
937 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
938 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
939 retval |= ERROR_RERUN;
940 LYXERR(Debug::LATEX, "Force rerun.");
943 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
944 retval |= LATEX_ERROR;
947 errstr = wait_for_error;
948 wait_for_error.clear();
950 if (!getline(ifs, tmp))
952 tmp = rtrim(tmp, "\r");
953 errstr += "\n" + tmp;
956 } while (!contains(tmp, "(job aborted"));
959 from_ascii("Emergency stop"),
960 from_local8bit(errstr),
967 if (!getline(ifs, tmp))
969 tmp = rtrim(tmp, "\r");
970 // 15 is somewhat arbitrarily chosen, based on practice.
971 // We used 10 for 14 years and increased it to 15 when we
975 } while (!prefixIs(tmp, "l."));
976 if (prefixIs(tmp, "l.")) {
977 // we have a latex error
980 "Package babel Error: You haven't defined the language")
982 "Package babel Error: You haven't loaded the option")
984 "Package babel Error: Unknown language"))
985 retval |= ERROR_RERUN;
986 // get the line number:
988 sscanf(tmp.c_str(), "l.%d", &line);
989 // get the rest of the message:
990 string errstr(tmp, tmp.find(' '));
993 tmp = rtrim(tmp, "\r");
994 while (!contains(errstr, "l.")
996 && !prefixIs(tmp, "! ")
997 && !contains(tmp, "(job aborted")) {
1001 tmp = rtrim(tmp, "\r");
1003 LYXERR(Debug::LATEX, "line: " << line << '\n'
1004 << "Desc: " << desc << '\n' << "Text: " << errstr);
1005 if (line == last_line)
1011 if (line_count <= 5) {
1013 // We have no idea what the encoding of
1015 // It seems that the output from the
1016 // latex compiler itself is pure ASCII,
1017 // but it can include bits from the
1018 // document, so whatever encoding we
1019 // assume here it can be wrong.
1020 terr.insertError(line,
1021 from_local8bit(desc),
1022 from_local8bit(errstr),
1028 // information messages, TeX warnings and other
1029 // warnings we have not caught earlier.
1030 if (prefixIs(token, "Overfull ")) {
1031 retval |= TEX_WARNING;
1032 } else if (prefixIs(token, "Underfull ")) {
1033 retval |= TEX_WARNING;
1034 } else if (contains(token, "Rerun to get citations")) {
1035 // Natbib seems to use this.
1036 retval |= UNDEF_CIT;
1037 } else if (contains(token, "No pages of output")
1038 || contains(token, "no pages of output")) {
1039 // No output file (e.g. the DVI or PDF) was created
1040 retval |= NO_OUTPUT;
1041 } else if (contains(token, "Error 256 (driver return code)")) {
1042 // This is a xdvipdfmx driver error reported by XeTeX.
1043 // We have to check whether an output PDF file was created.
1044 FileName pdffile = file;
1045 pdffile.changeExtension("pdf");
1046 if (!pdffile.exists())
1047 // No output PDF file was created (see #10076)
1048 retval |= NO_OUTPUT;
1049 } else if (contains(token, "That makes 100 errors")) {
1050 // More than 100 errors were reported
1051 retval |= TOO_MANY_ERRORS;
1052 } else if (prefixIs(token, "!pdfTeX error:")) {
1053 // otherwise we dont catch e.g.:
1054 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
1057 from_ascii("pdfTeX Error"),
1058 from_local8bit(token),
1060 } else if (!ignore_missing_glyphs
1061 && prefixIs(token, "Missing character: There is no ")
1062 && !contains(token, "nullfont")) {
1063 // Warning about missing glyph in selected font
1064 // may be dataloss (bug 9610)
1065 // but can be ignored for 'nullfont' (bug 10394).
1066 // as well as for ZERO WIDTH NON-JOINER (0x200C) which is
1067 // missing in many fonts and output for ligature break (bug 10727).
1068 // Since this error only occurs with utf8 output, we can safely assume
1069 // that the log file is utf8-encoded
1070 docstring const utoken = from_utf8(token);
1071 if (!contains(utoken, 0x200C)) {
1072 retval |= LATEX_ERROR;
1074 from_ascii("Missing glyphs!"),
1078 } else if (!wait_for_error.empty()) {
1079 // We collect information until we know we have an error.
1080 wait_for_error += token + '\n';
1084 LYXERR(Debug::LATEX, "Log line: " << token);
1091 bool insertIfExists(FileName const & absname, DepTable & head)
1093 if (absname.exists() && !absname.isDirectory()) {
1094 head.insert(absname, true);
1101 bool handleFoundFile(string const & ff, DepTable & head)
1103 // convert from native os path to unix path
1104 string foundfile = os::internal_path(trim(ff));
1106 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
1108 // Ok now we found a file.
1109 // Now we should make sure that this is a file that we can
1110 // access through the normal paths.
1111 // We will not try any fancy search methods to
1114 // (1) foundfile is an
1115 // absolute path and should
1118 if (FileName::isAbsolute(foundfile)) {
1119 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
1120 // On initial insert we want to do the update at once
1121 // since this file cannot be a file generated by
1123 absname.set(foundfile);
1124 if (!insertIfExists(absname, head)) {
1126 string strippedfile = foundfile;
1127 while (contains(strippedfile, " ")) {
1128 // files with spaces are often enclosed in quotation
1129 // marks; those have to be removed
1130 string unquoted = subst(strippedfile, "\"", "");
1131 absname.set(unquoted);
1132 if (insertIfExists(absname, head))
1134 // strip off part after last space and try again
1135 string tmp = strippedfile;
1136 rsplit(tmp, strippedfile, ' ');
1137 absname.set(strippedfile);
1138 if (insertIfExists(absname, head))
1144 string onlyfile = onlyFileName(foundfile);
1145 absname = makeAbsPath(onlyfile);
1148 while (contains(foundfile, ' ')) {
1149 if (absname.exists())
1153 // files with spaces are often enclosed in quotation
1154 // marks; those have to be removed
1155 string unquoted = subst(foundfile, "\"", "");
1156 absname = makeAbsPath(unquoted);
1157 if (absname.exists())
1159 // strip off part after last space and try again
1160 string strippedfile;
1161 rsplit(foundfile, strippedfile, ' ');
1162 foundfile = strippedfile;
1163 onlyfile = onlyFileName(strippedfile);
1164 absname = makeAbsPath(onlyfile);
1168 // (2) foundfile is in the tmpdir
1169 // insert it into head
1170 if (absname.exists() && !absname.isDirectory()) {
1171 // FIXME: This regex contained glo, but glo is used by the old
1172 // version of nomencl.sty. Do we need to put it back?
1173 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1174 if (regex_match(onlyfile, unwanted)) {
1175 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1176 << " in the dep file");
1177 } else if (suffixIs(onlyfile, ".tex")) {
1178 // This is a tex file generated by LyX
1179 // and latex is not likely to change this
1181 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1182 head.insert(absname, true);
1184 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1185 head.insert(absname);
1189 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1195 bool completeFilename(string const & ff, DepTable & head)
1197 // If we do not find a dot, we suspect
1198 // a fragmental file name
1199 if (!contains(ff, '.'))
1202 // if we have a dot, we let handleFoundFile decide
1203 return handleFoundFile(ff, head);
1207 int iterateLine(string const & token, regex const & reg, string const & opening,
1208 string const & closing, int fragment_pos, DepTable & head)
1211 string::const_iterator first = token.begin();
1212 string::const_iterator end = token.end();
1213 bool fragment = false;
1216 while (regex_search(first, end, what, reg)) {
1217 // if we have a dot, try to handle as file
1218 if (contains(what.str(1), '.')) {
1219 first = what[0].second;
1220 if (what.str(2) == closing) {
1221 handleFoundFile(what.str(1), head);
1222 // since we had a closing bracket,
1223 // do not investigate further
1225 } else if (what.str(2) == opening) {
1226 // if we have another opening bracket,
1227 // we might have a nested file chain
1228 // as is (file.ext (subfile.ext))
1229 fragment = !handleFoundFile(rtrim(what.str(1)), head);
1230 // decrease first position by one in order to
1231 // consider the opening delimiter on next iteration
1232 if (first > token.begin())
1235 // if we have no closing bracket,
1236 // try to handle as file nevertheless
1237 fragment = !handleFoundFile(
1238 what.str(1) + what.str(2), head);
1240 // if we do not have a dot, check if the line has
1241 // a closing bracket (else, we suspect a line break)
1242 else if (what.str(2) != closing) {
1243 first = what[0].second;
1246 // we have a closing bracket, so the content
1247 // is not a file name.
1248 // no need to investigate further
1249 first = what[0].second;
1252 last_match = what.str(1);
1255 // We need to consider the result from previous line iterations:
1256 // We might not find a fragment here, but another one might follow
1257 // E.g.: (filename.ext) <filenam
1258 // Vice versa, we consider the search completed if a real match
1259 // follows a potential fragment from a previous iteration.
1260 // E.g. <some text we considered a fragment (filename.ext)
1261 // result = -1 means we did not find a fragment!
1263 int last_match_pos = -1;
1264 if (!last_match.empty() && token.find(last_match) != string::npos)
1265 last_match_pos = int(token.find(last_match));
1267 if (last_match_pos > fragment_pos)
1268 result = last_match_pos;
1270 result = fragment_pos;
1272 if (last_match_pos < fragment_pos)
1273 result = fragment_pos;
1281 void LaTeX::deplog(DepTable & head)
1283 // This function reads the LaTeX log file end extracts all the
1284 // external files used by the LaTeX run. The files are then
1285 // entered into the dependency file.
1287 string const logfile =
1288 onlyFileName(changeExtension(file.absFileName(), ".log"));
1290 static regex const reg1("File: (.+).*");
1291 static regex const reg2("No file (.+)(.).*");
1292 static regex const reg3a("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1293 // LuaTeX has a slightly different output
1294 static regex const reg3b("\\\\openout[0-9]+.*=\\s*(.+)");
1295 // If an index should be created, MikTex does not write a line like
1296 // \openout# = 'sample.idx'.
1297 // but instead only a line like this into the log:
1298 // Writing index file sample.idx
1299 static regex const reg4("Writing index file (.+).*");
1300 static regex const regoldnomencl("Writing glossary file (.+).*");
1301 static regex const regnomencl(".*Writing nomenclature file (.+).*");
1302 // If a toc should be created, MikTex does not write a line like
1303 // \openout# = `sample.toc'.
1304 // but only a line like this into the log:
1306 // This line is also written by tetex.
1307 // This line is not present if no toc should be created.
1308 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1309 // file names can be enclosed in <...> (anywhere on the line)
1310 static regex const reg5(".*<[^>]+.*");
1311 // and also (...) anywhere on the line
1312 static regex const reg6(".*\\([^)]+.*");
1314 FileName const fn = makeAbsPath(logfile);
1315 ifstream ifs(fn.toFilesystemEncoding().c_str());
1318 // Ok, the scanning of files here is not sufficient.
1319 // Sometimes files are named by "File: xxx" only
1320 // Therefore we use some regexps to find files instead.
1321 // Note: all file names and paths might contains spaces.
1322 // Also, file names might be broken across lines. Therefore
1323 // we mark (potential) fragments and merge those lines.
1324 bool fragment = false;
1326 getline(ifs, token);
1327 // MikTeX sometimes inserts \0 in the log file. They can't be
1328 // removed directly with the existing string utility
1329 // functions, so convert them first to \r, and remove all
1330 // \r's afterwards, since we need to remove them anyway.
1331 token = subst(token, '\0', '\r');
1332 token = subst(token, "\r", "");
1333 if (token.empty() || token == ")") {
1334 lastline = string();
1338 // FIXME UNICODE: We assume that the file names in the log
1339 // file are in the file system encoding.
1340 token = to_utf8(from_filesystem8bit(token));
1342 // Sometimes, filenames are broken across lines.
1343 // We care for that and save suspicious lines.
1344 // Here we exclude some cases where we are sure
1345 // that there is no continued filename
1346 if (!lastline.empty()) {
1347 static regex const package_info("Package \\w+ Info: .*");
1348 static regex const package_warning("Package \\w+ Warning: .*");
1349 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1350 || prefixIs(token, "Package:")
1351 || prefixIs(token, "Language:")
1352 || prefixIs(token, "LaTeX Info:")
1353 || prefixIs(token, "LaTeX Font Info:")
1354 || prefixIs(token, "\\openout[")
1355 || prefixIs(token, "))")
1356 || regex_match(token, package_info)
1357 || regex_match(token, package_warning))
1358 lastline = string();
1361 if (!lastline.empty())
1362 // probably a continued filename from last line
1363 token = lastline + token;
1364 if (token.length() > 255) {
1365 // string too long. Cut off.
1366 token.erase(0, token.length() - 251);
1371 // (1) "File: file.ext"
1372 if (regex_match(token, sub, reg1)) {
1373 // is this a fragmental file name?
1374 fragment = !completeFilename(sub.str(1), head);
1376 if (suffixIs(token, ")"))
1377 // no fragment for sure
1379 // (2) "No file file.ext"
1380 } else if (regex_match(token, sub, reg2)) {
1381 // file names must contains a dot, line ends with dot
1382 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1383 fragment = !handleFoundFile(sub.str(1), head);
1385 // we suspect a line break
1387 // (3)(a) "\openout<nr> = `file.ext'."
1388 } else if (regex_match(token, sub, reg3a)) {
1389 // search for closing '. at the end of the line
1390 if (sub.str(2) == "\'.")
1391 fragment = !handleFoundFile(sub.str(1), head);
1393 // potential fragment
1395 // (3)(b) "\openout<nr> = file.ext" (LuaTeX)
1396 } else if (regex_match(token, sub, reg3b)) {
1397 // file names must contains a dot
1398 if (contains(sub.str(1), '.'))
1399 fragment = !handleFoundFile(sub.str(1), head);
1401 // potential fragment
1403 // (4) "Writing index file file.ext"
1404 } else if (regex_match(token, sub, reg4))
1405 // fragmential file name?
1406 fragment = !completeFilename(sub.str(1), head);
1407 // (5) "Writing nomenclature file file.ext"
1408 else if (regex_match(token, sub, regnomencl) ||
1409 regex_match(token, sub, regoldnomencl))
1410 // fragmental file name?
1411 fragment= !completeFilename(sub.str(1), head);
1412 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1413 else if (regex_match(token, sub, miktexTocReg))
1414 fragment = !handleFoundFile(onlyFileName(changeExtension(
1415 file.absFileName(), ".toc")), head);
1417 // not found, but we won't check further
1420 int fragment_pos = -1;
1422 // We can have several of these on one line
1423 // (and in addition to those above)
1424 if (regex_match(token, sub, reg5)) {
1425 // search for strings in <...>
1426 static regex const reg5_1("<([^>]+)(.)");
1427 fragment_pos = iterateLine(token, reg5_1, "<", ">",
1428 fragment_pos, head);
1429 fragment = (fragment_pos != -1);
1433 // We can have several of these on one line
1434 // this must be queried separated, because of
1435 // cases such as "File: file.ext (type eps)"
1436 // where "File: file.ext" would be skipped
1437 if (regex_match(token, sub, reg6)) {
1438 // search for strings in (...)
1439 static regex const reg6_1("\\(([^()]+)(.)");
1440 fragment_pos = iterateLine(token, reg6_1, "(", ")",
1441 fragment_pos, head);
1442 fragment = (fragment_pos != -1);
1446 // probable linebreak within file name:
1450 // no linebreak: reset
1451 lastline = string();
1454 // Make sure that the main .tex file is in the dependency file.
1455 head.insert(file, true);
1459 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1461 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1462 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1464 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1466 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1467 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1468 static regex const bibtexError2("^(.*---while reading file).*$");
1469 static regex const bibtexError3("(A bad cross reference---).*");
1470 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1471 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1472 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1473 int retval = NO_ERRORS;
1476 while (getline(ifs, token)) {
1477 token = rtrim(token, "\r");
1479 // FIXME UNICODE: We assume that citation keys and filenames
1480 // in the aux file are in the file system encoding.
1481 token = to_utf8(from_filesystem8bit(token));
1482 if (regex_match(token, sub, reg1)) {
1483 string data = sub.str(3);
1484 if (!data.empty()) {
1485 LYXERR(Debug::LATEX, "Found bib file: " << data);
1486 handleFoundFile(data, dep);
1489 else if (regex_match(token, sub, bibtexError)
1490 || regex_match(token, sub, bibtexError2)
1491 || regex_match(token, sub, bibtexError4)
1492 || regex_match(token, sub, bibtexError5)) {
1493 retval |= BIBTEX_ERROR;
1494 string errstr = N_("BibTeX error: ") + token;
1496 if ((prefixIs(token, "while executing---line")
1497 || prefixIs(token, "---line ")
1498 || prefixIs(token, "*Please notify the BibTeX"))
1499 && !prevtoken.empty()) {
1500 errstr = N_("BibTeX error: ") + prevtoken;
1501 msg = prevtoken + '\n';
1505 from_local8bit(errstr),
1506 from_local8bit(msg));
1507 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1508 retval |= BIBTEX_ERROR;
1509 string errstr = N_("BibTeX error: ") + prevtoken;
1510 string msg = prevtoken + '\n' + token;
1512 from_local8bit(errstr),
1513 from_local8bit(msg));
1514 } else if (regex_match(token, sub, biberError)) {
1515 retval |= BIBTEX_ERROR;
1516 string errstr = N_("Biber error: ") + sub.str(2);
1519 from_local8bit(errstr),
1520 from_local8bit(msg));
1528 int LaTeX::scanIlgFile(TeXErrors & terr)
1530 FileName const ilg_file(changeExtension(file.absFileName(), "ilg"));
1531 LYXERR(Debug::LATEX, "Scanning ilg file: " << ilg_file);
1533 ifstream ifs(ilg_file.toFilesystemEncoding().c_str());
1535 int retval = NO_ERRORS;
1538 while (getline(ifs, token)) {
1539 token = rtrim(token, "\r");
1541 if (prefixIs(token, "!! "))
1543 else if (!prevtoken.empty()) {
1544 retval |= INDEX_ERROR;
1545 string errstr = N_("Makeindex error: ") + prevtoken;
1546 string msg = prevtoken + '\n';
1549 from_local8bit(errstr),
1550 from_local8bit(msg));
1552 } else if (prefixIs(token, "ERROR: ")) {
1553 retval |= BIBTEX_ERROR;
1554 string errstr = N_("Xindy error: ") + token.substr(6);
1557 from_local8bit(errstr),
1558 from_local8bit(msg));