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 unsigned int count = 0; // number of times run
192 num_errors = 0; // just to make sure.
193 unsigned int const MAX_RUN = 6;
194 DepTable head; // empty head
195 bool rerun = false; // rerun requested
197 // The class LaTeX does not know the temp path.
198 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
202 // first check if the file dependencies exist:
203 // ->If it does exist
204 // check if any of the files mentioned in it have
205 // changed (done using a checksum).
207 // run latex once and
208 // remake the dependency file
209 // -> if not changed:
210 // just return there is nothing to do for us.
211 // ->if it doesn't exist
213 // run latex once (we need to run latex once anyway) and
214 // remake the dependency file.
217 bool had_depfile = depfile.exists();
218 bool run_bibtex = false;
219 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
222 LYXERR(Debug::DEPEND, "Dependency file exists");
223 // Read the dep file:
224 had_depfile = head.read(depfile);
228 // Update the checksums
230 // Can't just check if anything has changed because it might
231 // have aborted on error last time... in which cas we need
232 // to re-run latex and collect the error messages
233 // (even if they are the same).
234 if (!output_file.exists()) {
235 LYXERR(Debug::DEPEND,
236 "re-running LaTeX because output file doesn't exist.");
237 } else if (!head.sumchange()) {
238 LYXERR(Debug::DEPEND, "return no_change");
241 LYXERR(Debug::DEPEND, "Dependency file has changed");
244 if (head.extchanged(".bib") || head.extchanged(".bst"))
247 LYXERR(Debug::DEPEND,
248 "Dependency file does not exist, or has wrong format");
250 /// We scan the aux file even when had_depfile = false,
251 /// because we can run pdflatex on the file after running latex on it,
252 /// in which case we will not need to run bibtex again.
253 vector<AuxInfo> bibtex_info_old;
255 bibtex_info_old = scanAuxFiles(aux_file, runparams.only_childbibs);
258 LYXERR(Debug::LATEX, "Run #" << count);
259 message(runMessage(count));
261 int exit_code = startscript();
262 if (exit_code == Systemcall::KILLED)
263 return Systemcall::KILLED;
265 scanres = scanLogFile(terr);
266 if (scanres & ERROR_RERUN) {
267 LYXERR(Debug::LATEX, "Rerunning LaTeX");
269 exit_code = startscript();
270 if (exit_code == Systemcall::KILLED)
271 return Systemcall::KILLED;
272 scanres = scanLogFile(terr);
275 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file, runparams.only_childbibs);
276 if (!run_bibtex && bibtex_info_old != bibtex_info)
279 // update the dependencies.
280 deplog(head); // reads the latex log
284 // At this point we must run external programs if needed.
285 // makeindex will be run if a .idx file changed or was generated.
286 // And if there were undefined citations or changes in references
287 // the .aux file is checked for signs of bibtex. Bibtex is then run
290 // memoir (at least) writes an empty *idx file in the first place.
291 // A second latex run is needed.
292 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
293 rerun = idxfile.exists() && idxfile.isFileEmpty();
296 if (head.haschanged(idxfile)) {
298 LYXERR(Debug::LATEX, "Running MakeIndex.");
299 message(_("Running Index Processor."));
300 // onlyFileName() is needed for cygwin
302 runMakeIndex(onlyFileName(idxfile.absFileName()), runparams);
303 if (ret == Systemcall::KILLED)
304 return Systemcall::KILLED;
308 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
309 // If all nomencl entries are removed, nomencl writes an empty nlo file.
310 // DepTable::hasChanged() returns false in this case, since it does not
311 // distinguish empty files from non-existing files. This is why we need
312 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
313 // FIXME: Sort out the real problem in DepTable.
314 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty())) {
315 int const ret = runMakeIndexNomencl(file, ".nlo", ".nls");
316 if (ret == Systemcall::KILLED)
317 return Systemcall::KILLED;
321 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
322 if (head.haschanged(glofile)) {
323 int const ret = runMakeIndexNomencl(file, ".glo", ".gls");
330 // check if we're using biber instead of bibtex
331 // biber writes no info to the aux file, so we just check
332 // if a bcf file exists (and if it was updated)
333 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
334 biber |= head.exist(bcffile);
337 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
338 if (scanres & UNDEF_CIT || run_bibtex) {
339 // Here we must scan the .aux file and look for
340 // "\bibdata" and/or "\bibstyle". If one of those
341 // tags is found -> run bibtex and set rerun = true;
343 LYXERR(Debug::LATEX, "Running BibTeX.");
344 message(_("Running BibTeX."));
345 updateBibtexDependencies(head, bibtex_info);
347 rerun |= runBibTeX(bibtex_info, runparams, exit_code);
348 if (exit_code == Systemcall::KILLED)
349 return Systemcall::KILLED;
350 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
351 if (blgfile.exists())
352 bscanres = scanBlgFile(head, terr);
353 } else if (!had_depfile) {
354 /// If we run pdflatex on the file after running latex on it,
355 /// then we do not need to run bibtex, but we do need to
356 /// insert the .bib and .bst files into the .dep-pdf file.
357 updateBibtexDependencies(head, bibtex_info);
361 // we know on this point that latex has been run once (or we just
362 // returned) and the question now is to decide if we need to run
363 // it any more. This is done by asking if any of the files in the
364 // dependency file has changed. (remember that the checksum for
365 // a given file is reported to have changed if it just was created)
366 // -> if changed or rerun == true:
367 // run latex once more and
368 // update the dependency structure
369 // -> if not changed:
370 // we do nothing at this point
372 if (rerun || head.sumchange()) {
375 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
376 LYXERR(Debug::LATEX, "Run #" << count);
377 message(runMessage(count));
378 int exit_code = startscript();
379 if (exit_code == Systemcall::KILLED)
380 return Systemcall::KILLED;
381 scanres = scanLogFile(terr);
383 // update the depedencies
384 deplog(head); // reads the latex log
387 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
392 // Complex bibliography packages such as Biblatex require
393 // an additional bibtex cycle sometimes.
394 if (scanres & UNDEF_CIT) {
395 // Here we must scan the .aux file and look for
396 // "\bibdata" and/or "\bibstyle". If one of those
397 // tags is found -> run bibtex and set rerun = true;
399 LYXERR(Debug::LATEX, "Running BibTeX.");
400 message(_("Running BibTeX."));
401 updateBibtexDependencies(head, bibtex_info);
403 rerun |= runBibTeX(bibtex_info, runparams, exit_code);
404 if (exit_code == Systemcall::KILLED)
405 return Systemcall::KILLED;
406 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
407 if (blgfile.exists())
408 bscanres = scanBlgFile(head, terr);
412 // The inclusion of files generated by external programs such as
413 // makeindex or bibtex might have done changes to pagenumbering,
414 // etc. And because of this we must run the external programs
415 // again to make sure everything is redone correctly.
416 // Also there should be no need to run the external programs any
419 // run makeindex if the <file>.idx has changed or was generated.
420 if (head.haschanged(idxfile)) {
422 LYXERR(Debug::LATEX, "Running MakeIndex.");
423 message(_("Running Index Processor."));
424 // onlyFileName() is needed for cygwin
425 int const ret = runMakeIndex(onlyFileName(changeExtension(
426 file.absFileName(), ".idx")), runparams);
427 if (ret == Systemcall::KILLED)
428 return Systemcall::KILLED;
432 // MSVC complains that bool |= int is unsafe. Not sure why.
433 if (head.haschanged(nlofile))
434 rerun |= (runMakeIndexNomencl(file, ".nlo", ".nls") != 0);
435 if (head.haschanged(glofile))
436 rerun |= (runMakeIndexNomencl(file, ".glo", ".gls") != 0);
439 // we will only run latex more if the log file asks for it.
440 // or if the sumchange() is true.
441 // -> rerun asked for:
443 // remake the dependency file
444 // goto 2 or return if max runs are reached.
445 // -> rerun not asked for:
446 // just return (fall out of bottom of func)
448 while ((head.sumchange() || rerun || (scanres & RERUN))
449 && count < MAX_RUN) {
450 // Yes rerun until message goes away, or until
451 // MAX_RUNS are reached.
454 LYXERR(Debug::LATEX, "Run #" << count);
455 message(runMessage(count));
457 scanres = scanLogFile(terr);
463 // Write the dependencies to file.
467 // add flag here, just before return, instead of when exit_code
468 // is defined because scanres is sometimes overwritten above
470 scanres |= NONZERO_ERROR;
473 LYXERR(Debug::LATEX, "Done.");
475 if (bscanres & ERRORS)
476 return bscanres; // return on error
482 int LaTeX::startscript()
484 // onlyFileName() is needed for cygwin
485 string tmp = cmd + ' '
486 + quoteName(onlyFileName(file.toFilesystemEncoding()))
487 + " > " + os::nulldev();
489 Systemcall::Starttype const starttype =
490 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
491 return one.startscript(starttype, tmp, path, lpath, true);
495 int LaTeX::runMakeIndex(string const & f, OutputParams const & rp,
496 string const & params)
498 string tmp = rp.use_japanese ?
499 lyxrc.jindex_command : lyxrc.index_command;
501 if (!rp.index_command.empty())
502 tmp = rp.index_command;
504 if (contains(tmp, "$$x")) {
505 // This adds appropriate [te]xindy options
506 // such as language and codepage (for the
507 // main document language/encoding)
508 string xdyopts = rp.xindy_language;
509 if (!xdyopts.empty())
510 xdyopts = "-L " + xdyopts;
511 if (rp.encoding->iconvName() == "UTF-8") {
512 if (!xdyopts.empty())
514 xdyopts += "-C utf8";
516 tmp = subst(tmp, "$$x", xdyopts);
520 "idx file has been made, running index processor ("
521 << tmp << ") on file " << f);
523 tmp = subst(tmp, "$$lang", rp.document_language);
524 if (rp.use_indices) {
525 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
527 "Multiple indices. Using splitindex command: " << tmp);
533 Systemcall::Starttype const starttype =
534 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
535 return one.startscript(starttype, tmp, path, lpath, true);
539 int LaTeX::runMakeIndexNomencl(FileName const & fname,
540 string const & nlo, string const & nls)
542 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
543 message(_("Running MakeIndex for nomencl."));
544 string tmp = lyxrc.nomencl_command + ' ';
545 // onlyFileName() is needed for cygwin
546 tmp += quoteName(onlyFileName(changeExtension(fname.absFileName(), nlo)));
548 + onlyFileName(changeExtension(fname.toFilesystemEncoding(), nls));
550 Systemcall::Starttype const starttype =
551 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
552 return one.startscript(starttype, tmp, path, lpath, true);
556 vector<AuxInfo> const
557 LaTeX::scanAuxFiles(FileName const & fname, bool const only_childbibs)
559 vector<AuxInfo> result;
561 // With chapterbib, we have to bibtex all children's aux files
562 // but _not_ the master's!
563 if (only_childbibs) {
564 for (string const &s: children) {
566 makeAbsPath(s, fname.onlyPath().realPath());
567 fn.changeExtension("aux");
569 result.push_back(scanAuxFile(fn));
574 result.push_back(scanAuxFile(fname));
576 // This is for bibtopic
577 string const basename = removeExtension(fname.absFileName());
578 for (int i = 1; i < 1000; ++i) {
579 FileName const file2(basename
580 + '.' + convert<string>(i)
584 result.push_back(scanAuxFile(file2));
590 AuxInfo const LaTeX::scanAuxFile(FileName const & fname)
593 result.aux_file = fname;
594 scanAuxFile(fname, result);
599 void LaTeX::scanAuxFile(FileName const & fname, AuxInfo & aux_info)
601 LYXERR(Debug::LATEX, "Scanning aux file: " << fname);
603 ifstream ifs(fname.toFilesystemEncoding().c_str());
605 static regex const reg1("\\\\citation\\{([^}]+)\\}");
606 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
607 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
608 static regex const reg4("\\\\@input\\{([^}]+)\\}");
610 while (getline(ifs, token)) {
611 token = rtrim(token, "\r");
613 // FIXME UNICODE: We assume that citation keys and filenames
614 // in the aux file are in the file system encoding.
615 token = to_utf8(from_filesystem8bit(token));
616 if (regex_match(token, sub, reg1)) {
617 string data = sub.str(1);
618 while (!data.empty()) {
620 data = split(data, citation, ',');
621 LYXERR(Debug::LATEX, "Citation: " << citation);
622 aux_info.citations.insert(citation);
624 } else if (regex_match(token, sub, reg2)) {
625 string data = sub.str(1);
626 // data is now all the bib files separated by ','
627 // get them one by one and pass them to the helper
628 while (!data.empty()) {
630 data = split(data, database, ',');
631 database = changeExtension(database, "bib");
632 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
633 aux_info.databases.insert(database);
635 } else if (regex_match(token, sub, reg3)) {
636 string style = sub.str(1);
637 // token is now the style file
638 // pass it to the helper
639 style = changeExtension(style, "bst");
640 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
641 aux_info.styles.insert(style);
642 } else if (regex_match(token, sub, reg4)) {
643 string const file2 = sub.str(1);
644 scanAuxFile(makeAbsPath(file2), aux_info);
650 void LaTeX::updateBibtexDependencies(DepTable & dep,
651 vector<AuxInfo> const & bibtex_info)
653 // Since a run of Bibtex mandates more latex runs it is ok to
654 // remove all ".bib" and ".bst" files.
655 dep.remove_files_with_extension(".bib");
656 dep.remove_files_with_extension(".bst");
657 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
659 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
660 it != bibtex_info.end(); ++it) {
661 for (set<string>::const_iterator it2 = it->databases.begin();
662 it2 != it->databases.end(); ++it2) {
663 FileName const file = findtexfile(*it2, "bib");
665 dep.insert(file, true);
668 for (set<string>::const_iterator it2 = it->styles.begin();
669 it2 != it->styles.end(); ++it2) {
670 FileName const file = findtexfile(*it2, "bst");
672 dep.insert(file, true);
676 // biber writes nothing into the aux file.
677 // Instead, we have to scan the blg file
680 scanBlgFile(dep, terr);
685 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
686 OutputParams const & rp, int & exit_code)
690 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
691 it != bibtex_info.end(); ++it) {
692 if (!biber && it->databases.empty())
696 string tmp = rp.bibtex_command;
698 // onlyFileName() is needed for cygwin
699 tmp += quoteName(onlyFileName(removeExtension(
700 it->aux_file.absFileName())));
702 Systemcall::Starttype const starttype =
703 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
704 exit_code = one.startscript(starttype, tmp, path, lpath, true);
709 // Return whether bibtex was run
714 //helper func for scanLogFile; gets line number X from strings "... on input line X ..."
715 //returns 0 if none is found
716 int getLineNumber(const string &token){
717 string l = support::token(token, ' ', tokenPos(token,' ',"line") + 1);
718 return l.empty() ? 0 : convert<int>(l);
722 int LaTeX::scanLogFile(TeXErrors & terr)
726 int retval = NO_ERRORS;
728 onlyFileName(changeExtension(file.absFileName(), ".log"));
729 LYXERR(Debug::LATEX, "Log file: " << tmp);
730 FileName const fn = FileName(makeAbsPath(tmp));
731 // FIXME we should use an ifdocstream here and a docstring for token
732 // below. The encoding of the log file depends on the _output_ (font)
733 // encoding of the TeX file (T1, TU etc.). See #10728.
734 ifstream ifs(fn.toFilesystemEncoding().c_str());
735 bool fle_style = false;
736 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
737 static regex const child_file("[^0-9]*([0-9]+[A-Za-z]*_.+\\.tex).*");
738 // Flag for 'File ended while scanning' message.
739 // We need to wait for subsequent processing.
740 string wait_for_error;
743 stack <pair<string, int> > child;
749 while (getline(ifs, token)) {
750 // MikTeX sometimes inserts \0 in the log file. They can't be
751 // removed directly with the existing string utility
752 // functions, so convert them first to \r, and remove all
753 // \r's afterwards, since we need to remove them anyway.
754 token = subst(token, '\0', '\r');
755 token = subst(token, "\r", "");
758 LYXERR(Debug::LATEX, "Log line: " << token);
763 // Track child documents
764 for (size_t i = 0; i < token.length(); ++i) {
765 if (token[i] == '(') {
767 size_t j = token.find('(', i + 1);
768 size_t len = j == string::npos
769 ? token.substr(i + 1).length()
771 string const substr = token.substr(i + 1, len);
772 if (regex_match(substr, sub, child_file)) {
773 string const name = sub.str(1);
774 // Sometimes also masters have a name that matches
775 // (if their name starts with a number and _)
776 if (name != file.onlyFileName()) {
777 child.push(make_pair(name, pnest));
778 children.push_back(name);
782 } else if (token[i] == ')') {
784 && child.top().second == pnest)
789 child_name = child.empty() ? empty_string() : child.top().first;
791 if (contains(token, "file:line:error style messages enabled"))
794 //Handles both "LaTeX Warning:" & "Package natbib Warning:"
795 //Various handlers for missing citations below won't catch the problem if citation
796 //key is long (>~25chars), because pdflatex splits output at line length 80.
797 //TODO: TL 2020 engines will contain new commandline switch --cnf-line which we
798 //can use to set max_print_line variable for appropriate length and detect all
800 if (contains(token, "There were undefined citations.") ||
801 prefixIs(token, "Package biblatex Warning: The following entry could not be found"))
804 if (prefixIs(token, "LaTeX Warning:") ||
805 prefixIs(token, "! pdfTeX warning")) {
806 // Here shall we handle different
808 retval |= LATEX_WARNING;
809 LYXERR(Debug::LATEX, "LaTeX Warning.");
810 if (contains(token, "Rerun to get cross-references")) {
812 LYXERR(Debug::LATEX, "We should rerun.");
813 // package clefval needs 2 latex runs before bibtex
814 } else if (contains(token, "Value of")
815 && contains(token, "on page")
816 && contains(token, "undefined")) {
817 retval |= ERROR_RERUN;
818 LYXERR(Debug::LATEX, "Force rerun.");
820 } else if (contains(token, "Etaremune labels have changed")) {
821 retval |= ERROR_RERUN;
822 LYXERR(Debug::LATEX, "Force rerun.");
824 } else if (contains(token, "Endnotes may have changed. Rerun")) {
826 LYXERR(Debug::LATEX, "We should rerun.");
827 //"Citation `cit' on page X undefined on input line X."
828 } else if (contains(token, "Citation")
829 //&& contains(token, "on input line") //often split to newline
830 && contains(token, "undefined")) {
832 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
833 from_utf8(token), child_name);
834 //"Reference `X' on page Y undefined on input line Z."
835 } else if (contains(token, "Reference")
836 //&& contains(token, "on input line")) //often split to new line
837 && contains(token, "undefined")) {
839 terr.insertRef(getLineNumber(token), from_ascii("Reference undefined"),
840 from_utf8(token), child_name);
842 //If label is too long pdlaftex log line splitting will make the above fail
843 //so we catch at least this generic statement occuring for both CIT & REF.
844 } else if (contains(token, "There were undefined references.")) {
845 if (!(retval & UNDEF_CIT)) //if not handled already
849 } else if (prefixIs(token, "Package")) {
851 retval |= PACKAGE_WARNING;
852 if (contains(token, "natbib Warning:")) {
854 if (contains(token, "Citation")
855 && contains(token, "on page")
856 && contains(token, "undefined")) {
858 //Unf only keys up to ~6 chars will make it due to line splits
859 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
860 from_utf8(token), child_name);
862 } else if (contains(token, "run BibTeX")) {
864 } else if (contains(token, "run Biber")) {
867 } else if (contains(token, "Rerun LaTeX") ||
868 contains(token, "Please rerun LaTeX") ||
869 contains(token, "Rerun to get")) {
870 // at least longtable.sty and bibtopic.sty
872 LYXERR(Debug::LATEX, "We should rerun.");
875 } else if (prefixIs(token, "LETTRE WARNING:")) {
876 if (contains(token, "veuillez recompiler")) {
878 LYXERR(Debug::LATEX, "We should rerun.");
881 } else if (token[0] == '(') {
882 if (contains(token, "Rerun LaTeX") ||
883 contains(token, "Rerun to get")) {
885 LYXERR(Debug::LATEX, "We should rerun.");
888 } else if (prefixIs(token, "! ")
890 && regex_match(token, sub, file_line_error)
891 && !contains(token, "pdfTeX warning"))) {
892 // Ok, we have something that looks like a TeX Error
893 // but what do we really have.
895 // Just get the error description:
897 if (prefixIs(token, "! "))
898 desc = string(token, 2);
901 if (contains(token, "LaTeX Error:"))
902 retval |= LATEX_ERROR;
904 if (prefixIs(token, "! File ended while scanning")) {
905 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
906 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
907 retval |= ERROR_RERUN;
908 LYXERR(Debug::LATEX, "Force rerun.");
910 // bug 6445. At this point its not clear we finish with error.
911 wait_for_error = desc;
916 if (prefixIs(token, "! Incomplete \\if")) {
917 // bug 10666. At this point its not clear we finish with error.
918 wait_for_error = desc;
922 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
923 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
924 retval |= ERROR_RERUN;
925 LYXERR(Debug::LATEX, "Force rerun.");
928 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
929 retval |= LATEX_ERROR;
932 errstr = wait_for_error;
933 wait_for_error.clear();
935 if (!getline(ifs, tmp))
937 tmp = rtrim(tmp, "\r");
938 errstr += "\n" + tmp;
941 } while (!contains(tmp, "(job aborted"));
944 from_ascii("Emergency stop"),
945 from_local8bit(errstr),
952 if (!getline(ifs, tmp))
954 tmp = rtrim(tmp, "\r");
955 // 15 is somewhat arbitrarily chosen, based on practice.
956 // We used 10 for 14 years and increased it to 15 when we
960 } while (!prefixIs(tmp, "l."));
961 if (prefixIs(tmp, "l.")) {
962 // we have a latex error
965 "Package babel Error: You haven't defined the language")
967 "Package babel Error: You haven't loaded the option")
969 "Package babel Error: Unknown language"))
970 retval |= ERROR_RERUN;
971 // get the line number:
973 sscanf(tmp.c_str(), "l.%d", &line);
974 // get the rest of the message:
975 string errstr(tmp, tmp.find(' '));
978 tmp = rtrim(tmp, "\r");
979 while (!contains(errstr, "l.")
981 && !prefixIs(tmp, "! ")
982 && !contains(tmp, "(job aborted")) {
986 tmp = rtrim(tmp, "\r");
988 LYXERR(Debug::LATEX, "line: " << line << '\n'
989 << "Desc: " << desc << '\n' << "Text: " << errstr);
990 if (line == last_line)
996 if (line_count <= 5) {
998 // We have no idea what the encoding of
1000 // It seems that the output from the
1001 // latex compiler itself is pure ASCII,
1002 // but it can include bits from the
1003 // document, so whatever encoding we
1004 // assume here it can be wrong.
1005 terr.insertError(line,
1006 from_local8bit(desc),
1007 from_local8bit(errstr),
1013 // information messages, TeX warnings and other
1014 // warnings we have not caught earlier.
1015 if (prefixIs(token, "Overfull ")) {
1016 retval |= TEX_WARNING;
1017 } else if (prefixIs(token, "Underfull ")) {
1018 retval |= TEX_WARNING;
1019 } else if (contains(token, "Rerun to get citations")) {
1020 // Natbib seems to use this.
1021 retval |= UNDEF_CIT;
1022 } else if (contains(token, "No pages of output")
1023 || contains(token, "no pages of output")) {
1024 // No output file (e.g. the DVI or PDF) was created
1025 retval |= NO_OUTPUT;
1026 } else if (contains(token, "Error 256 (driver return code)")) {
1027 // This is a xdvipdfmx driver error reported by XeTeX.
1028 // We have to check whether an output PDF file was created.
1029 FileName pdffile = file;
1030 pdffile.changeExtension("pdf");
1031 if (!pdffile.exists())
1032 // No output PDF file was created (see #10076)
1033 retval |= NO_OUTPUT;
1034 } else if (contains(token, "That makes 100 errors")) {
1035 // More than 100 errors were reported
1036 retval |= TOO_MANY_ERRORS;
1037 } else if (prefixIs(token, "!pdfTeX error:")) {
1038 // otherwise we dont catch e.g.:
1039 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
1042 from_ascii("pdfTeX Error"),
1043 from_local8bit(token),
1045 } else if (!ignore_missing_glyphs
1046 && prefixIs(token, "Missing character: There is no ")
1047 && !contains(token, "nullfont")) {
1048 // Warning about missing glyph in selected font
1049 // may be dataloss (bug 9610)
1050 // but can be ignored for 'nullfont' (bug 10394).
1051 // as well as for ZERO WIDTH NON-JOINER (0x200C) which is
1052 // missing in many fonts and output for ligature break (bug 10727).
1053 // Since this error only occurs with utf8 output, we can safely assume
1054 // that the log file is utf8-encoded
1055 docstring const utoken = from_utf8(token);
1056 if (!contains(utoken, 0x200C)) {
1057 retval |= LATEX_ERROR;
1059 from_ascii("Missing glyphs!"),
1063 } else if (!wait_for_error.empty()) {
1064 // We collect information until we know we have an error.
1065 wait_for_error += token + '\n';
1069 LYXERR(Debug::LATEX, "Log line: " << token);
1076 bool insertIfExists(FileName const & absname, DepTable & head)
1078 if (absname.exists() && !absname.isDirectory()) {
1079 head.insert(absname, true);
1086 bool handleFoundFile(string const & ff, DepTable & head)
1088 // convert from native os path to unix path
1089 string foundfile = os::internal_path(trim(ff));
1091 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
1093 // Ok now we found a file.
1094 // Now we should make sure that this is a file that we can
1095 // access through the normal paths.
1096 // We will not try any fancy search methods to
1099 // (1) foundfile is an
1100 // absolute path and should
1103 if (FileName::isAbsolute(foundfile)) {
1104 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
1105 // On initial insert we want to do the update at once
1106 // since this file cannot be a file generated by
1108 absname.set(foundfile);
1109 if (!insertIfExists(absname, head)) {
1111 string strippedfile = foundfile;
1112 while (contains(strippedfile, " ")) {
1113 // files with spaces are often enclosed in quotation
1114 // marks; those have to be removed
1115 string unquoted = subst(strippedfile, "\"", "");
1116 absname.set(unquoted);
1117 if (insertIfExists(absname, head))
1119 // strip off part after last space and try again
1120 string tmp = strippedfile;
1121 rsplit(tmp, strippedfile, ' ');
1122 absname.set(strippedfile);
1123 if (insertIfExists(absname, head))
1129 string onlyfile = onlyFileName(foundfile);
1130 absname = makeAbsPath(onlyfile);
1133 while (contains(foundfile, ' ')) {
1134 if (absname.exists())
1138 // files with spaces are often enclosed in quotation
1139 // marks; those have to be removed
1140 string unquoted = subst(foundfile, "\"", "");
1141 absname = makeAbsPath(unquoted);
1142 if (absname.exists())
1144 // strip off part after last space and try again
1145 string strippedfile;
1146 rsplit(foundfile, strippedfile, ' ');
1147 foundfile = strippedfile;
1148 onlyfile = onlyFileName(strippedfile);
1149 absname = makeAbsPath(onlyfile);
1153 // (2) foundfile is in the tmpdir
1154 // insert it into head
1155 if (absname.exists() && !absname.isDirectory()) {
1156 // FIXME: This regex contained glo, but glo is used by the old
1157 // version of nomencl.sty. Do we need to put it back?
1158 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1159 if (regex_match(onlyfile, unwanted)) {
1160 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1161 << " in the dep file");
1162 } else if (suffixIs(onlyfile, ".tex")) {
1163 // This is a tex file generated by LyX
1164 // and latex is not likely to change this
1166 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1167 head.insert(absname, true);
1169 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1170 head.insert(absname);
1174 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1180 bool completeFilename(string const & ff, DepTable & head)
1182 // If we do not find a dot, we suspect
1183 // a fragmental file name
1184 if (!contains(ff, '.'))
1187 // if we have a dot, we let handleFoundFile decide
1188 return handleFoundFile(ff, head);
1192 int iterateLine(string const & token, regex const & reg, string const & opening,
1193 string const & closing, int fragment_pos, DepTable & head)
1196 string::const_iterator first = token.begin();
1197 string::const_iterator end = token.end();
1198 bool fragment = false;
1201 while (regex_search(first, end, what, reg)) {
1202 // if we have a dot, try to handle as file
1203 if (contains(what.str(1), '.')) {
1204 first = what[0].second;
1205 if (what.str(2) == closing) {
1206 handleFoundFile(what.str(1), head);
1207 // since we had a closing bracket,
1208 // do not investigate further
1210 } else if (what.str(2) == opening) {
1211 // if we have another opening bracket,
1212 // we might have a nested file chain
1213 // as is (file.ext (subfile.ext))
1214 fragment = !handleFoundFile(rtrim(what.str(1)), head);
1215 // decrease first position by one in order to
1216 // consider the opening delimiter on next iteration
1217 if (first > token.begin())
1220 // if we have no closing bracket,
1221 // try to handle as file nevertheless
1222 fragment = !handleFoundFile(
1223 what.str(1) + what.str(2), head);
1225 // if we do not have a dot, check if the line has
1226 // a closing bracket (else, we suspect a line break)
1227 else if (what.str(2) != closing) {
1228 first = what[0].second;
1231 // we have a closing bracket, so the content
1232 // is not a file name.
1233 // no need to investigate further
1234 first = what[0].second;
1237 last_match = what.str(1);
1240 // We need to consider the result from previous line iterations:
1241 // We might not find a fragment here, but another one might follow
1242 // E.g.: (filename.ext) <filenam
1243 // Vice versa, we consider the search completed if a real match
1244 // follows a potential fragment from a previous iteration.
1245 // E.g. <some text we considered a fragment (filename.ext)
1246 // result = -1 means we did not find a fragment!
1248 int last_match_pos = -1;
1249 if (!last_match.empty() && token.find(last_match) != string::npos)
1250 last_match_pos = int(token.find(last_match));
1252 if (last_match_pos > fragment_pos)
1253 result = last_match_pos;
1255 result = fragment_pos;
1257 if (last_match_pos < fragment_pos)
1258 result = fragment_pos;
1266 void LaTeX::deplog(DepTable & head)
1268 // This function reads the LaTeX log file end extracts all the
1269 // external files used by the LaTeX run. The files are then
1270 // entered into the dependency file.
1272 string const logfile =
1273 onlyFileName(changeExtension(file.absFileName(), ".log"));
1275 static regex const reg1("File: (.+).*");
1276 static regex const reg2("No file (.+)(.).*");
1277 static regex const reg3a("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1278 // LuaTeX has a slightly different output
1279 static regex const reg3b("\\\\openout[0-9]+.*=\\s*(.+)");
1280 // If an index should be created, MikTex does not write a line like
1281 // \openout# = 'sample.idx'.
1282 // but instead only a line like this into the log:
1283 // Writing index file sample.idx
1284 static regex const reg4("Writing index file (.+).*");
1285 static regex const regoldnomencl("Writing glossary file (.+).*");
1286 static regex const regnomencl(".*Writing nomenclature file (.+).*");
1287 // If a toc should be created, MikTex does not write a line like
1288 // \openout# = `sample.toc'.
1289 // but only a line like this into the log:
1291 // This line is also written by tetex.
1292 // This line is not present if no toc should be created.
1293 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1294 // file names can be enclosed in <...> (anywhere on the line)
1295 static regex const reg5(".*<[^>]+.*");
1296 // and also (...) anywhere on the line
1297 static regex const reg6(".*\\([^)]+.*");
1299 FileName const fn = makeAbsPath(logfile);
1300 ifstream ifs(fn.toFilesystemEncoding().c_str());
1303 // Ok, the scanning of files here is not sufficient.
1304 // Sometimes files are named by "File: xxx" only
1305 // Therefore we use some regexps to find files instead.
1306 // Note: all file names and paths might contains spaces.
1307 // Also, file names might be broken across lines. Therefore
1308 // we mark (potential) fragments and merge those lines.
1309 bool fragment = false;
1311 getline(ifs, token);
1312 // MikTeX sometimes inserts \0 in the log file. They can't be
1313 // removed directly with the existing string utility
1314 // functions, so convert them first to \r, and remove all
1315 // \r's afterwards, since we need to remove them anyway.
1316 token = subst(token, '\0', '\r');
1317 token = subst(token, "\r", "");
1318 if (token.empty() || token == ")") {
1319 lastline = string();
1323 // FIXME UNICODE: We assume that the file names in the log
1324 // file are in the file system encoding.
1325 token = to_utf8(from_filesystem8bit(token));
1327 // Sometimes, filenames are broken across lines.
1328 // We care for that and save suspicious lines.
1329 // Here we exclude some cases where we are sure
1330 // that there is no continued filename
1331 if (!lastline.empty()) {
1332 static regex const package_info("Package \\w+ Info: .*");
1333 static regex const package_warning("Package \\w+ Warning: .*");
1334 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1335 || prefixIs(token, "Package:")
1336 || prefixIs(token, "Language:")
1337 || prefixIs(token, "LaTeX Info:")
1338 || prefixIs(token, "LaTeX Font Info:")
1339 || prefixIs(token, "\\openout[")
1340 || prefixIs(token, "))")
1341 || regex_match(token, package_info)
1342 || regex_match(token, package_warning))
1343 lastline = string();
1346 if (!lastline.empty())
1347 // probably a continued filename from last line
1348 token = lastline + token;
1349 if (token.length() > 255) {
1350 // string too long. Cut off.
1351 token.erase(0, token.length() - 251);
1356 // (1) "File: file.ext"
1357 if (regex_match(token, sub, reg1)) {
1358 // is this a fragmental file name?
1359 fragment = !completeFilename(sub.str(1), head);
1361 if (suffixIs(token, ")"))
1362 // no fragment for sure
1364 // (2) "No file file.ext"
1365 } else if (regex_match(token, sub, reg2)) {
1366 // file names must contains a dot, line ends with dot
1367 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1368 fragment = !handleFoundFile(sub.str(1), head);
1370 // we suspect a line break
1372 // (3)(a) "\openout<nr> = `file.ext'."
1373 } else if (regex_match(token, sub, reg3a)) {
1374 // search for closing '. at the end of the line
1375 if (sub.str(2) == "\'.")
1376 fragment = !handleFoundFile(sub.str(1), head);
1378 // potential fragment
1380 // (3)(b) "\openout<nr> = file.ext" (LuaTeX)
1381 } else if (regex_match(token, sub, reg3b)) {
1382 // file names must contains a dot
1383 if (contains(sub.str(1), '.'))
1384 fragment = !handleFoundFile(sub.str(1), head);
1386 // potential fragment
1388 // (4) "Writing index file file.ext"
1389 } else if (regex_match(token, sub, reg4))
1390 // fragmential file name?
1391 fragment = !completeFilename(sub.str(1), head);
1392 // (5) "Writing nomenclature file file.ext"
1393 else if (regex_match(token, sub, regnomencl) ||
1394 regex_match(token, sub, regoldnomencl))
1395 // fragmental file name?
1396 fragment= !completeFilename(sub.str(1), head);
1397 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1398 else if (regex_match(token, sub, miktexTocReg))
1399 fragment = !handleFoundFile(onlyFileName(changeExtension(
1400 file.absFileName(), ".toc")), head);
1402 // not found, but we won't check further
1405 int fragment_pos = -1;
1407 // We can have several of these on one line
1408 // (and in addition to those above)
1409 if (regex_match(token, sub, reg5)) {
1410 // search for strings in <...>
1411 static regex const reg5_1("<([^>]+)(.)");
1412 fragment_pos = iterateLine(token, reg5_1, "<", ">",
1413 fragment_pos, head);
1414 fragment = (fragment_pos != -1);
1418 // We can have several of these on one line
1419 // this must be queried separated, because of
1420 // cases such as "File: file.ext (type eps)"
1421 // where "File: file.ext" would be skipped
1422 if (regex_match(token, sub, reg6)) {
1423 // search for strings in (...)
1424 static regex const reg6_1("\\(([^()]+)(.)");
1425 fragment_pos = iterateLine(token, reg6_1, "(", ")",
1426 fragment_pos, head);
1427 fragment = (fragment_pos != -1);
1431 // probable linebreak within file name:
1435 // no linebreak: reset
1436 lastline = string();
1439 // Make sure that the main .tex file is in the dependency file.
1440 head.insert(file, true);
1444 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1446 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1447 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1449 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1451 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1452 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1453 static regex const bibtexError2("^(.*---while reading file).*$");
1454 static regex const bibtexError3("(A bad cross reference---).*");
1455 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1456 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1457 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1458 int retval = NO_ERRORS;
1461 while (getline(ifs, token)) {
1462 token = rtrim(token, "\r");
1464 // FIXME UNICODE: We assume that citation keys and filenames
1465 // in the aux file are in the file system encoding.
1466 token = to_utf8(from_filesystem8bit(token));
1467 if (regex_match(token, sub, reg1)) {
1468 string data = sub.str(3);
1469 if (!data.empty()) {
1470 LYXERR(Debug::LATEX, "Found bib file: " << data);
1471 handleFoundFile(data, dep);
1474 else if (regex_match(token, sub, bibtexError)
1475 || regex_match(token, sub, bibtexError2)
1476 || regex_match(token, sub, bibtexError4)
1477 || regex_match(token, sub, bibtexError5)) {
1478 retval |= BIBTEX_ERROR;
1479 string errstr = N_("BibTeX error: ") + token;
1481 if ((prefixIs(token, "while executing---line")
1482 || prefixIs(token, "---line ")
1483 || prefixIs(token, "*Please notify the BibTeX"))
1484 && !prevtoken.empty()) {
1485 errstr = N_("BibTeX error: ") + prevtoken;
1486 msg = prevtoken + '\n';
1490 from_local8bit(errstr),
1491 from_local8bit(msg));
1492 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1493 retval |= BIBTEX_ERROR;
1494 string errstr = N_("BibTeX error: ") + prevtoken;
1495 string msg = prevtoken + '\n' + token;
1497 from_local8bit(errstr),
1498 from_local8bit(msg));
1499 } else if (regex_match(token, sub, biberError)) {
1500 retval |= BIBTEX_ERROR;
1501 string errstr = N_("Biber error: ") + sub.str(2);
1504 from_local8bit(errstr),
1505 from_local8bit(msg));