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"
23 #include "support/debug.h"
24 #include "support/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/gettext.h"
28 #include "support/lstrings.h"
29 #include "support/Systemcall.h"
30 #include "support/os.h"
32 #include "support/regex.h"
39 using namespace lyx::support;
43 namespace os = support::os;
45 // TODO: in no particular order
46 // - get rid of the call to
47 // BufferList::updateIncludedTeXfiles, this should either
48 // be done before calling LaTeX::funcs or in a completely
50 // - the makeindex style files should be taken care of with
51 // the dependency mechanism.
55 docstring runMessage(unsigned int count)
57 return bformat(_("Waiting for LaTeX run number %1$d"), count);
66 void TeXErrors::insertError(int line, docstring const & error_desc,
67 docstring const & error_text,
68 string const & child_name)
70 Error newerr(line, error_desc, error_text, child_name);
71 errors.push_back(newerr);
75 bool operator==(AuxInfo const & a, AuxInfo const & o)
77 return a.aux_file == o.aux_file
78 && a.citations == o.citations
79 && a.databases == o.databases
80 && a.styles == o.styles;
84 bool operator!=(AuxInfo const & a, AuxInfo const & o)
94 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
95 FileName const & f, string const & p)
96 : cmd(latex), file(f), path(p), runparams(rp), biber(false)
99 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
100 depfile = FileName(file.absFileName() + ".dep-pdf");
102 FileName(changeExtension(file.absFileName(), ".pdf"));
104 depfile = FileName(file.absFileName() + ".dep");
106 FileName(changeExtension(file.absFileName(), ".dvi"));
111 void LaTeX::deleteFilesOnError() const
113 // currently just a dummy function.
115 // What files do we have to delete?
117 // This will at least make latex do all the runs
118 depfile.removeFile();
120 // but the reason for the error might be in a generated file...
123 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
127 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
131 FileName const ind(changeExtension(file.absFileName(), ".ind"));
135 FileName const nls(changeExtension(file.absFileName(), ".nls"));
138 // nomencl file (old version of the package)
139 FileName const gls(changeExtension(file.absFileName(), ".gls"));
142 // Also remove the aux file
143 FileName const aux(changeExtension(file.absFileName(), ".aux"));
148 int LaTeX::run(TeXErrors & terr)
149 // We know that this function will only be run if the lyx buffer
150 // has been changed. We also know that a newly written .tex file
151 // is always different from the previous one because of the date
152 // in it. However it seems safe to run latex (at least) one time
153 // each time the .tex file changes.
155 int scanres = NO_ERRORS;
156 unsigned int count = 0; // number of times run
157 num_errors = 0; // just to make sure.
158 unsigned int const MAX_RUN = 6;
159 DepTable head; // empty head
160 bool rerun = false; // rerun requested
162 // The class LaTeX does not know the temp path.
163 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
166 // Never write the depfile if an error was encountered.
169 // first check if the file dependencies exist:
170 // ->If it does exist
171 // check if any of the files mentioned in it have
172 // changed (done using a checksum).
174 // run latex once and
175 // remake the dependency file
176 // -> if not changed:
177 // just return there is nothing to do for us.
178 // ->if it doesn't exist
180 // run latex once (we need to run latex once anyway) and
181 // remake the dependency file.
184 bool had_depfile = depfile.exists();
185 bool run_bibtex = false;
186 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
189 LYXERR(Debug::DEPEND, "Dependency file exists");
190 // Read the dep file:
191 had_depfile = head.read(depfile);
195 // Update the checksums
197 // Can't just check if anything has changed because it might
198 // have aborted on error last time... in which cas we need
199 // to re-run latex and collect the error messages
200 // (even if they are the same).
201 if (!output_file.exists()) {
202 LYXERR(Debug::DEPEND,
203 "re-running LaTeX because output file doesn't exist.");
204 } else if (!head.sumchange()) {
205 LYXERR(Debug::DEPEND, "return no_change");
208 LYXERR(Debug::DEPEND, "Dependency file has changed");
211 if (head.extchanged(".bib") || head.extchanged(".bst"))
214 LYXERR(Debug::DEPEND,
215 "Dependency file does not exist, or has wrong format");
217 /// We scan the aux file even when had_depfile = false,
218 /// because we can run pdflatex on the file after running latex on it,
219 /// in which case we will not need to run bibtex again.
220 vector<AuxInfo> bibtex_info_old;
222 bibtex_info_old = scanAuxFiles(aux_file);
225 LYXERR(Debug::LATEX, "Run #" << count);
226 message(runMessage(count));
229 scanres = scanLogFile(terr);
230 if (scanres & ERROR_RERUN) {
231 LYXERR(Debug::LATEX, "Rerunning LaTeX");
233 scanres = scanLogFile(terr);
236 if (scanres & ERRORS) {
237 deleteFilesOnError();
238 return scanres; // return on error
241 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
242 if (!run_bibtex && bibtex_info_old != bibtex_info)
245 // update the dependencies.
246 deplog(head); // reads the latex log
250 // At this point we must run external programs if needed.
251 // makeindex will be run if a .idx file changed or was generated.
252 // And if there were undefined citations or changes in references
253 // the .aux file is checked for signs of bibtex. Bibtex is then run
256 // memoir (at least) writes an empty *idx file in the first place.
257 // A second latex run is needed.
258 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
259 rerun = idxfile.exists() && idxfile.isFileEmpty();
262 if (head.haschanged(idxfile)) {
264 LYXERR(Debug::LATEX, "Running MakeIndex.");
265 message(_("Running Index Processor."));
266 // onlyFileName() is needed for cygwin
267 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
270 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
271 // If all nomencl entries are removed, nomencl writes an empty nlo file.
272 // DepTable::hasChanged() returns false in this case, since it does not
273 // distinguish empty files from non-existing files. This is why we need
274 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
275 // FIXME: Sort out the real problem in DepTable.
276 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
277 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
278 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
279 if (head.haschanged(glofile))
280 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
282 // check if we're using biber instead of bibtex
283 // biber writes no info to the aux file, so we just check
284 // if a bcf file exists (and if it was updated)
285 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
286 biber |= head.exist(bcffile);
289 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
290 if (scanres & UNDEF_CIT || run_bibtex) {
291 // Here we must scan the .aux file and look for
292 // "\bibdata" and/or "\bibstyle". If one of those
293 // tags is found -> run bibtex and set rerun = true;
295 LYXERR(Debug::LATEX, "Running BibTeX.");
296 message(_("Running BibTeX."));
297 updateBibtexDependencies(head, bibtex_info);
298 rerun |= runBibTeX(bibtex_info, runparams);
299 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
300 if (blgfile.exists()) {
301 int bscanres = scanBlgFile(head, terr);
302 if (bscanres & ERRORS) {
303 deleteFilesOnError();
304 return bscanres; // return on error
307 } else if (!had_depfile) {
308 /// If we run pdflatex on the file after running latex on it,
309 /// then we do not need to run bibtex, but we do need to
310 /// insert the .bib and .bst files into the .dep-pdf file.
311 updateBibtexDependencies(head, bibtex_info);
315 // we know on this point that latex has been run once (or we just
316 // returned) and the question now is to decide if we need to run
317 // it any more. This is done by asking if any of the files in the
318 // dependency file has changed. (remember that the checksum for
319 // a given file is reported to have changed if it just was created)
320 // -> if changed or rerun == true:
321 // run latex once more and
322 // update the dependency structure
323 // -> if not changed:
324 // we do nothing at this point
326 if (rerun || head.sumchange()) {
329 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
330 LYXERR(Debug::LATEX, "Run #" << count);
331 message(runMessage(count));
333 scanres = scanLogFile(terr);
334 if (scanres & ERRORS) {
335 deleteFilesOnError();
336 return scanres; // return on error
339 // update the depedencies
340 deplog(head); // reads the latex log
343 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
348 // Complex bibliography packages such as Biblatex require
349 // an additional bibtex cycle sometimes.
350 if (scanres & UNDEF_CIT) {
351 // Here we must scan the .aux file and look for
352 // "\bibdata" and/or "\bibstyle". If one of those
353 // tags is found -> run bibtex and set rerun = true;
355 LYXERR(Debug::LATEX, "Running BibTeX.");
356 message(_("Running BibTeX."));
357 updateBibtexDependencies(head, bibtex_info);
358 rerun |= runBibTeX(bibtex_info, runparams);
359 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
360 if (blgfile.exists()) {
361 int bscanres = scanBlgFile(head, terr);
362 if (bscanres & ERRORS) {
363 deleteFilesOnError();
364 return bscanres; // return on error
370 // The inclusion of files generated by external programs such as
371 // makeindex or bibtex might have done changes to pagenumbering,
372 // etc. And because of this we must run the external programs
373 // again to make sure everything is redone correctly.
374 // Also there should be no need to run the external programs any
377 // run makeindex if the <file>.idx has changed or was generated.
378 if (head.haschanged(idxfile)) {
380 LYXERR(Debug::LATEX, "Running MakeIndex.");
381 message(_("Running Index Processor."));
382 // onlyFileName() is needed for cygwin
383 rerun = runMakeIndex(onlyFileName(changeExtension(
384 file.absFileName(), ".idx")), runparams);
387 // I am not pretty sure if need this twice.
388 if (head.haschanged(nlofile))
389 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
390 if (head.haschanged(glofile))
391 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
394 // we will only run latex more if the log file asks for it.
395 // or if the sumchange() is true.
396 // -> rerun asked for:
398 // remake the dependency file
399 // goto 2 or return if max runs are reached.
400 // -> rerun not asked for:
401 // just return (fall out of bottom of func)
403 while ((head.sumchange() || rerun || (scanres & RERUN))
404 && count < MAX_RUN) {
405 // Yes rerun until message goes away, or until
406 // MAX_RUNS are reached.
409 LYXERR(Debug::LATEX, "Run #" << count);
410 message(runMessage(count));
412 scanres = scanLogFile(terr);
413 if (scanres & ERRORS) {
414 deleteFilesOnError();
415 return scanres; // return on error
422 // Write the dependencies to file.
424 LYXERR(Debug::LATEX, "Done.");
429 int LaTeX::startscript()
431 // onlyFileName() is needed for cygwin
432 string tmp = cmd + ' '
433 + quoteName(onlyFileName(file.toFilesystemEncoding()))
434 + " > " + os::nulldev();
436 return one.startscript(Systemcall::Wait, tmp, path);
440 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
441 string const & params)
443 string tmp = runparams.use_japanese ?
444 lyxrc.jindex_command : lyxrc.index_command;
446 if (!runparams.index_command.empty())
447 tmp = runparams.index_command;
450 "idx file has been made, running index processor ("
451 << tmp << ") on file " << f);
453 tmp = subst(tmp, "$$lang", runparams.document_language);
454 if (runparams.use_indices) {
455 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
457 "Multiple indices. Using splitindex command: " << tmp);
463 one.startscript(Systemcall::Wait, tmp, path);
468 bool LaTeX::runMakeIndexNomencl(FileName const & file,
469 string const & nlo, string const & nls)
471 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
472 message(_("Running MakeIndex for nomencl."));
473 string tmp = lyxrc.nomencl_command + ' ';
474 // onlyFileName() is needed for cygwin
475 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
477 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
479 one.startscript(Systemcall::Wait, tmp, path);
484 vector<AuxInfo> const
485 LaTeX::scanAuxFiles(FileName const & file)
487 vector<AuxInfo> result;
489 result.push_back(scanAuxFile(file));
491 string const basename = removeExtension(file.absFileName());
492 for (int i = 1; i < 1000; ++i) {
493 FileName const file2(basename
494 + '.' + convert<string>(i)
498 result.push_back(scanAuxFile(file2));
504 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
507 result.aux_file = file;
508 scanAuxFile(file, result);
513 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
515 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
517 ifstream ifs(file.toFilesystemEncoding().c_str());
519 static regex const reg1("\\\\citation\\{([^}]+)\\}");
520 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
521 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
522 static regex const reg4("\\\\@input\\{([^}]+)\\}");
524 while (getline(ifs, token)) {
525 token = rtrim(token, "\r");
527 // FIXME UNICODE: We assume that citation keys and filenames
528 // in the aux file are in the file system encoding.
529 token = to_utf8(from_filesystem8bit(token));
530 if (regex_match(token, sub, reg1)) {
531 string data = sub.str(1);
532 while (!data.empty()) {
534 data = split(data, citation, ',');
535 LYXERR(Debug::LATEX, "Citation: " << citation);
536 aux_info.citations.insert(citation);
538 } else if (regex_match(token, sub, reg2)) {
539 string data = sub.str(1);
540 // data is now all the bib files separated by ','
541 // get them one by one and pass them to the helper
542 while (!data.empty()) {
544 data = split(data, database, ',');
545 database = changeExtension(database, "bib");
546 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
547 aux_info.databases.insert(database);
549 } else if (regex_match(token, sub, reg3)) {
550 string style = sub.str(1);
551 // token is now the style file
552 // pass it to the helper
553 style = changeExtension(style, "bst");
554 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
555 aux_info.styles.insert(style);
556 } else if (regex_match(token, sub, reg4)) {
557 string const file2 = sub.str(1);
558 scanAuxFile(makeAbsPath(file2), aux_info);
564 void LaTeX::updateBibtexDependencies(DepTable & dep,
565 vector<AuxInfo> const & bibtex_info)
567 // Since a run of Bibtex mandates more latex runs it is ok to
568 // remove all ".bib" and ".bst" files.
569 dep.remove_files_with_extension(".bib");
570 dep.remove_files_with_extension(".bst");
571 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
573 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
574 it != bibtex_info.end(); ++it) {
575 for (set<string>::const_iterator it2 = it->databases.begin();
576 it2 != it->databases.end(); ++it2) {
577 FileName const file = findtexfile(*it2, "bib");
579 dep.insert(file, true);
582 for (set<string>::const_iterator it2 = it->styles.begin();
583 it2 != it->styles.end(); ++it2) {
584 FileName const file = findtexfile(*it2, "bst");
586 dep.insert(file, true);
590 // biber writes nothing into the aux file.
591 // Instead, we have to scan the blg file
594 scanBlgFile(dep, terr);
599 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
600 OutputParams const & runparams)
603 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
604 it != bibtex_info.end(); ++it) {
605 if (!biber && it->databases.empty())
609 string tmp = runparams.use_japanese ?
610 lyxrc.jbibtex_command : lyxrc.bibtex_command;
612 if (!runparams.bibtex_command.empty())
613 tmp = runparams.bibtex_command;
615 // onlyFileName() is needed for cygwin
616 tmp += quoteName(onlyFileName(removeExtension(
617 it->aux_file.absFileName())));
619 one.startscript(Systemcall::Wait, tmp, path);
621 // Return whether bibtex was run
626 int LaTeX::scanLogFile(TeXErrors & terr)
630 int retval = NO_ERRORS;
632 onlyFileName(changeExtension(file.absFileName(), ".log"));
633 LYXERR(Debug::LATEX, "Log file: " << tmp);
634 FileName const fn = FileName(makeAbsPath(tmp));
635 ifstream ifs(fn.toFilesystemEncoding().c_str());
636 bool fle_style = false;
637 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
638 static regex child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
639 // Flag for 'File ended while scanning' message.
640 // We need to wait for subsequent processing.
641 string wait_for_error;
644 stack <pair<string, int> > child;
647 while (getline(ifs, token)) {
648 // MikTeX sometimes inserts \0 in the log file. They can't be
649 // removed directly with the existing string utility
650 // functions, so convert them first to \r, and remove all
651 // \r's afterwards, since we need to remove them anyway.
652 token = subst(token, '\0', '\r');
653 token = subst(token, "\r", "");
656 LYXERR(Debug::LATEX, "Log line: " << token);
661 // Track child documents
662 for (size_t i = 0; i < token.length(); ++i) {
663 if (token[i] == '(') {
665 size_t j = token.find('(', i + 1);
666 size_t len = j == string::npos
667 ? token.substr(i + 1).length()
669 if (regex_match(token.substr(i + 1, len),
671 string const name = sub.str(1);
672 child.push(make_pair(name, pnest));
675 } else if (token[i] == ')') {
677 && child.top().second == pnest)
682 child_name = child.empty() ? empty_string() : child.top().first;
684 if (contains(token, "file:line:error style messages enabled"))
687 if (prefixIs(token, "LaTeX Warning:") ||
688 prefixIs(token, "! pdfTeX warning")) {
689 // Here shall we handle different
691 retval |= LATEX_WARNING;
692 LYXERR(Debug::LATEX, "LaTeX Warning.");
693 if (contains(token, "Rerun to get cross-references")) {
695 LYXERR(Debug::LATEX, "We should rerun.");
696 // package clefval needs 2 latex runs before bibtex
697 } else if (contains(token, "Value of")
698 && contains(token, "on page")
699 && contains(token, "undefined")) {
700 retval |= ERROR_RERUN;
701 LYXERR(Debug::LATEX, "Force rerun.");
703 } else if (contains(token, "Etaremune labels have changed")) {
704 retval |= ERROR_RERUN;
705 LYXERR(Debug::LATEX, "Force rerun.");
706 } else if (contains(token, "Citation")
707 && contains(token, "on page")
708 && contains(token, "undefined")) {
710 } else if (contains(token, "Citation")
711 && contains(token, "on input line")
712 && contains(token, "undefined")) {
715 } else if (prefixIs(token, "Package")) {
717 retval |= PACKAGE_WARNING;
718 if (contains(token, "natbib Warning:")) {
720 if (contains(token, "Citation")
721 && contains(token, "on page")
722 && contains(token, "undefined")) {
725 } else if (contains(token, "run BibTeX")) {
727 } else if (contains(token, "run Biber")) {
730 } else if (contains(token, "Rerun LaTeX") ||
731 contains(token, "Please rerun LaTeX") ||
732 contains(token, "Rerun to get")) {
733 // at least longtable.sty and bibtopic.sty
735 LYXERR(Debug::LATEX, "We should rerun.");
738 } else if (prefixIs(token, "LETTRE WARNING:")) {
739 if (contains(token, "veuillez recompiler")) {
741 LYXERR(Debug::LATEX, "We should rerun.");
744 } else if (token[0] == '(') {
745 if (contains(token, "Rerun LaTeX") ||
746 contains(token, "Rerun to get")) {
748 LYXERR(Debug::LATEX, "We should rerun.");
751 } else if (prefixIs(token, "! ")
753 && regex_match(token, sub, file_line_error)
754 && !contains(token, "pdfTeX warning"))) {
755 // Ok, we have something that looks like a TeX Error
756 // but what do we really have.
758 // Just get the error description:
760 if (prefixIs(token, "! "))
761 desc = string(token, 2);
764 if (contains(token, "LaTeX Error:"))
765 retval |= LATEX_ERROR;
767 if (prefixIs(token, "! File ended while scanning")){
768 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
769 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
770 retval |= ERROR_RERUN;
771 LYXERR(Debug::LATEX, "Force rerun.");
773 // bug 6445. At this point its not clear we finish with error.
774 wait_for_error = desc;
779 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
780 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
781 retval |= ERROR_RERUN;
782 LYXERR(Debug::LATEX, "Force rerun.");
785 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
786 retval |= LATEX_ERROR;
789 errstr = wait_for_error;
791 if (!getline(ifs, tmp))
793 tmp = rtrim(tmp, "\r");
794 errstr += "\n" + tmp;
797 } while (!contains(tmp, "(job aborted"));
800 from_local8bit("Emergency stop"),
801 from_local8bit(errstr),
809 if (!getline(ifs, tmp))
811 tmp = rtrim(tmp, "\r");
814 } while (!prefixIs(tmp, "l."));
815 if (prefixIs(tmp, "l.")) {
816 // we have a latex error
819 "Package babel Error: You haven't defined the language")
821 "Package babel Error: You haven't loaded the option")
823 "Package babel Error: Unknown language"))
824 retval |= ERROR_RERUN;
825 // get the line number:
827 sscanf(tmp.c_str(), "l.%d", &line);
828 // get the rest of the message:
829 string errstr(tmp, tmp.find(' '));
832 tmp = rtrim(tmp, "\r");
833 while (!contains(errstr, "l.")
835 && !prefixIs(tmp, "! ")
836 && !contains(tmp, "(job aborted")) {
840 tmp = rtrim(tmp, "\r");
842 LYXERR(Debug::LATEX, "line: " << line << '\n'
843 << "Desc: " << desc << '\n' << "Text: " << errstr);
844 if (line == last_line)
850 if (line_count <= 5) {
852 // We have no idea what the encoding of
854 // It seems that the output from the
855 // latex compiler itself is pure ASCII,
856 // but it can include bits from the
857 // document, so whatever encoding we
858 // assume here it can be wrong.
859 terr.insertError(line,
860 from_local8bit(desc),
861 from_local8bit(errstr),
867 // information messages, TeX warnings and other
868 // warnings we have not caught earlier.
869 if (prefixIs(token, "Overfull ")) {
870 retval |= TEX_WARNING;
871 } else if (prefixIs(token, "Underfull ")) {
872 retval |= TEX_WARNING;
873 } else if (contains(token, "Rerun to get citations")) {
874 // Natbib seems to use this.
876 } else if (contains(token, "No pages of output")) {
877 // A dvi file was not created
879 } else if (contains(token, "That makes 100 errors")) {
880 // More than 100 errors were reprted
881 retval |= TOO_MANY_ERRORS;
882 } else if (prefixIs(token, "!pdfTeX error:")){
883 // otherwise we dont catch e.g.:
884 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
887 from_local8bit("pdfTeX Error"),
888 from_local8bit(token),
893 LYXERR(Debug::LATEX, "Log line: " << token);
900 bool insertIfExists(FileName const & absname, DepTable & head)
902 if (absname.exists() && !absname.isDirectory()) {
903 head.insert(absname, true);
910 bool handleFoundFile(string const & ff, DepTable & head)
912 // convert from native os path to unix path
913 string foundfile = os::internal_path(trim(ff));
915 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
917 // Ok now we found a file.
918 // Now we should make sure that this is a file that we can
919 // access through the normal paths.
920 // We will not try any fancy search methods to
923 // (1) foundfile is an
924 // absolute path and should
927 if (FileName::isAbsolute(foundfile)) {
928 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
929 // On initial insert we want to do the update at once
930 // since this file cannot be a file generated by
932 absname.set(foundfile);
933 if (!insertIfExists(absname, head)) {
935 string strippedfile = foundfile;
936 while (contains(strippedfile, " ")) {
937 // files with spaces are often enclosed in quotation
938 // marks; those have to be removed
939 string unquoted = subst(strippedfile, "\"", "");
940 absname.set(unquoted);
941 if (insertIfExists(absname, head))
943 // strip off part after last space and try again
944 string tmp = strippedfile;
945 string const stripoff =
946 rsplit(tmp, strippedfile, ' ');
947 absname.set(strippedfile);
948 if (insertIfExists(absname, head))
954 string onlyfile = onlyFileName(foundfile);
955 absname = makeAbsPath(onlyfile);
958 while (contains(foundfile, ' ')) {
959 if (absname.exists())
963 // files with spaces are often enclosed in quotation
964 // marks; those have to be removed
965 string unquoted = subst(foundfile, "\"", "");
966 absname = makeAbsPath(unquoted);
967 if (absname.exists())
969 // strip off part after last space and try again
971 string const stripoff =
972 rsplit(foundfile, strippedfile, ' ');
973 foundfile = strippedfile;
974 onlyfile = onlyFileName(strippedfile);
975 absname = makeAbsPath(onlyfile);
979 // (2) foundfile is in the tmpdir
980 // insert it into head
981 if (absname.exists() && !absname.isDirectory()) {
982 // FIXME: This regex contained glo, but glo is used by the old
983 // version of nomencl.sty. Do we need to put it back?
984 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
985 if (regex_match(onlyfile, unwanted)) {
986 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
987 << " in the dep file");
988 } else if (suffixIs(onlyfile, ".tex")) {
989 // This is a tex file generated by LyX
990 // and latex is not likely to change this
992 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
993 head.insert(absname, true);
995 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
996 head.insert(absname);
1000 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1006 bool completeFilename(string const & ff, DepTable & head)
1008 // If we do not find a dot, we suspect
1009 // a fragmental file name
1010 if (!contains(ff, '.'))
1013 // if we have a dot, we let handleFoundFile decide
1014 return handleFoundFile(ff, head);
1018 int iterateLine(string const token, regex const reg, string const & closing,
1019 int fragment_pos, DepTable & head)
1022 string::const_iterator first = token.begin();
1023 string::const_iterator end = token.end();
1024 bool fragment = false;
1027 while (regex_search(first, end, what, reg)) {
1028 // if we have a dot, try to handle as file
1029 if (contains(what.str(1), '.')) {
1030 first = what[0].second;
1031 if (what.str(2) == closing) {
1032 handleFoundFile(what.str(1), head);
1033 // since we had a closing bracket,
1034 // do not investigate further
1037 // if we have no closing bracket,
1038 // try to handle as file nevertheless
1039 fragment = !handleFoundFile(
1040 what.str(1) + what.str(2), head);
1042 // if we do not have a dot, check if the line has
1043 // a closing bracket (else, we suspect a line break)
1044 else if (what.str(2) != closing) {
1045 first = what[0].second;
1048 // we have a closing bracket, so the content
1049 // is not a file name.
1050 // no need to investigate further
1051 first = what[0].second;
1054 last_match = what.str(1);
1057 // We need to consider the result from previous line iterations:
1058 // We might not find a fragment here, but another one might follow
1059 // E.g.: (filename.ext) <filenam
1060 // Vice versa, we consider the search completed if a real match
1061 // follows a potential fragment from a previous iteration.
1062 // E.g. <some text we considered a fragment (filename.ext)
1063 // result = -1 means we did not find a fragment!
1065 int last_match_pos = -1;
1066 if (!last_match.empty() && token.find(last_match) != string::npos)
1067 last_match_pos = int(token.find(last_match));
1069 if (last_match_pos > fragment_pos)
1070 result = last_match_pos;
1072 result = fragment_pos;
1074 if (last_match_pos < fragment_pos)
1075 result = fragment_pos;
1083 void LaTeX::deplog(DepTable & head)
1085 // This function reads the LaTeX log file end extracts all the
1086 // external files used by the LaTeX run. The files are then
1087 // entered into the dependency file.
1089 string const logfile =
1090 onlyFileName(changeExtension(file.absFileName(), ".log"));
1092 static regex const reg1("File: (.+).*");
1093 static regex const reg2("No file (.+)(.).*");
1094 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1095 // If an index should be created, MikTex does not write a line like
1096 // \openout# = 'sample.idx'.
1097 // but instead only a line like this into the log:
1098 // Writing index file sample.idx
1099 static regex const reg4("Writing index file (.+).*");
1100 static regex const regoldnomencl("Writing glossary file (.+).*");
1101 static regex const regnomencl("Writing nomenclature file (.+).*");
1102 // If a toc should be created, MikTex does not write a line like
1103 // \openout# = `sample.toc'.
1104 // but only a line like this into the log:
1106 // This line is also written by tetex.
1107 // This line is not present if no toc should be created.
1108 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1109 // file names can be enclosed in <...> (anywhere on the line)
1110 static regex const reg5(".*<[^>]+.*");
1111 // and also (...) anywhere on the line
1112 static regex const reg6(".*\\([^)]+.*");
1114 FileName const fn = makeAbsPath(logfile);
1115 ifstream ifs(fn.toFilesystemEncoding().c_str());
1118 // Ok, the scanning of files here is not sufficient.
1119 // Sometimes files are named by "File: xxx" only
1120 // Therefore we use some regexps to find files instead.
1121 // Note: all file names and paths might contains spaces.
1122 // Also, file names might be broken across lines. Therefore
1123 // we mark (potential) fragments and merge those lines.
1124 bool fragment = false;
1126 getline(ifs, token);
1127 // MikTeX sometimes inserts \0 in the log file. They can't be
1128 // removed directly with the existing string utility
1129 // functions, so convert them first to \r, and remove all
1130 // \r's afterwards, since we need to remove them anyway.
1131 token = subst(token, '\0', '\r');
1132 token = subst(token, "\r", "");
1133 if (token.empty() || token == ")") {
1134 lastline = string();
1138 // FIXME UNICODE: We assume that the file names in the log
1139 // file are in the file system encoding.
1140 token = to_utf8(from_filesystem8bit(token));
1142 // Sometimes, filenames are broken across lines.
1143 // We care for that and save suspicious lines.
1144 // Here we exclude some cases where we are sure
1145 // that there is no continued filename
1146 if (!lastline.empty()) {
1147 static regex const package_info("Package \\w+ Info: .*");
1148 static regex const package_warning("Package \\w+ Warning: .*");
1149 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1150 || prefixIs(token, "Package:")
1151 || prefixIs(token, "Language:")
1152 || prefixIs(token, "LaTeX Info:")
1153 || prefixIs(token, "LaTeX Font Info:")
1154 || prefixIs(token, "\\openout[")
1155 || prefixIs(token, "))")
1156 || regex_match(token, package_info)
1157 || regex_match(token, package_warning))
1158 lastline = string();
1161 if (!lastline.empty())
1162 // probably a continued filename from last line
1163 token = lastline + token;
1164 if (token.length() > 255) {
1165 // string too long. Cut off.
1166 token.erase(0, token.length() - 251);
1171 // (1) "File: file.ext"
1172 if (regex_match(token, sub, reg1)) {
1173 // is this a fragmental file name?
1174 fragment = !completeFilename(sub.str(1), head);
1176 if (suffixIs(token, ")"))
1177 // no fragment for sure
1179 // (2) "No file file.ext"
1180 } else if (regex_match(token, sub, reg2)) {
1181 // file names must contains a dot, line ends with dot
1182 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1183 fragment = !handleFoundFile(sub.str(1), head);
1185 // we suspect a line break
1187 // (3) "\openout<nr> = `file.ext'."
1188 } else if (regex_match(token, sub, reg3)) {
1189 // search for closing '. at the end of the line
1190 if (sub.str(2) == "\'.")
1191 fragment = !handleFoundFile(sub.str(1), head);
1193 // potential fragment
1195 // (4) "Writing index file file.ext"
1196 } else if (regex_match(token, sub, reg4))
1197 // fragmential file name?
1198 fragment = !completeFilename(sub.str(1), head);
1199 // (5) "Writing nomenclature file file.ext"
1200 else if (regex_match(token, sub, regnomencl) ||
1201 regex_match(token, sub, regoldnomencl))
1202 // fragmental file name?
1203 fragment= !completeFilename(sub.str(1), head);
1204 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1205 else if (regex_match(token, sub, miktexTocReg))
1206 fragment = !handleFoundFile(onlyFileName(changeExtension(
1207 file.absFileName(), ".toc")), head);
1209 // not found, but we won't check further
1212 int fragment_pos = -1;
1214 // We can have several of these on one line
1215 // (and in addition to those above)
1216 if (regex_match(token, sub, reg5)) {
1217 // search for strings in <...>
1218 static regex reg5_1("<([^>]+)(.)");
1219 fragment_pos = iterateLine(token, reg5_1, ">",
1220 fragment_pos, head);
1221 fragment = (fragment_pos != -1);
1225 // We can have several of these on one line
1226 // this must be queried separated, because of
1227 // cases such as "File: file.ext (type eps)"
1228 // where "File: file.ext" would be skipped
1229 if (regex_match(token, sub, reg6)) {
1230 // search for strings in (...)
1231 static regex reg6_1("\\(([^()]+)(.)");
1232 fragment_pos = iterateLine(token, reg6_1, ")",
1233 fragment_pos, head);
1234 fragment = (fragment_pos != -1);
1238 // probable linebreak within file name:
1242 // no linebreak: reset
1243 lastline = string();
1246 // Make sure that the main .tex file is in the dependency file.
1247 head.insert(file, true);
1251 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1253 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1254 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1256 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1258 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1259 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1260 static regex const bibtexError2("^(.*---while reading file).*$");
1261 static regex const bibtexError3("(A bad cross reference---).*");
1262 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1263 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1264 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1265 int retval = NO_ERRORS;
1268 while (getline(ifs, token)) {
1269 token = rtrim(token, "\r");
1271 // FIXME UNICODE: We assume that citation keys and filenames
1272 // in the aux file are in the file system encoding.
1273 token = to_utf8(from_filesystem8bit(token));
1274 if (regex_match(token, sub, reg1)) {
1275 string data = sub.str(3);
1276 if (!data.empty()) {
1277 LYXERR(Debug::LATEX, "Found bib file: " << data);
1278 handleFoundFile(data, dep);
1281 else if (regex_match(token, sub, bibtexError)
1282 || regex_match(token, sub, bibtexError2)
1283 || regex_match(token, sub, bibtexError4)
1284 || regex_match(token, sub, bibtexError5)) {
1285 retval |= BIBTEX_ERROR;
1286 string errstr = N_("BibTeX error: ") + token;
1288 if ((prefixIs(token, "while executing---line")
1289 || prefixIs(token, "---line ")
1290 || prefixIs(token, "*Please notify the BibTeX"))
1291 && !prevtoken.empty()) {
1292 errstr = N_("BibTeX error: ") + prevtoken;
1293 message = prevtoken + '\n';
1297 from_local8bit(errstr),
1298 from_local8bit(message));
1299 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1300 retval |= BIBTEX_ERROR;
1301 string errstr = N_("BibTeX error: ") + prevtoken;
1302 string message = prevtoken + '\n' + token;
1304 from_local8bit(errstr),
1305 from_local8bit(message));
1306 } else if (regex_match(token, sub, biberError)) {
1307 retval |= BIBTEX_ERROR;
1308 string errstr = N_("Biber error: ") + sub.str(2);
1309 string message = token;
1311 from_local8bit(errstr),
1312 from_local8bit(message));