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) as well
518 // as input markup (latex or xelatex)
519 string xdyopts = rp.xindy_language;
520 if (!xdyopts.empty())
521 xdyopts = "-L " + xdyopts;
522 if (rp.isFullUnicode() && rp.encoding->package() == Encoding::none) {
523 if (!xdyopts.empty())
525 // xelatex includes lualatex
526 xdyopts += "-I xelatex";
528 else if (rp.encoding->iconvName() == "UTF-8") {
529 if (!xdyopts.empty())
531 // -I not really needed for texindy, but for xindy
532 xdyopts += "-C utf8 -I latex";
535 if (!xdyopts.empty())
537 // not really needed for texindy, but for xindy
538 xdyopts += "-I latex";
540 tmp = subst(tmp, "$$x", xdyopts);
543 if (contains(tmp, "$$b")) {
544 // advise xindy to write a log file
545 tmp = subst(tmp, "$$b", removeExtension(f));
549 "idx file has been made, running index processor ("
550 << tmp << ") on file " << f);
552 tmp = subst(tmp, "$$lang", rp.document_language);
553 if (rp.use_indices) {
554 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
556 "Multiple indices. Using splitindex command: " << tmp);
562 Systemcall::Starttype const starttype =
563 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
564 return one.startscript(starttype, tmp, path, lpath, true);
568 int LaTeX::runMakeIndexNomencl(FileName const & fname,
569 string const & nlo, string const & nls)
571 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
572 message(_("Running MakeIndex for nomencl."));
573 string tmp = lyxrc.nomencl_command + ' ';
574 // onlyFileName() is needed for cygwin
575 tmp += quoteName(onlyFileName(changeExtension(fname.absFileName(), nlo)));
577 + onlyFileName(changeExtension(fname.toFilesystemEncoding(), nls));
579 Systemcall::Starttype const starttype =
580 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
581 return one.startscript(starttype, tmp, path, lpath, true);
585 vector<AuxInfo> const
586 LaTeX::scanAuxFiles(FileName const & fname, bool const only_childbibs)
588 vector<AuxInfo> result;
590 // With chapterbib, we have to bibtex all children's aux files
591 // but _not_ the master's!
592 if (only_childbibs) {
593 for (string const &s: children) {
595 makeAbsPath(s, fname.onlyPath().realPath());
596 fn.changeExtension("aux");
598 result.push_back(scanAuxFile(fn));
603 result.push_back(scanAuxFile(fname));
605 // This is for bibtopic
606 string const basename = removeExtension(fname.absFileName());
607 for (int i = 1; i < 1000; ++i) {
608 FileName const file2(basename
609 + '.' + convert<string>(i)
613 result.push_back(scanAuxFile(file2));
619 AuxInfo const LaTeX::scanAuxFile(FileName const & fname)
622 result.aux_file = fname;
623 scanAuxFile(fname, result);
628 void LaTeX::scanAuxFile(FileName const & fname, AuxInfo & aux_info)
630 LYXERR(Debug::LATEX, "Scanning aux file: " << fname);
632 ifstream ifs(fname.toFilesystemEncoding().c_str());
634 static regex const reg1("\\\\citation\\{([^}]+)\\}");
635 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
636 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
637 static regex const reg4("\\\\@input\\{([^}]+)\\}");
639 while (getline(ifs, token)) {
640 token = rtrim(token, "\r");
642 // FIXME UNICODE: We assume that citation keys and filenames
643 // in the aux file are in the file system encoding.
644 token = to_utf8(from_filesystem8bit(token));
645 if (regex_match(token, sub, reg1)) {
646 string data = sub.str(1);
647 while (!data.empty()) {
649 data = split(data, citation, ',');
650 LYXERR(Debug::LATEX, "Citation: " << citation);
651 aux_info.citations.insert(citation);
653 } else if (regex_match(token, sub, reg2)) {
654 string data = sub.str(1);
655 // data is now all the bib files separated by ','
656 // get them one by one and pass them to the helper
657 while (!data.empty()) {
659 data = split(data, database, ',');
660 database = changeExtension(database, "bib");
661 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
662 aux_info.databases.insert(database);
664 } else if (regex_match(token, sub, reg3)) {
665 string style = sub.str(1);
666 // token is now the style file
667 // pass it to the helper
668 style = changeExtension(style, "bst");
669 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
670 aux_info.styles.insert(style);
671 } else if (regex_match(token, sub, reg4)) {
672 string const file2 = sub.str(1);
673 scanAuxFile(makeAbsPath(file2), aux_info);
679 void LaTeX::updateBibtexDependencies(DepTable & dep,
680 vector<AuxInfo> const & bibtex_info)
682 // Since a run of Bibtex mandates more latex runs it is ok to
683 // remove all ".bib" and ".bst" files.
684 dep.remove_files_with_extension(".bib");
685 dep.remove_files_with_extension(".bst");
686 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
688 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
689 it != bibtex_info.end(); ++it) {
690 for (set<string>::const_iterator it2 = it->databases.begin();
691 it2 != it->databases.end(); ++it2) {
692 FileName const file = findtexfile(*it2, "bib");
694 dep.insert(file, true);
697 for (set<string>::const_iterator it2 = it->styles.begin();
698 it2 != it->styles.end(); ++it2) {
699 FileName const file = findtexfile(*it2, "bst");
701 dep.insert(file, true);
705 // biber writes nothing into the aux file.
706 // Instead, we have to scan the blg file
709 scanBlgFile(dep, terr);
714 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
715 OutputParams const & rp, int & exit_code)
719 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
720 it != bibtex_info.end(); ++it) {
721 if (!biber && it->databases.empty())
725 string tmp = rp.bibtex_command;
727 // onlyFileName() is needed for cygwin
728 tmp += quoteName(onlyFileName(removeExtension(
729 it->aux_file.absFileName())));
731 Systemcall::Starttype const starttype =
732 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
733 exit_code = one.startscript(starttype, tmp, path, lpath, true);
738 // Return whether bibtex was run
743 //helper func for scanLogFile; gets line number X from strings "... on input line X ..."
744 //returns 0 if none is found
745 int getLineNumber(const string &token){
746 string l = support::token(token, ' ', tokenPos(token,' ',"line") + 1);
747 return l.empty() ? 0 : convert<int>(l);
751 int LaTeX::scanLogFile(TeXErrors & terr)
755 int retval = NO_ERRORS;
757 onlyFileName(changeExtension(file.absFileName(), ".log"));
758 LYXERR(Debug::LATEX, "Log file: " << tmp);
759 FileName const fn = FileName(makeAbsPath(tmp));
760 // FIXME we should use an ifdocstream here and a docstring for token
761 // below. The encoding of the log file depends on the _output_ (font)
762 // encoding of the TeX file (T1, TU etc.). See #10728.
763 ifstream ifs(fn.toFilesystemEncoding().c_str());
764 bool fle_style = false;
765 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
766 static regex const child_file("[^0-9]*([0-9]+[A-Za-z]*_.+\\.tex).*");
767 // Flag for 'File ended while scanning' message.
768 // We need to wait for subsequent processing.
769 string wait_for_error;
772 stack <pair<string, int> > child;
778 while (getline(ifs, token)) {
779 // MikTeX sometimes inserts \0 in the log file. They can't be
780 // removed directly with the existing string utility
781 // functions, so convert them first to \r, and remove all
782 // \r's afterwards, since we need to remove them anyway.
783 token = subst(token, '\0', '\r');
784 token = subst(token, "\r", "");
787 LYXERR(Debug::LATEX, "Log line: " << token);
792 // Track child documents
793 for (size_t i = 0; i < token.length(); ++i) {
794 if (token[i] == '(') {
796 size_t j = token.find('(', i + 1);
797 size_t len = j == string::npos
798 ? token.substr(i + 1).length()
800 string const substr = token.substr(i + 1, len);
801 if (regex_match(substr, sub, child_file)) {
802 string const name = sub.str(1);
803 // Sometimes also masters have a name that matches
804 // (if their name starts with a number and _)
805 if (name != file.onlyFileName()) {
806 child.push(make_pair(name, pnest));
807 children.push_back(name);
811 } else if (token[i] == ')') {
813 && child.top().second == pnest)
818 child_name = child.empty() ? empty_string() : child.top().first;
820 if (contains(token, "file:line:error style messages enabled"))
823 //Handles both "LaTeX Warning:" & "Package natbib Warning:"
824 //Various handlers for missing citations below won't catch the problem if citation
825 //key is long (>~25chars), because pdflatex splits output at line length 80.
826 //TODO: TL 2020 engines will contain new commandline switch --cnf-line which we
827 //can use to set max_print_line variable for appropriate length and detect all
829 if (contains(token, "There were undefined citations.") ||
830 prefixIs(token, "Package biblatex Warning: The following entry could not be found"))
833 if (prefixIs(token, "LaTeX Warning:") ||
834 prefixIs(token, "! pdfTeX warning")) {
835 // Here shall we handle different
837 retval |= LATEX_WARNING;
838 LYXERR(Debug::LATEX, "LaTeX Warning.");
839 if (contains(token, "Rerun to get cross-references")) {
841 LYXERR(Debug::LATEX, "We should rerun.");
842 // package clefval needs 2 latex runs before bibtex
843 } else if (contains(token, "Value of")
844 && contains(token, "on page")
845 && contains(token, "undefined")) {
846 retval |= ERROR_RERUN;
847 LYXERR(Debug::LATEX, "Force rerun.");
849 } else if (contains(token, "Etaremune labels have changed")) {
850 retval |= ERROR_RERUN;
851 LYXERR(Debug::LATEX, "Force rerun.");
853 } else if (contains(token, "Endnotes may have changed. Rerun")) {
855 LYXERR(Debug::LATEX, "We should rerun.");
856 //"Citation `cit' on page X undefined on input line X."
857 } else if (contains(token, "Citation")
858 //&& contains(token, "on input line") //often split to newline
859 && contains(token, "undefined")) {
861 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
862 from_utf8(token), child_name);
863 //"Reference `X' on page Y undefined on input line Z."
864 } else if (contains(token, "Reference")
865 //&& contains(token, "on input line")) //often split to new line
866 && contains(token, "undefined")) {
868 terr.insertRef(getLineNumber(token), from_ascii("Reference undefined"),
869 from_utf8(token), child_name);
871 //If label is too long pdlaftex log line splitting will make the above fail
872 //so we catch at least this generic statement occuring for both CIT & REF.
873 } else if (contains(token, "There were undefined references.")) {
874 if (!(retval & UNDEF_CIT)) //if not handled already
878 } else if (prefixIs(token, "Package")) {
880 retval |= PACKAGE_WARNING;
881 if (contains(token, "natbib Warning:")) {
883 if (contains(token, "Citation")
884 && contains(token, "on page")
885 && contains(token, "undefined")) {
887 //Unf only keys up to ~6 chars will make it due to line splits
888 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
889 from_utf8(token), child_name);
891 } else if (contains(token, "run BibTeX")) {
893 } else if (contains(token, "run Biber")) {
896 } else if (contains(token, "Rerun LaTeX") ||
897 contains(token, "Please rerun LaTeX") ||
898 contains(token, "Rerun to get")) {
899 // at least longtable.sty and bibtopic.sty
901 LYXERR(Debug::LATEX, "We should rerun.");
904 } else if (prefixIs(token, "LETTRE WARNING:")) {
905 if (contains(token, "veuillez recompiler")) {
907 LYXERR(Debug::LATEX, "We should rerun.");
910 } else if (token[0] == '(') {
911 if (contains(token, "Rerun LaTeX") ||
912 contains(token, "Rerun to get")) {
914 LYXERR(Debug::LATEX, "We should rerun.");
917 } else if (prefixIs(token, "! ")
919 && regex_match(token, sub, file_line_error)
920 && !contains(token, "pdfTeX warning"))) {
921 // Ok, we have something that looks like a TeX Error
922 // but what do we really have.
924 // Just get the error description:
926 if (prefixIs(token, "! "))
927 desc = string(token, 2);
930 if (contains(token, "LaTeX Error:"))
931 retval |= LATEX_ERROR;
933 if (prefixIs(token, "! File ended while scanning")) {
934 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
935 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
936 retval |= ERROR_RERUN;
937 LYXERR(Debug::LATEX, "Force rerun.");
939 // bug 6445. At this point its not clear we finish with error.
940 wait_for_error = desc;
945 if (prefixIs(token, "! Incomplete \\if")) {
946 // bug 10666. At this point its not clear we finish with error.
947 wait_for_error = desc;
951 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
952 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
953 retval |= ERROR_RERUN;
954 LYXERR(Debug::LATEX, "Force rerun.");
957 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
958 retval |= LATEX_ERROR;
961 errstr = wait_for_error;
962 wait_for_error.clear();
964 if (!getline(ifs, tmp))
966 tmp = rtrim(tmp, "\r");
967 errstr += "\n" + tmp;
970 } while (!contains(tmp, "(job aborted"));
973 from_ascii("Emergency stop"),
974 from_local8bit(errstr),
981 if (!getline(ifs, tmp))
983 tmp = rtrim(tmp, "\r");
984 // 15 is somewhat arbitrarily chosen, based on practice.
985 // We used 10 for 14 years and increased it to 15 when we
989 } while (!prefixIs(tmp, "l."));
990 if (prefixIs(tmp, "l.")) {
991 // we have a latex error
994 "Package babel Error: You haven't defined the language")
996 "Package babel Error: You haven't loaded the option")
998 "Package babel Error: Unknown language"))
999 retval |= ERROR_RERUN;
1000 // get the line number:
1002 sscanf(tmp.c_str(), "l.%d", &line);
1003 // get the rest of the message:
1004 string errstr(tmp, tmp.find(' '));
1007 tmp = rtrim(tmp, "\r");
1008 while (!contains(errstr, "l.")
1010 && !prefixIs(tmp, "! ")
1011 && !contains(tmp, "(job aborted")) {
1015 tmp = rtrim(tmp, "\r");
1017 LYXERR(Debug::LATEX, "line: " << line << '\n'
1018 << "Desc: " << desc << '\n' << "Text: " << errstr);
1019 if (line == last_line)
1025 if (line_count <= 5) {
1027 // We have no idea what the encoding of
1029 // It seems that the output from the
1030 // latex compiler itself is pure ASCII,
1031 // but it can include bits from the
1032 // document, so whatever encoding we
1033 // assume here it can be wrong.
1034 terr.insertError(line,
1035 from_local8bit(desc),
1036 from_local8bit(errstr),
1042 // information messages, TeX warnings and other
1043 // warnings we have not caught earlier.
1044 if (prefixIs(token, "Overfull ")) {
1045 retval |= TEX_WARNING;
1046 } else if (prefixIs(token, "Underfull ")) {
1047 retval |= TEX_WARNING;
1048 } else if (contains(token, "Rerun to get citations")) {
1049 // Natbib seems to use this.
1050 retval |= UNDEF_CIT;
1051 } else if (contains(token, "No pages of output")
1052 || contains(token, "no pages of output")) {
1053 // No output file (e.g. the DVI or PDF) was created
1054 retval |= NO_OUTPUT;
1055 } else if (contains(token, "Error 256 (driver return code)")) {
1056 // This is a xdvipdfmx driver error reported by XeTeX.
1057 // We have to check whether an output PDF file was created.
1058 FileName pdffile = file;
1059 pdffile.changeExtension("pdf");
1060 if (!pdffile.exists())
1061 // No output PDF file was created (see #10076)
1062 retval |= NO_OUTPUT;
1063 } else if (contains(token, "That makes 100 errors")) {
1064 // More than 100 errors were reported
1065 retval |= TOO_MANY_ERRORS;
1066 } else if (prefixIs(token, "!pdfTeX error:")) {
1067 // otherwise we dont catch e.g.:
1068 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
1071 from_ascii("pdfTeX Error"),
1072 from_local8bit(token),
1074 } else if (!ignore_missing_glyphs
1075 && prefixIs(token, "Missing character: There is no ")
1076 && !contains(token, "nullfont")) {
1077 // Warning about missing glyph in selected font
1078 // may be dataloss (bug 9610)
1079 // but can be ignored for 'nullfont' (bug 10394).
1080 // as well as for ZERO WIDTH NON-JOINER (0x200C) which is
1081 // missing in many fonts and output for ligature break (bug 10727).
1082 // Since this error only occurs with utf8 output, we can safely assume
1083 // that the log file is utf8-encoded
1084 docstring const utoken = from_utf8(token);
1085 if (!contains(utoken, 0x200C)) {
1086 retval |= LATEX_ERROR;
1088 from_ascii("Missing glyphs!"),
1092 } else if (!wait_for_error.empty()) {
1093 // We collect information until we know we have an error.
1094 wait_for_error += token + '\n';
1098 LYXERR(Debug::LATEX, "Log line: " << token);
1105 bool insertIfExists(FileName const & absname, DepTable & head)
1107 if (absname.exists() && !absname.isDirectory()) {
1108 head.insert(absname, true);
1115 bool handleFoundFile(string const & ff, DepTable & head)
1117 // convert from native os path to unix path
1118 string foundfile = os::internal_path(trim(ff));
1120 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
1122 // Ok now we found a file.
1123 // Now we should make sure that this is a file that we can
1124 // access through the normal paths.
1125 // We will not try any fancy search methods to
1128 // (1) foundfile is an
1129 // absolute path and should
1132 if (FileName::isAbsolute(foundfile)) {
1133 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
1134 // On initial insert we want to do the update at once
1135 // since this file cannot be a file generated by
1137 absname.set(foundfile);
1138 if (!insertIfExists(absname, head)) {
1140 string strippedfile = foundfile;
1141 while (contains(strippedfile, " ")) {
1142 // files with spaces are often enclosed in quotation
1143 // marks; those have to be removed
1144 string unquoted = subst(strippedfile, "\"", "");
1145 absname.set(unquoted);
1146 if (insertIfExists(absname, head))
1148 // strip off part after last space and try again
1149 string tmp = strippedfile;
1150 rsplit(tmp, strippedfile, ' ');
1151 absname.set(strippedfile);
1152 if (insertIfExists(absname, head))
1158 string onlyfile = onlyFileName(foundfile);
1159 absname = makeAbsPath(onlyfile);
1162 while (contains(foundfile, ' ')) {
1163 if (absname.exists())
1167 // files with spaces are often enclosed in quotation
1168 // marks; those have to be removed
1169 string unquoted = subst(foundfile, "\"", "");
1170 absname = makeAbsPath(unquoted);
1171 if (absname.exists())
1173 // strip off part after last space and try again
1174 string strippedfile;
1175 rsplit(foundfile, strippedfile, ' ');
1176 foundfile = strippedfile;
1177 onlyfile = onlyFileName(strippedfile);
1178 absname = makeAbsPath(onlyfile);
1182 // (2) foundfile is in the tmpdir
1183 // insert it into head
1184 if (absname.exists() && !absname.isDirectory()) {
1185 // FIXME: This regex contained glo, but glo is used by the old
1186 // version of nomencl.sty. Do we need to put it back?
1187 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1188 if (regex_match(onlyfile, unwanted)) {
1189 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1190 << " in the dep file");
1191 } else if (suffixIs(onlyfile, ".tex")) {
1192 // This is a tex file generated by LyX
1193 // and latex is not likely to change this
1195 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1196 head.insert(absname, true);
1198 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1199 head.insert(absname);
1203 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1209 bool completeFilename(string const & ff, DepTable & head)
1211 // If we do not find a dot, we suspect
1212 // a fragmental file name
1213 if (!contains(ff, '.'))
1216 // if we have a dot, we let handleFoundFile decide
1217 return handleFoundFile(ff, head);
1221 int iterateLine(string const & token, regex const & reg, string const & opening,
1222 string const & closing, int fragment_pos, DepTable & head)
1225 string::const_iterator first = token.begin();
1226 string::const_iterator end = token.end();
1227 bool fragment = false;
1230 while (regex_search(first, end, what, reg)) {
1231 // if we have a dot, try to handle as file
1232 if (contains(what.str(1), '.')) {
1233 first = what[0].second;
1234 if (what.str(2) == closing) {
1235 handleFoundFile(what.str(1), head);
1236 // since we had a closing bracket,
1237 // do not investigate further
1239 } else if (what.str(2) == opening) {
1240 // if we have another opening bracket,
1241 // we might have a nested file chain
1242 // as is (file.ext (subfile.ext))
1243 fragment = !handleFoundFile(rtrim(what.str(1)), head);
1244 // decrease first position by one in order to
1245 // consider the opening delimiter on next iteration
1246 if (first > token.begin())
1249 // if we have no closing bracket,
1250 // try to handle as file nevertheless
1251 fragment = !handleFoundFile(
1252 what.str(1) + what.str(2), head);
1254 // if we do not have a dot, check if the line has
1255 // a closing bracket (else, we suspect a line break)
1256 else if (what.str(2) != closing) {
1257 first = what[0].second;
1260 // we have a closing bracket, so the content
1261 // is not a file name.
1262 // no need to investigate further
1263 first = what[0].second;
1266 last_match = what.str(1);
1269 // We need to consider the result from previous line iterations:
1270 // We might not find a fragment here, but another one might follow
1271 // E.g.: (filename.ext) <filenam
1272 // Vice versa, we consider the search completed if a real match
1273 // follows a potential fragment from a previous iteration.
1274 // E.g. <some text we considered a fragment (filename.ext)
1275 // result = -1 means we did not find a fragment!
1277 int last_match_pos = -1;
1278 if (!last_match.empty() && token.find(last_match) != string::npos)
1279 last_match_pos = int(token.find(last_match));
1281 if (last_match_pos > fragment_pos)
1282 result = last_match_pos;
1284 result = fragment_pos;
1286 if (last_match_pos < fragment_pos)
1287 result = fragment_pos;
1295 void LaTeX::deplog(DepTable & head)
1297 // This function reads the LaTeX log file end extracts all the
1298 // external files used by the LaTeX run. The files are then
1299 // entered into the dependency file.
1301 string const logfile =
1302 onlyFileName(changeExtension(file.absFileName(), ".log"));
1304 static regex const reg1("File: (.+).*");
1305 static regex const reg2("No file (.+)(.).*");
1306 static regex const reg3a("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1307 // LuaTeX has a slightly different output
1308 static regex const reg3b("\\\\openout[0-9]+.*=\\s*(.+)");
1309 // If an index should be created, MikTex does not write a line like
1310 // \openout# = 'sample.idx'.
1311 // but instead only a line like this into the log:
1312 // Writing index file sample.idx
1313 static regex const reg4("Writing index file (.+).*");
1314 static regex const regoldnomencl("Writing glossary file (.+).*");
1315 static regex const regnomencl(".*Writing nomenclature file (.+).*");
1316 // If a toc should be created, MikTex does not write a line like
1317 // \openout# = `sample.toc'.
1318 // but only a line like this into the log:
1320 // This line is also written by tetex.
1321 // This line is not present if no toc should be created.
1322 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1323 // file names can be enclosed in <...> (anywhere on the line)
1324 static regex const reg5(".*<[^>]+.*");
1325 // and also (...) anywhere on the line
1326 static regex const reg6(".*\\([^)]+.*");
1328 FileName const fn = makeAbsPath(logfile);
1329 ifstream ifs(fn.toFilesystemEncoding().c_str());
1332 // Ok, the scanning of files here is not sufficient.
1333 // Sometimes files are named by "File: xxx" only
1334 // Therefore we use some regexps to find files instead.
1335 // Note: all file names and paths might contains spaces.
1336 // Also, file names might be broken across lines. Therefore
1337 // we mark (potential) fragments and merge those lines.
1338 bool fragment = false;
1340 getline(ifs, token);
1341 // MikTeX sometimes inserts \0 in the log file. They can't be
1342 // removed directly with the existing string utility
1343 // functions, so convert them first to \r, and remove all
1344 // \r's afterwards, since we need to remove them anyway.
1345 token = subst(token, '\0', '\r');
1346 token = subst(token, "\r", "");
1347 if (token.empty() || token == ")") {
1348 lastline = string();
1352 // FIXME UNICODE: We assume that the file names in the log
1353 // file are in the file system encoding.
1354 token = to_utf8(from_filesystem8bit(token));
1356 // Sometimes, filenames are broken across lines.
1357 // We care for that and save suspicious lines.
1358 // Here we exclude some cases where we are sure
1359 // that there is no continued filename
1360 if (!lastline.empty()) {
1361 static regex const package_info("Package \\w+ Info: .*");
1362 static regex const package_warning("Package \\w+ Warning: .*");
1363 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1364 || prefixIs(token, "Package:")
1365 || prefixIs(token, "Language:")
1366 || prefixIs(token, "LaTeX Info:")
1367 || prefixIs(token, "LaTeX Font Info:")
1368 || prefixIs(token, "\\openout[")
1369 || prefixIs(token, "))")
1370 || regex_match(token, package_info)
1371 || regex_match(token, package_warning))
1372 lastline = string();
1375 if (!lastline.empty())
1376 // probably a continued filename from last line
1377 token = lastline + token;
1378 if (token.length() > 255) {
1379 // string too long. Cut off.
1380 token.erase(0, token.length() - 251);
1385 // (1) "File: file.ext"
1386 if (regex_match(token, sub, reg1)) {
1387 // is this a fragmental file name?
1388 fragment = !completeFilename(sub.str(1), head);
1390 if (suffixIs(token, ")"))
1391 // no fragment for sure
1393 // (2) "No file file.ext"
1394 } else if (regex_match(token, sub, reg2)) {
1395 // file names must contains a dot, line ends with dot
1396 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1397 fragment = !handleFoundFile(sub.str(1), head);
1399 // we suspect a line break
1401 // (3)(a) "\openout<nr> = `file.ext'."
1402 } else if (regex_match(token, sub, reg3a)) {
1403 // search for closing '. at the end of the line
1404 if (sub.str(2) == "\'.")
1405 fragment = !handleFoundFile(sub.str(1), head);
1407 // potential fragment
1409 // (3)(b) "\openout<nr> = file.ext" (LuaTeX)
1410 } else if (regex_match(token, sub, reg3b)) {
1411 // file names must contains a dot
1412 if (contains(sub.str(1), '.'))
1413 fragment = !handleFoundFile(sub.str(1), head);
1415 // potential fragment
1417 // (4) "Writing index file file.ext"
1418 } else if (regex_match(token, sub, reg4))
1419 // fragmential file name?
1420 fragment = !completeFilename(sub.str(1), head);
1421 // (5) "Writing nomenclature file file.ext"
1422 else if (regex_match(token, sub, regnomencl) ||
1423 regex_match(token, sub, regoldnomencl))
1424 // fragmental file name?
1425 fragment= !completeFilename(sub.str(1), head);
1426 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1427 else if (regex_match(token, sub, miktexTocReg))
1428 fragment = !handleFoundFile(onlyFileName(changeExtension(
1429 file.absFileName(), ".toc")), head);
1431 // not found, but we won't check further
1434 int fragment_pos = -1;
1436 // We can have several of these on one line
1437 // (and in addition to those above)
1438 if (regex_match(token, sub, reg5)) {
1439 // search for strings in <...>
1440 static regex const reg5_1("<([^>]+)(.)");
1441 fragment_pos = iterateLine(token, reg5_1, "<", ">",
1442 fragment_pos, head);
1443 fragment = (fragment_pos != -1);
1447 // We can have several of these on one line
1448 // this must be queried separated, because of
1449 // cases such as "File: file.ext (type eps)"
1450 // where "File: file.ext" would be skipped
1451 if (regex_match(token, sub, reg6)) {
1452 // search for strings in (...)
1453 static regex const reg6_1("\\(([^()]+)(.)");
1454 fragment_pos = iterateLine(token, reg6_1, "(", ")",
1455 fragment_pos, head);
1456 fragment = (fragment_pos != -1);
1460 // probable linebreak within file name:
1464 // no linebreak: reset
1465 lastline = string();
1468 // Make sure that the main .tex file is in the dependency file.
1469 head.insert(file, true);
1473 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1475 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1476 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1478 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1480 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1481 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1482 static regex const bibtexError2("^(.*---while reading file).*$");
1483 static regex const bibtexError3("(A bad cross reference---).*");
1484 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1485 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1486 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1487 int retval = NO_ERRORS;
1490 while (getline(ifs, token)) {
1491 token = rtrim(token, "\r");
1493 // FIXME UNICODE: We assume that citation keys and filenames
1494 // in the aux file are in the file system encoding.
1495 token = to_utf8(from_filesystem8bit(token));
1496 if (regex_match(token, sub, reg1)) {
1497 string data = sub.str(3);
1498 if (!data.empty()) {
1499 LYXERR(Debug::LATEX, "Found bib file: " << data);
1500 handleFoundFile(data, dep);
1503 else if (regex_match(token, sub, bibtexError)
1504 || regex_match(token, sub, bibtexError2)
1505 || regex_match(token, sub, bibtexError4)
1506 || regex_match(token, sub, bibtexError5)) {
1507 retval |= BIBTEX_ERROR;
1508 string errstr = N_("BibTeX error: ") + token;
1510 if ((prefixIs(token, "while executing---line")
1511 || prefixIs(token, "---line ")
1512 || prefixIs(token, "*Please notify the BibTeX"))
1513 && !prevtoken.empty()) {
1514 errstr = N_("BibTeX error: ") + prevtoken;
1515 msg = prevtoken + '\n';
1519 from_local8bit(errstr),
1520 from_local8bit(msg));
1521 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1522 retval |= BIBTEX_ERROR;
1523 string errstr = N_("BibTeX error: ") + prevtoken;
1524 string msg = prevtoken + '\n' + token;
1526 from_local8bit(errstr),
1527 from_local8bit(msg));
1528 } else if (regex_match(token, sub, biberError)) {
1529 retval |= BIBTEX_ERROR;
1530 string errstr = N_("Biber error: ") + sub.str(2);
1533 from_local8bit(errstr),
1534 from_local8bit(msg));
1542 int LaTeX::scanIlgFile(TeXErrors & terr)
1544 FileName const ilg_file(changeExtension(file.absFileName(), "ilg"));
1545 LYXERR(Debug::LATEX, "Scanning ilg file: " << ilg_file);
1547 ifstream ifs(ilg_file.toFilesystemEncoding().c_str());
1549 int retval = NO_ERRORS;
1552 while (getline(ifs, token)) {
1553 token = rtrim(token, "\r");
1555 if (prefixIs(token, "!! "))
1557 else if (!prevtoken.empty()) {
1558 retval |= INDEX_ERROR;
1559 string errstr = N_("Makeindex error: ") + prevtoken;
1560 string msg = prevtoken + '\n';
1563 from_local8bit(errstr),
1564 from_local8bit(msg));
1566 } else if (prefixIs(token, "ERROR: ")) {
1567 retval |= BIBTEX_ERROR;
1568 string errstr = N_("Xindy error: ") + token.substr(6);
1571 from_local8bit(errstr),
1572 from_local8bit(msg));