3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author Jürgen Spitzmüller
13 * Full author contact details are available in file CREDITS.
18 #include "BufferList.h"
24 #include "support/debug.h"
25 #include "support/convert.h"
26 #include "support/FileName.h"
27 #include "support/filetools.h"
28 #include "support/gettext.h"
29 #include "support/lstrings.h"
30 #include "support/Systemcall.h"
31 #include "support/os.h"
33 #include "support/regex.h"
40 using namespace lyx::support;
44 namespace os = support::os;
46 // TODO: in no particular order
47 // - get rid of the call to
48 // BufferList::updateIncludedTeXfiles, this should either
49 // be done before calling LaTeX::funcs or in a completely
51 // - the makeindex style files should be taken care of with
52 // the dependency mechanism.
56 docstring runMessage(unsigned int count)
58 return bformat(_("Waiting for LaTeX run number %1$d"), count);
67 void TeXErrors::insertError(int line, docstring const & error_desc,
68 docstring const & error_text,
69 string const & child_name)
71 Error newerr(line, error_desc, error_text, child_name);
72 errors.push_back(newerr);
76 bool operator==(AuxInfo const & a, AuxInfo const & o)
78 return a.aux_file == o.aux_file
79 && a.citations == o.citations
80 && a.databases == o.databases
81 && a.styles == o.styles;
85 bool operator!=(AuxInfo const & a, AuxInfo const & o)
95 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
96 FileName const & f, string const & p, string const & lp,
97 bool const clean_start)
98 : cmd(latex), file(f), path(p), lpath(lp), runparams(rp), biber(false)
101 // lualatex can still produce a DVI with --output-format=dvi. However,
102 // we do not use that internally (we use the "dvilualatex" command) so
103 // it would only happen from a custom converter. Thus, it is better to
104 // guess that lualatex produces a PDF than to guess a DVI.
105 // FIXME we should base the extension on the output format, which we should
106 // get in a robust way, e.g. from the converter.
107 if (prefixIs(cmd, "pdf") || prefixIs(cmd, "lualatex") || prefixIs(cmd, "xelatex")) {
108 depfile = FileName(file.absFileName() + ".dep-pdf");
110 FileName(changeExtension(file.absFileName(), ".pdf"));
112 depfile = FileName(file.absFileName() + ".dep");
114 FileName(changeExtension(file.absFileName(), ".dvi"));
117 removeAuxiliaryFiles();
121 void LaTeX::removeAuxiliaryFiles() const
123 // Note that we do not always call this function when there is an error.
124 // For example, if there is an error but an output file is produced we
125 // still would like to output (export/view) the file.
127 // What files do we have to delete?
129 // This will at least make latex do all the runs
130 depfile.removeFile();
132 // but the reason for the error might be in a generated file...
135 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
139 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
143 FileName const ind(changeExtension(file.absFileName(), ".ind"));
147 FileName const nls(changeExtension(file.absFileName(), ".nls"));
150 // nomencl file (old version of the package)
151 FileName const gls(changeExtension(file.absFileName(), ".gls"));
154 // Also remove the aux file
155 FileName const aux(changeExtension(file.absFileName(), ".aux"));
158 // Also remove the .out file (e.g. hyperref bookmarks) (#9963)
159 FileName const out(changeExtension(file.absFileName(), ".out"));
162 // Remove the output file, which is often generated even if error
163 output_file.removeFile();
167 int LaTeX::run(TeXErrors & terr)
168 // We know that this function will only be run if the lyx buffer
169 // has been changed. We also know that a newly written .tex file
170 // is always different from the previous one because of the date
171 // in it. However it seems safe to run latex (at least) one time
172 // each time the .tex file changes.
174 int scanres = NO_ERRORS;
175 int bscanres = NO_ERRORS;
176 unsigned int count = 0; // number of times run
177 num_errors = 0; // just to make sure.
178 unsigned int const MAX_RUN = 6;
179 DepTable head; // empty head
180 bool rerun = false; // rerun requested
182 // The class LaTeX does not know the temp path.
183 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
187 // first check if the file dependencies exist:
188 // ->If it does exist
189 // check if any of the files mentioned in it have
190 // changed (done using a checksum).
192 // run latex once and
193 // remake the dependency file
194 // -> if not changed:
195 // just return there is nothing to do for us.
196 // ->if it doesn't exist
198 // run latex once (we need to run latex once anyway) and
199 // remake the dependency file.
202 bool had_depfile = depfile.exists();
203 bool run_bibtex = false;
204 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
207 LYXERR(Debug::DEPEND, "Dependency file exists");
208 // Read the dep file:
209 had_depfile = head.read(depfile);
213 // Update the checksums
215 // Can't just check if anything has changed because it might
216 // have aborted on error last time... in which cas we need
217 // to re-run latex and collect the error messages
218 // (even if they are the same).
219 if (!output_file.exists()) {
220 LYXERR(Debug::DEPEND,
221 "re-running LaTeX because output file doesn't exist.");
222 } else if (!head.sumchange()) {
223 LYXERR(Debug::DEPEND, "return no_change");
226 LYXERR(Debug::DEPEND, "Dependency file has changed");
229 if (head.extchanged(".bib") || head.extchanged(".bst"))
232 LYXERR(Debug::DEPEND,
233 "Dependency file does not exist, or has wrong format");
235 /// We scan the aux file even when had_depfile = false,
236 /// because we can run pdflatex on the file after running latex on it,
237 /// in which case we will not need to run bibtex again.
238 vector<AuxInfo> bibtex_info_old;
240 bibtex_info_old = scanAuxFiles(aux_file, runparams.only_childbibs);
243 LYXERR(Debug::LATEX, "Run #" << count);
244 message(runMessage(count));
246 int exit_code = startscript();
248 scanres = scanLogFile(terr);
249 if (scanres & ERROR_RERUN) {
250 LYXERR(Debug::LATEX, "Rerunning LaTeX");
252 exit_code = startscript();
253 scanres = scanLogFile(terr);
256 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file, runparams.only_childbibs);
257 if (!run_bibtex && bibtex_info_old != bibtex_info)
260 // update the dependencies.
261 deplog(head); // reads the latex log
265 // At this point we must run external programs if needed.
266 // makeindex will be run if a .idx file changed or was generated.
267 // And if there were undefined citations or changes in references
268 // the .aux file is checked for signs of bibtex. Bibtex is then run
271 // memoir (at least) writes an empty *idx file in the first place.
272 // A second latex run is needed.
273 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
274 rerun = idxfile.exists() && idxfile.isFileEmpty();
277 if (head.haschanged(idxfile)) {
279 LYXERR(Debug::LATEX, "Running MakeIndex.");
280 message(_("Running Index Processor."));
281 // onlyFileName() is needed for cygwin
282 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
285 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
286 // If all nomencl entries are removed, nomencl writes an empty nlo file.
287 // DepTable::hasChanged() returns false in this case, since it does not
288 // distinguish empty files from non-existing files. This is why we need
289 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
290 // FIXME: Sort out the real problem in DepTable.
291 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
292 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
293 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
294 if (head.haschanged(glofile))
295 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
297 // check if we're using biber instead of bibtex
298 // biber writes no info to the aux file, so we just check
299 // if a bcf file exists (and if it was updated)
300 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
301 biber |= head.exist(bcffile);
304 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
305 if (scanres & UNDEF_CIT || run_bibtex) {
306 // Here we must scan the .aux file and look for
307 // "\bibdata" and/or "\bibstyle". If one of those
308 // tags is found -> run bibtex and set rerun = true;
310 LYXERR(Debug::LATEX, "Running BibTeX.");
311 message(_("Running BibTeX."));
312 updateBibtexDependencies(head, bibtex_info);
313 rerun |= runBibTeX(bibtex_info, runparams);
314 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
315 if (blgfile.exists())
316 bscanres = scanBlgFile(head, terr);
317 } else if (!had_depfile) {
318 /// If we run pdflatex on the file after running latex on it,
319 /// then we do not need to run bibtex, but we do need to
320 /// insert the .bib and .bst files into the .dep-pdf file.
321 updateBibtexDependencies(head, bibtex_info);
325 // we know on this point that latex has been run once (or we just
326 // returned) and the question now is to decide if we need to run
327 // it any more. This is done by asking if any of the files in the
328 // dependency file has changed. (remember that the checksum for
329 // a given file is reported to have changed if it just was created)
330 // -> if changed or rerun == true:
331 // run latex once more and
332 // update the dependency structure
333 // -> if not changed:
334 // we do nothing at this point
336 if (rerun || head.sumchange()) {
339 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
340 LYXERR(Debug::LATEX, "Run #" << count);
341 message(runMessage(count));
343 scanres = scanLogFile(terr);
345 // update the depedencies
346 deplog(head); // reads the latex log
349 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
354 // Complex bibliography packages such as Biblatex require
355 // an additional bibtex cycle sometimes.
356 if (scanres & UNDEF_CIT) {
357 // Here we must scan the .aux file and look for
358 // "\bibdata" and/or "\bibstyle". If one of those
359 // tags is found -> run bibtex and set rerun = true;
361 LYXERR(Debug::LATEX, "Running BibTeX.");
362 message(_("Running BibTeX."));
363 updateBibtexDependencies(head, bibtex_info);
364 rerun |= runBibTeX(bibtex_info, runparams);
365 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
366 if (blgfile.exists())
367 bscanres = scanBlgFile(head, terr);
371 // The inclusion of files generated by external programs such as
372 // makeindex or bibtex might have done changes to pagenumbering,
373 // etc. And because of this we must run the external programs
374 // again to make sure everything is redone correctly.
375 // Also there should be no need to run the external programs any
378 // run makeindex if the <file>.idx has changed or was generated.
379 if (head.haschanged(idxfile)) {
381 LYXERR(Debug::LATEX, "Running MakeIndex.");
382 message(_("Running Index Processor."));
383 // onlyFileName() is needed for cygwin
384 rerun = runMakeIndex(onlyFileName(changeExtension(
385 file.absFileName(), ".idx")), runparams);
388 // I am not pretty sure if need this twice.
389 if (head.haschanged(nlofile))
390 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
391 if (head.haschanged(glofile))
392 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
395 // we will only run latex more if the log file asks for it.
396 // or if the sumchange() is true.
397 // -> rerun asked for:
399 // remake the dependency file
400 // goto 2 or return if max runs are reached.
401 // -> rerun not asked for:
402 // just return (fall out of bottom of func)
404 while ((head.sumchange() || rerun || (scanres & RERUN))
405 && count < MAX_RUN) {
406 // Yes rerun until message goes away, or until
407 // MAX_RUNS are reached.
410 LYXERR(Debug::LATEX, "Run #" << count);
411 message(runMessage(count));
413 scanres = scanLogFile(terr);
419 // Write the dependencies to file.
423 // add flag here, just before return, instead of when exit_code
424 // is defined because scanres is sometimes overwritten above
426 scanres |= NONZERO_ERROR;
429 LYXERR(Debug::LATEX, "Done.");
431 if (bscanres & ERRORS)
432 return bscanres; // return on error
438 int LaTeX::startscript()
440 // onlyFileName() is needed for cygwin
441 string tmp = cmd + ' '
442 + quoteName(onlyFileName(file.toFilesystemEncoding()))
443 + " > " + os::nulldev();
445 return one.startscript(Systemcall::Wait, tmp, path, lpath);
449 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
450 string const & params)
452 string tmp = runparams.use_japanese ?
453 lyxrc.jindex_command : lyxrc.index_command;
455 if (!runparams.index_command.empty())
456 tmp = runparams.index_command;
459 "idx file has been made, running index processor ("
460 << tmp << ") on file " << f);
462 tmp = subst(tmp, "$$lang", runparams.document_language);
463 if (runparams.use_indices) {
464 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
466 "Multiple indices. Using splitindex command: " << tmp);
472 one.startscript(Systemcall::Wait, tmp, path, lpath);
477 bool LaTeX::runMakeIndexNomencl(FileName const & file,
478 string const & nlo, string const & nls)
480 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
481 message(_("Running MakeIndex for nomencl."));
482 string tmp = lyxrc.nomencl_command + ' ';
483 // onlyFileName() is needed for cygwin
484 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
486 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
488 one.startscript(Systemcall::Wait, tmp, path, lpath);
493 vector<AuxInfo> const
494 LaTeX::scanAuxFiles(FileName const & file, bool const only_childbibs)
496 vector<AuxInfo> result;
498 // With chapterbib, we have to bibtex all children's aux files
499 // but _not_ the master's!
500 if (only_childbibs) {
501 for (string const &s: children) {
503 makeAbsPath(s, file.onlyPath().realPath());
504 fn.changeExtension("aux");
506 result.push_back(scanAuxFile(fn));
511 result.push_back(scanAuxFile(file));
513 // This is for bibtopic
514 string const basename = removeExtension(file.absFileName());
515 for (int i = 1; i < 1000; ++i) {
516 FileName const file2(basename
517 + '.' + convert<string>(i)
521 result.push_back(scanAuxFile(file2));
527 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
530 result.aux_file = file;
531 scanAuxFile(file, result);
536 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
538 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
540 ifstream ifs(file.toFilesystemEncoding().c_str());
542 static regex const reg1("\\\\citation\\{([^}]+)\\}");
543 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
544 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
545 static regex const reg4("\\\\@input\\{([^}]+)\\}");
547 while (getline(ifs, token)) {
548 token = rtrim(token, "\r");
550 // FIXME UNICODE: We assume that citation keys and filenames
551 // in the aux file are in the file system encoding.
552 token = to_utf8(from_filesystem8bit(token));
553 if (regex_match(token, sub, reg1)) {
554 string data = sub.str(1);
555 while (!data.empty()) {
557 data = split(data, citation, ',');
558 LYXERR(Debug::LATEX, "Citation: " << citation);
559 aux_info.citations.insert(citation);
561 } else if (regex_match(token, sub, reg2)) {
562 string data = sub.str(1);
563 // data is now all the bib files separated by ','
564 // get them one by one and pass them to the helper
565 while (!data.empty()) {
567 data = split(data, database, ',');
568 database = changeExtension(database, "bib");
569 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
570 aux_info.databases.insert(database);
572 } else if (regex_match(token, sub, reg3)) {
573 string style = sub.str(1);
574 // token is now the style file
575 // pass it to the helper
576 style = changeExtension(style, "bst");
577 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
578 aux_info.styles.insert(style);
579 } else if (regex_match(token, sub, reg4)) {
580 string const file2 = sub.str(1);
581 scanAuxFile(makeAbsPath(file2), aux_info);
587 void LaTeX::updateBibtexDependencies(DepTable & dep,
588 vector<AuxInfo> const & bibtex_info)
590 // Since a run of Bibtex mandates more latex runs it is ok to
591 // remove all ".bib" and ".bst" files.
592 dep.remove_files_with_extension(".bib");
593 dep.remove_files_with_extension(".bst");
594 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
596 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
597 it != bibtex_info.end(); ++it) {
598 for (set<string>::const_iterator it2 = it->databases.begin();
599 it2 != it->databases.end(); ++it2) {
600 FileName const file = findtexfile(*it2, "bib");
602 dep.insert(file, true);
605 for (set<string>::const_iterator it2 = it->styles.begin();
606 it2 != it->styles.end(); ++it2) {
607 FileName const file = findtexfile(*it2, "bst");
609 dep.insert(file, true);
613 // biber writes nothing into the aux file.
614 // Instead, we have to scan the blg file
617 scanBlgFile(dep, terr);
622 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
623 OutputParams const & runparams)
626 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
627 it != bibtex_info.end(); ++it) {
628 if (!biber && it->databases.empty())
632 string tmp = runparams.bibtex_command;
634 // onlyFileName() is needed for cygwin
635 tmp += quoteName(onlyFileName(removeExtension(
636 it->aux_file.absFileName())));
638 one.startscript(Systemcall::Wait, tmp, path, lpath);
640 // Return whether bibtex was run
645 int LaTeX::scanLogFile(TeXErrors & terr)
649 int retval = NO_ERRORS;
651 onlyFileName(changeExtension(file.absFileName(), ".log"));
652 LYXERR(Debug::LATEX, "Log file: " << tmp);
653 FileName const fn = FileName(makeAbsPath(tmp));
654 ifstream ifs(fn.toFilesystemEncoding().c_str());
655 bool fle_style = false;
656 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
657 static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
658 // Flag for 'File ended while scanning' message.
659 // We need to wait for subsequent processing.
660 string wait_for_error;
663 stack <pair<string, int> > child;
667 while (getline(ifs, token)) {
668 // MikTeX sometimes inserts \0 in the log file. They can't be
669 // removed directly with the existing string utility
670 // functions, so convert them first to \r, and remove all
671 // \r's afterwards, since we need to remove them anyway.
672 token = subst(token, '\0', '\r');
673 token = subst(token, "\r", "");
676 LYXERR(Debug::LATEX, "Log line: " << token);
681 // Track child documents
682 for (size_t i = 0; i < token.length(); ++i) {
683 if (token[i] == '(') {
685 size_t j = token.find('(', i + 1);
686 size_t len = j == string::npos
687 ? token.substr(i + 1).length()
689 string const substr = token.substr(i + 1, len);
690 if (regex_match(substr, sub, child_file)) {
691 string const name = sub.str(1);
692 child.push(make_pair(name, pnest));
693 children.push_back(name);
696 } else if (token[i] == ')') {
698 && child.top().second == pnest)
703 child_name = child.empty() ? empty_string() : child.top().first;
705 if (contains(token, "file:line:error style messages enabled"))
708 if (prefixIs(token, "LaTeX Warning:") ||
709 prefixIs(token, "! pdfTeX warning")) {
710 // Here shall we handle different
712 retval |= LATEX_WARNING;
713 LYXERR(Debug::LATEX, "LaTeX Warning.");
714 if (contains(token, "Rerun to get cross-references")) {
716 LYXERR(Debug::LATEX, "We should rerun.");
717 // package clefval needs 2 latex runs before bibtex
718 } else if (contains(token, "Value of")
719 && contains(token, "on page")
720 && contains(token, "undefined")) {
721 retval |= ERROR_RERUN;
722 LYXERR(Debug::LATEX, "Force rerun.");
724 } else if (contains(token, "Etaremune labels have changed")) {
725 retval |= ERROR_RERUN;
726 LYXERR(Debug::LATEX, "Force rerun.");
727 } else if (contains(token, "Citation")
728 && contains(token, "on page")
729 && contains(token, "undefined")) {
731 } else if (contains(token, "Citation")
732 && contains(token, "on input line")
733 && contains(token, "undefined")) {
736 } else if (prefixIs(token, "Package")) {
738 retval |= PACKAGE_WARNING;
739 if (contains(token, "natbib Warning:")) {
741 if (contains(token, "Citation")
742 && contains(token, "on page")
743 && contains(token, "undefined")) {
746 } else if (contains(token, "run BibTeX")) {
748 } else if (contains(token, "run Biber")) {
751 } else if (contains(token, "Rerun LaTeX") ||
752 contains(token, "Please rerun LaTeX") ||
753 contains(token, "Rerun to get")) {
754 // at least longtable.sty and bibtopic.sty
756 LYXERR(Debug::LATEX, "We should rerun.");
759 } else if (prefixIs(token, "LETTRE WARNING:")) {
760 if (contains(token, "veuillez recompiler")) {
762 LYXERR(Debug::LATEX, "We should rerun.");
765 } else if (token[0] == '(') {
766 if (contains(token, "Rerun LaTeX") ||
767 contains(token, "Rerun to get")) {
769 LYXERR(Debug::LATEX, "We should rerun.");
772 } else if (prefixIs(token, "! ")
774 && regex_match(token, sub, file_line_error)
775 && !contains(token, "pdfTeX warning"))) {
776 // Ok, we have something that looks like a TeX Error
777 // but what do we really have.
779 // Just get the error description:
781 if (prefixIs(token, "! "))
782 desc = string(token, 2);
785 if (contains(token, "LaTeX Error:"))
786 retval |= LATEX_ERROR;
788 if (prefixIs(token, "! File ended while scanning")){
789 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
790 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
791 retval |= ERROR_RERUN;
792 LYXERR(Debug::LATEX, "Force rerun.");
794 // bug 6445. At this point its not clear we finish with error.
795 wait_for_error = desc;
800 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
801 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
802 retval |= ERROR_RERUN;
803 LYXERR(Debug::LATEX, "Force rerun.");
806 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
807 retval |= LATEX_ERROR;
810 errstr = wait_for_error;
812 if (!getline(ifs, tmp))
814 tmp = rtrim(tmp, "\r");
815 errstr += "\n" + tmp;
818 } while (!contains(tmp, "(job aborted"));
821 from_local8bit("Emergency stop"),
822 from_local8bit(errstr),
830 if (!getline(ifs, tmp))
832 tmp = rtrim(tmp, "\r");
833 // 15 is somewhat arbitrarily chosen, based on practice.
834 // We used 10 for 14 years and increased it to 15 when we
838 } while (!prefixIs(tmp, "l."));
839 if (prefixIs(tmp, "l.")) {
840 // we have a latex error
843 "Package babel Error: You haven't defined the language")
845 "Package babel Error: You haven't loaded the option")
847 "Package babel Error: Unknown language"))
848 retval |= ERROR_RERUN;
849 // get the line number:
851 sscanf(tmp.c_str(), "l.%d", &line);
852 // get the rest of the message:
853 string errstr(tmp, tmp.find(' '));
856 tmp = rtrim(tmp, "\r");
857 while (!contains(errstr, "l.")
859 && !prefixIs(tmp, "! ")
860 && !contains(tmp, "(job aborted")) {
864 tmp = rtrim(tmp, "\r");
866 LYXERR(Debug::LATEX, "line: " << line << '\n'
867 << "Desc: " << desc << '\n' << "Text: " << errstr);
868 if (line == last_line)
874 if (line_count <= 5) {
876 // We have no idea what the encoding of
878 // It seems that the output from the
879 // latex compiler itself is pure ASCII,
880 // but it can include bits from the
881 // document, so whatever encoding we
882 // assume here it can be wrong.
883 terr.insertError(line,
884 from_local8bit(desc),
885 from_local8bit(errstr),
891 // information messages, TeX warnings and other
892 // warnings we have not caught earlier.
893 if (prefixIs(token, "Overfull ")) {
894 retval |= TEX_WARNING;
895 } else if (prefixIs(token, "Underfull ")) {
896 retval |= TEX_WARNING;
897 } else if (contains(token, "Rerun to get citations")) {
898 // Natbib seems to use this.
900 } else if (contains(token, "No pages of output")
901 || contains(token, "no pages of output")) {
902 // No output file (e.g. the DVI or PDF) was created
904 } else if (contains(token, "That makes 100 errors")) {
905 // More than 100 errors were reprted
906 retval |= TOO_MANY_ERRORS;
907 } else if (prefixIs(token, "!pdfTeX error:")) {
908 // otherwise we dont catch e.g.:
909 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
912 from_local8bit("pdfTeX Error"),
913 from_local8bit(token),
915 } else if (!ignore_missing_glyphs
916 && prefixIs(token, "Missing character: There is no ")
917 && !contains(token, "nullfont")) {
918 // Warning about missing glyph in selected font
919 // may be dataloss (bug 9610)
920 // but can be ignored for 'nullfont' (bug 10394).
921 retval |= LATEX_ERROR;
923 from_local8bit("Missing glyphs!"),
924 from_local8bit(token),
929 LYXERR(Debug::LATEX, "Log line: " << token);
936 bool insertIfExists(FileName const & absname, DepTable & head)
938 if (absname.exists() && !absname.isDirectory()) {
939 head.insert(absname, true);
946 bool handleFoundFile(string const & ff, DepTable & head)
948 // convert from native os path to unix path
949 string foundfile = os::internal_path(trim(ff));
951 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
953 // Ok now we found a file.
954 // Now we should make sure that this is a file that we can
955 // access through the normal paths.
956 // We will not try any fancy search methods to
959 // (1) foundfile is an
960 // absolute path and should
963 if (FileName::isAbsolute(foundfile)) {
964 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
965 // On initial insert we want to do the update at once
966 // since this file cannot be a file generated by
968 absname.set(foundfile);
969 if (!insertIfExists(absname, head)) {
971 string strippedfile = foundfile;
972 while (contains(strippedfile, " ")) {
973 // files with spaces are often enclosed in quotation
974 // marks; those have to be removed
975 string unquoted = subst(strippedfile, "\"", "");
976 absname.set(unquoted);
977 if (insertIfExists(absname, head))
979 // strip off part after last space and try again
980 string tmp = strippedfile;
981 rsplit(tmp, strippedfile, ' ');
982 absname.set(strippedfile);
983 if (insertIfExists(absname, head))
989 string onlyfile = onlyFileName(foundfile);
990 absname = makeAbsPath(onlyfile);
993 while (contains(foundfile, ' ')) {
994 if (absname.exists())
998 // files with spaces are often enclosed in quotation
999 // marks; those have to be removed
1000 string unquoted = subst(foundfile, "\"", "");
1001 absname = makeAbsPath(unquoted);
1002 if (absname.exists())
1004 // strip off part after last space and try again
1005 string strippedfile;
1006 rsplit(foundfile, strippedfile, ' ');
1007 foundfile = strippedfile;
1008 onlyfile = onlyFileName(strippedfile);
1009 absname = makeAbsPath(onlyfile);
1013 // (2) foundfile is in the tmpdir
1014 // insert it into head
1015 if (absname.exists() && !absname.isDirectory()) {
1016 // FIXME: This regex contained glo, but glo is used by the old
1017 // version of nomencl.sty. Do we need to put it back?
1018 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1019 if (regex_match(onlyfile, unwanted)) {
1020 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1021 << " in the dep file");
1022 } else if (suffixIs(onlyfile, ".tex")) {
1023 // This is a tex file generated by LyX
1024 // and latex is not likely to change this
1026 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1027 head.insert(absname, true);
1029 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1030 head.insert(absname);
1034 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1040 bool completeFilename(string const & ff, DepTable & head)
1042 // If we do not find a dot, we suspect
1043 // a fragmental file name
1044 if (!contains(ff, '.'))
1047 // if we have a dot, we let handleFoundFile decide
1048 return handleFoundFile(ff, head);
1052 int iterateLine(string const & token, regex const & reg, string const & closing,
1053 int fragment_pos, DepTable & head)
1056 string::const_iterator first = token.begin();
1057 string::const_iterator end = token.end();
1058 bool fragment = false;
1061 while (regex_search(first, end, what, reg)) {
1062 // if we have a dot, try to handle as file
1063 if (contains(what.str(1), '.')) {
1064 first = what[0].second;
1065 if (what.str(2) == closing) {
1066 handleFoundFile(what.str(1), head);
1067 // since we had a closing bracket,
1068 // do not investigate further
1071 // if we have no closing bracket,
1072 // try to handle as file nevertheless
1073 fragment = !handleFoundFile(
1074 what.str(1) + what.str(2), head);
1076 // if we do not have a dot, check if the line has
1077 // a closing bracket (else, we suspect a line break)
1078 else if (what.str(2) != closing) {
1079 first = what[0].second;
1082 // we have a closing bracket, so the content
1083 // is not a file name.
1084 // no need to investigate further
1085 first = what[0].second;
1088 last_match = what.str(1);
1091 // We need to consider the result from previous line iterations:
1092 // We might not find a fragment here, but another one might follow
1093 // E.g.: (filename.ext) <filenam
1094 // Vice versa, we consider the search completed if a real match
1095 // follows a potential fragment from a previous iteration.
1096 // E.g. <some text we considered a fragment (filename.ext)
1097 // result = -1 means we did not find a fragment!
1099 int last_match_pos = -1;
1100 if (!last_match.empty() && token.find(last_match) != string::npos)
1101 last_match_pos = int(token.find(last_match));
1103 if (last_match_pos > fragment_pos)
1104 result = last_match_pos;
1106 result = fragment_pos;
1108 if (last_match_pos < fragment_pos)
1109 result = fragment_pos;
1117 void LaTeX::deplog(DepTable & head)
1119 // This function reads the LaTeX log file end extracts all the
1120 // external files used by the LaTeX run. The files are then
1121 // entered into the dependency file.
1123 string const logfile =
1124 onlyFileName(changeExtension(file.absFileName(), ".log"));
1126 static regex const reg1("File: (.+).*");
1127 static regex const reg2("No file (.+)(.).*");
1128 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1129 // If an index should be created, MikTex does not write a line like
1130 // \openout# = 'sample.idx'.
1131 // but instead only a line like this into the log:
1132 // Writing index file sample.idx
1133 static regex const reg4("Writing index file (.+).*");
1134 static regex const regoldnomencl("Writing glossary file (.+).*");
1135 static regex const regnomencl("Writing nomenclature file (.+).*");
1136 // If a toc should be created, MikTex does not write a line like
1137 // \openout# = `sample.toc'.
1138 // but only a line like this into the log:
1140 // This line is also written by tetex.
1141 // This line is not present if no toc should be created.
1142 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1143 // file names can be enclosed in <...> (anywhere on the line)
1144 static regex const reg5(".*<[^>]+.*");
1145 // and also (...) anywhere on the line
1146 static regex const reg6(".*\\([^)]+.*");
1148 FileName const fn = makeAbsPath(logfile);
1149 ifstream ifs(fn.toFilesystemEncoding().c_str());
1152 // Ok, the scanning of files here is not sufficient.
1153 // Sometimes files are named by "File: xxx" only
1154 // Therefore we use some regexps to find files instead.
1155 // Note: all file names and paths might contains spaces.
1156 // Also, file names might be broken across lines. Therefore
1157 // we mark (potential) fragments and merge those lines.
1158 bool fragment = false;
1160 getline(ifs, token);
1161 // MikTeX sometimes inserts \0 in the log file. They can't be
1162 // removed directly with the existing string utility
1163 // functions, so convert them first to \r, and remove all
1164 // \r's afterwards, since we need to remove them anyway.
1165 token = subst(token, '\0', '\r');
1166 token = subst(token, "\r", "");
1167 if (token.empty() || token == ")") {
1168 lastline = string();
1172 // FIXME UNICODE: We assume that the file names in the log
1173 // file are in the file system encoding.
1174 token = to_utf8(from_filesystem8bit(token));
1176 // Sometimes, filenames are broken across lines.
1177 // We care for that and save suspicious lines.
1178 // Here we exclude some cases where we are sure
1179 // that there is no continued filename
1180 if (!lastline.empty()) {
1181 static regex const package_info("Package \\w+ Info: .*");
1182 static regex const package_warning("Package \\w+ Warning: .*");
1183 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1184 || prefixIs(token, "Package:")
1185 || prefixIs(token, "Language:")
1186 || prefixIs(token, "LaTeX Info:")
1187 || prefixIs(token, "LaTeX Font Info:")
1188 || prefixIs(token, "\\openout[")
1189 || prefixIs(token, "))")
1190 || regex_match(token, package_info)
1191 || regex_match(token, package_warning))
1192 lastline = string();
1195 if (!lastline.empty())
1196 // probably a continued filename from last line
1197 token = lastline + token;
1198 if (token.length() > 255) {
1199 // string too long. Cut off.
1200 token.erase(0, token.length() - 251);
1205 // (1) "File: file.ext"
1206 if (regex_match(token, sub, reg1)) {
1207 // is this a fragmental file name?
1208 fragment = !completeFilename(sub.str(1), head);
1210 if (suffixIs(token, ")"))
1211 // no fragment for sure
1213 // (2) "No file file.ext"
1214 } else if (regex_match(token, sub, reg2)) {
1215 // file names must contains a dot, line ends with dot
1216 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1217 fragment = !handleFoundFile(sub.str(1), head);
1219 // we suspect a line break
1221 // (3) "\openout<nr> = `file.ext'."
1222 } else if (regex_match(token, sub, reg3)) {
1223 // search for closing '. at the end of the line
1224 if (sub.str(2) == "\'.")
1225 fragment = !handleFoundFile(sub.str(1), head);
1227 // potential fragment
1229 // (4) "Writing index file file.ext"
1230 } else if (regex_match(token, sub, reg4))
1231 // fragmential file name?
1232 fragment = !completeFilename(sub.str(1), head);
1233 // (5) "Writing nomenclature file file.ext"
1234 else if (regex_match(token, sub, regnomencl) ||
1235 regex_match(token, sub, regoldnomencl))
1236 // fragmental file name?
1237 fragment= !completeFilename(sub.str(1), head);
1238 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1239 else if (regex_match(token, sub, miktexTocReg))
1240 fragment = !handleFoundFile(onlyFileName(changeExtension(
1241 file.absFileName(), ".toc")), head);
1243 // not found, but we won't check further
1246 int fragment_pos = -1;
1248 // We can have several of these on one line
1249 // (and in addition to those above)
1250 if (regex_match(token, sub, reg5)) {
1251 // search for strings in <...>
1252 static regex const reg5_1("<([^>]+)(.)");
1253 fragment_pos = iterateLine(token, reg5_1, ">",
1254 fragment_pos, head);
1255 fragment = (fragment_pos != -1);
1259 // We can have several of these on one line
1260 // this must be queried separated, because of
1261 // cases such as "File: file.ext (type eps)"
1262 // where "File: file.ext" would be skipped
1263 if (regex_match(token, sub, reg6)) {
1264 // search for strings in (...)
1265 static regex const reg6_1("\\(([^()]+)(.)");
1266 fragment_pos = iterateLine(token, reg6_1, ")",
1267 fragment_pos, head);
1268 fragment = (fragment_pos != -1);
1272 // probable linebreak within file name:
1276 // no linebreak: reset
1277 lastline = string();
1280 // Make sure that the main .tex file is in the dependency file.
1281 head.insert(file, true);
1285 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1287 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1288 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1290 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1292 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1293 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1294 static regex const bibtexError2("^(.*---while reading file).*$");
1295 static regex const bibtexError3("(A bad cross reference---).*");
1296 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1297 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1298 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1299 int retval = NO_ERRORS;
1302 while (getline(ifs, token)) {
1303 token = rtrim(token, "\r");
1305 // FIXME UNICODE: We assume that citation keys and filenames
1306 // in the aux file are in the file system encoding.
1307 token = to_utf8(from_filesystem8bit(token));
1308 if (regex_match(token, sub, reg1)) {
1309 string data = sub.str(3);
1310 if (!data.empty()) {
1311 LYXERR(Debug::LATEX, "Found bib file: " << data);
1312 handleFoundFile(data, dep);
1315 else if (regex_match(token, sub, bibtexError)
1316 || regex_match(token, sub, bibtexError2)
1317 || regex_match(token, sub, bibtexError4)
1318 || regex_match(token, sub, bibtexError5)) {
1319 retval |= BIBTEX_ERROR;
1320 string errstr = N_("BibTeX error: ") + token;
1322 if ((prefixIs(token, "while executing---line")
1323 || prefixIs(token, "---line ")
1324 || prefixIs(token, "*Please notify the BibTeX"))
1325 && !prevtoken.empty()) {
1326 errstr = N_("BibTeX error: ") + prevtoken;
1327 message = prevtoken + '\n';
1331 from_local8bit(errstr),
1332 from_local8bit(message));
1333 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1334 retval |= BIBTEX_ERROR;
1335 string errstr = N_("BibTeX error: ") + prevtoken;
1336 string message = prevtoken + '\n' + token;
1338 from_local8bit(errstr),
1339 from_local8bit(message));
1340 } else if (regex_match(token, sub, biberError)) {
1341 retval |= BIBTEX_ERROR;
1342 string errstr = N_("Biber error: ") + sub.str(2);
1343 string message = token;
1345 from_local8bit(errstr),
1346 from_local8bit(message));