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 // What files do we have to delete?
115 // This will at least make latex do all the runs
116 depfile.removeFile();
118 // but the reason for the error might be in a generated file...
121 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
125 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
129 FileName const ind(changeExtension(file.absFileName(), ".ind"));
133 FileName const nls(changeExtension(file.absFileName(), ".nls"));
136 // nomencl file (old version of the package)
137 FileName const gls(changeExtension(file.absFileName(), ".gls"));
140 // Also remove the aux file
141 FileName const aux(changeExtension(file.absFileName(), ".aux"));
144 // Remove the output file, which is often generated even if error
145 output_file.removeFile();
149 int LaTeX::run(TeXErrors & terr)
150 // We know that this function will only be run if the lyx buffer
151 // has been changed. We also know that a newly written .tex file
152 // is always different from the previous one because of the date
153 // in it. However it seems safe to run latex (at least) one time
154 // each time the .tex file changes.
156 int scanres = NO_ERRORS;
157 unsigned int count = 0; // number of times run
158 num_errors = 0; // just to make sure.
159 unsigned int const MAX_RUN = 6;
160 DepTable head; // empty head
161 bool rerun = false; // rerun requested
163 // The class LaTeX does not know the temp path.
164 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
167 // Never write the depfile if an error was encountered.
170 // first check if the file dependencies exist:
171 // ->If it does exist
172 // check if any of the files mentioned in it have
173 // changed (done using a checksum).
175 // run latex once and
176 // remake the dependency file
177 // -> if not changed:
178 // just return there is nothing to do for us.
179 // ->if it doesn't exist
181 // run latex once (we need to run latex once anyway) and
182 // remake the dependency file.
185 bool had_depfile = depfile.exists();
186 bool run_bibtex = false;
187 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
190 LYXERR(Debug::DEPEND, "Dependency file exists");
191 // Read the dep file:
192 had_depfile = head.read(depfile);
196 // Update the checksums
198 // Can't just check if anything has changed because it might
199 // have aborted on error last time... in which cas we need
200 // to re-run latex and collect the error messages
201 // (even if they are the same).
202 if (!output_file.exists()) {
203 LYXERR(Debug::DEPEND,
204 "re-running LaTeX because output file doesn't exist.");
205 } else if (!head.sumchange()) {
206 LYXERR(Debug::DEPEND, "return no_change");
209 LYXERR(Debug::DEPEND, "Dependency file has changed");
212 if (head.extchanged(".bib") || head.extchanged(".bst"))
215 LYXERR(Debug::DEPEND,
216 "Dependency file does not exist, or has wrong format");
218 /// We scan the aux file even when had_depfile = false,
219 /// because we can run pdflatex on the file after running latex on it,
220 /// in which case we will not need to run bibtex again.
221 vector<AuxInfo> bibtex_info_old;
223 bibtex_info_old = scanAuxFiles(aux_file);
226 LYXERR(Debug::LATEX, "Run #" << count);
227 message(runMessage(count));
230 scanres = scanLogFile(terr);
231 if (scanres & ERROR_RERUN) {
232 LYXERR(Debug::LATEX, "Rerunning LaTeX");
234 scanres = scanLogFile(terr);
237 if (scanres & ERRORS) {
238 deleteFilesOnError();
239 return scanres; // return on error
242 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
243 if (!run_bibtex && bibtex_info_old != bibtex_info)
246 // update the dependencies.
247 deplog(head); // reads the latex log
251 // At this point we must run external programs if needed.
252 // makeindex will be run if a .idx file changed or was generated.
253 // And if there were undefined citations or changes in references
254 // the .aux file is checked for signs of bibtex. Bibtex is then run
257 // memoir (at least) writes an empty *idx file in the first place.
258 // A second latex run is needed.
259 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
260 rerun = idxfile.exists() && idxfile.isFileEmpty();
263 if (head.haschanged(idxfile)) {
265 LYXERR(Debug::LATEX, "Running MakeIndex.");
266 message(_("Running Index Processor."));
267 // onlyFileName() is needed for cygwin
268 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
271 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
272 // If all nomencl entries are removed, nomencl writes an empty nlo file.
273 // DepTable::hasChanged() returns false in this case, since it does not
274 // distinguish empty files from non-existing files. This is why we need
275 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
276 // FIXME: Sort out the real problem in DepTable.
277 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
278 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
279 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
280 if (head.haschanged(glofile))
281 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
283 // check if we're using biber instead of bibtex
284 // biber writes no info to the aux file, so we just check
285 // if a bcf file exists (and if it was updated)
286 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
287 biber |= head.exist(bcffile);
290 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
291 if (scanres & UNDEF_CIT || run_bibtex) {
292 // Here we must scan the .aux file and look for
293 // "\bibdata" and/or "\bibstyle". If one of those
294 // tags is found -> run bibtex and set rerun = true;
296 LYXERR(Debug::LATEX, "Running BibTeX.");
297 message(_("Running BibTeX."));
298 updateBibtexDependencies(head, bibtex_info);
299 rerun |= runBibTeX(bibtex_info, runparams);
300 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
301 if (blgfile.exists()) {
302 int bscanres = scanBlgFile(head, terr);
303 if (bscanres & ERRORS) {
304 deleteFilesOnError();
305 return bscanres; // return on error
308 } else if (!had_depfile) {
309 /// If we run pdflatex on the file after running latex on it,
310 /// then we do not need to run bibtex, but we do need to
311 /// insert the .bib and .bst files into the .dep-pdf file.
312 updateBibtexDependencies(head, bibtex_info);
316 // we know on this point that latex has been run once (or we just
317 // returned) and the question now is to decide if we need to run
318 // it any more. This is done by asking if any of the files in the
319 // dependency file has changed. (remember that the checksum for
320 // a given file is reported to have changed if it just was created)
321 // -> if changed or rerun == true:
322 // run latex once more and
323 // update the dependency structure
324 // -> if not changed:
325 // we do nothing at this point
327 if (rerun || head.sumchange()) {
330 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
331 LYXERR(Debug::LATEX, "Run #" << count);
332 message(runMessage(count));
334 scanres = scanLogFile(terr);
335 if (scanres & ERRORS) {
336 deleteFilesOnError();
337 return scanres; // return on error
340 // update the depedencies
341 deplog(head); // reads the latex log
344 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
349 // Complex bibliography packages such as Biblatex require
350 // an additional bibtex cycle sometimes.
351 if (scanres & UNDEF_CIT) {
352 // Here we must scan the .aux file and look for
353 // "\bibdata" and/or "\bibstyle". If one of those
354 // tags is found -> run bibtex and set rerun = true;
356 LYXERR(Debug::LATEX, "Running BibTeX.");
357 message(_("Running BibTeX."));
358 updateBibtexDependencies(head, bibtex_info);
359 rerun |= runBibTeX(bibtex_info, runparams);
360 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
361 if (blgfile.exists()) {
362 int bscanres = scanBlgFile(head, terr);
363 if (bscanres & ERRORS) {
364 deleteFilesOnError();
365 return bscanres; // return on error
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);
414 if (scanres & ERRORS) {
415 deleteFilesOnError();
416 return scanres; // return on error
423 // Write the dependencies to file.
425 if (scanres & NO_OUTPUT) {
426 // A previous run could have left a PDF and since
427 // no PDF is created if NO_OUTPUT, we remove any
428 // existing PDF and temporary files so that an
429 // incorrect PDF is not displayed, which could otherwise
430 // happen if View is run again because the checksum will
431 // be the same so any lingering PDF will be viewed.
432 deleteFilesOnError();
434 LYXERR(Debug::LATEX, "Done.");
439 int LaTeX::startscript()
441 // onlyFileName() is needed for cygwin
442 string tmp = cmd + ' '
443 + quoteName(onlyFileName(file.toFilesystemEncoding()))
444 + " > " + os::nulldev();
446 return one.startscript(Systemcall::Wait, tmp, path);
450 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
451 string const & params)
453 string tmp = runparams.use_japanese ?
454 lyxrc.jindex_command : lyxrc.index_command;
456 if (!runparams.index_command.empty())
457 tmp = runparams.index_command;
460 "idx file has been made, running index processor ("
461 << tmp << ") on file " << f);
463 tmp = subst(tmp, "$$lang", runparams.document_language);
464 if (runparams.use_indices) {
465 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
467 "Multiple indices. Using splitindex command: " << tmp);
473 one.startscript(Systemcall::Wait, tmp, path);
478 bool LaTeX::runMakeIndexNomencl(FileName const & file,
479 string const & nlo, string const & nls)
481 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
482 message(_("Running MakeIndex for nomencl."));
483 string tmp = lyxrc.nomencl_command + ' ';
484 // onlyFileName() is needed for cygwin
485 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
487 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
489 one.startscript(Systemcall::Wait, tmp, path);
494 vector<AuxInfo> const
495 LaTeX::scanAuxFiles(FileName const & file)
497 vector<AuxInfo> result;
499 result.push_back(scanAuxFile(file));
501 string const basename = removeExtension(file.absFileName());
502 for (int i = 1; i < 1000; ++i) {
503 FileName const file2(basename
504 + '.' + convert<string>(i)
508 result.push_back(scanAuxFile(file2));
514 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
517 result.aux_file = file;
518 scanAuxFile(file, result);
523 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
525 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
527 ifstream ifs(file.toFilesystemEncoding().c_str());
529 static regex const reg1("\\\\citation\\{([^}]+)\\}");
530 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
531 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
532 static regex const reg4("\\\\@input\\{([^}]+)\\}");
534 while (getline(ifs, token)) {
535 token = rtrim(token, "\r");
537 // FIXME UNICODE: We assume that citation keys and filenames
538 // in the aux file are in the file system encoding.
539 token = to_utf8(from_filesystem8bit(token));
540 if (regex_match(token, sub, reg1)) {
541 string data = sub.str(1);
542 while (!data.empty()) {
544 data = split(data, citation, ',');
545 LYXERR(Debug::LATEX, "Citation: " << citation);
546 aux_info.citations.insert(citation);
548 } else if (regex_match(token, sub, reg2)) {
549 string data = sub.str(1);
550 // data is now all the bib files separated by ','
551 // get them one by one and pass them to the helper
552 while (!data.empty()) {
554 data = split(data, database, ',');
555 database = changeExtension(database, "bib");
556 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
557 aux_info.databases.insert(database);
559 } else if (regex_match(token, sub, reg3)) {
560 string style = sub.str(1);
561 // token is now the style file
562 // pass it to the helper
563 style = changeExtension(style, "bst");
564 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
565 aux_info.styles.insert(style);
566 } else if (regex_match(token, sub, reg4)) {
567 string const file2 = sub.str(1);
568 scanAuxFile(makeAbsPath(file2), aux_info);
574 void LaTeX::updateBibtexDependencies(DepTable & dep,
575 vector<AuxInfo> const & bibtex_info)
577 // Since a run of Bibtex mandates more latex runs it is ok to
578 // remove all ".bib" and ".bst" files.
579 dep.remove_files_with_extension(".bib");
580 dep.remove_files_with_extension(".bst");
581 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
583 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
584 it != bibtex_info.end(); ++it) {
585 for (set<string>::const_iterator it2 = it->databases.begin();
586 it2 != it->databases.end(); ++it2) {
587 FileName const file = findtexfile(*it2, "bib");
589 dep.insert(file, true);
592 for (set<string>::const_iterator it2 = it->styles.begin();
593 it2 != it->styles.end(); ++it2) {
594 FileName const file = findtexfile(*it2, "bst");
596 dep.insert(file, true);
600 // biber writes nothing into the aux file.
601 // Instead, we have to scan the blg file
604 scanBlgFile(dep, terr);
609 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
610 OutputParams const & runparams)
613 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
614 it != bibtex_info.end(); ++it) {
615 if (!biber && it->databases.empty())
619 string tmp = runparams.use_japanese ?
620 lyxrc.jbibtex_command : lyxrc.bibtex_command;
622 if (!runparams.bibtex_command.empty())
623 tmp = runparams.bibtex_command;
625 // onlyFileName() is needed for cygwin
626 tmp += quoteName(onlyFileName(removeExtension(
627 it->aux_file.absFileName())));
629 one.startscript(Systemcall::Wait, tmp, path);
631 // Return whether bibtex was run
636 int LaTeX::scanLogFile(TeXErrors & terr)
640 int retval = NO_ERRORS;
642 onlyFileName(changeExtension(file.absFileName(), ".log"));
643 LYXERR(Debug::LATEX, "Log file: " << tmp);
644 FileName const fn = FileName(makeAbsPath(tmp));
645 ifstream ifs(fn.toFilesystemEncoding().c_str());
646 bool fle_style = false;
647 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
648 static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
649 // Flag for 'File ended while scanning' message.
650 // We need to wait for subsequent processing.
651 string wait_for_error;
654 stack <pair<string, int> > child;
657 while (getline(ifs, token)) {
658 // MikTeX sometimes inserts \0 in the log file. They can't be
659 // removed directly with the existing string utility
660 // functions, so convert them first to \r, and remove all
661 // \r's afterwards, since we need to remove them anyway.
662 token = subst(token, '\0', '\r');
663 token = subst(token, "\r", "");
666 LYXERR(Debug::LATEX, "Log line: " << token);
671 // Track child documents
672 for (size_t i = 0; i < token.length(); ++i) {
673 if (token[i] == '(') {
675 size_t j = token.find('(', i + 1);
676 size_t len = j == string::npos
677 ? token.substr(i + 1).length()
679 string const substr = token.substr(i + 1, len);
680 if (regex_match(substr, sub, child_file)) {
681 string const name = sub.str(1);
682 child.push(make_pair(name, pnest));
685 } else if (token[i] == ')') {
687 && child.top().second == pnest)
692 child_name = child.empty() ? empty_string() : child.top().first;
694 if (contains(token, "file:line:error style messages enabled"))
697 if (prefixIs(token, "LaTeX Warning:") ||
698 prefixIs(token, "! pdfTeX warning")) {
699 // Here shall we handle different
701 retval |= LATEX_WARNING;
702 LYXERR(Debug::LATEX, "LaTeX Warning.");
703 if (contains(token, "Rerun to get cross-references")) {
705 LYXERR(Debug::LATEX, "We should rerun.");
706 // package clefval needs 2 latex runs before bibtex
707 } else if (contains(token, "Value of")
708 && contains(token, "on page")
709 && contains(token, "undefined")) {
710 retval |= ERROR_RERUN;
711 LYXERR(Debug::LATEX, "Force rerun.");
713 } else if (contains(token, "Etaremune labels have changed")) {
714 retval |= ERROR_RERUN;
715 LYXERR(Debug::LATEX, "Force rerun.");
716 } else if (contains(token, "Citation")
717 && contains(token, "on page")
718 && contains(token, "undefined")) {
720 } else if (contains(token, "Citation")
721 && contains(token, "on input line")
722 && contains(token, "undefined")) {
725 } else if (prefixIs(token, "Package")) {
727 retval |= PACKAGE_WARNING;
728 if (contains(token, "natbib Warning:")) {
730 if (contains(token, "Citation")
731 && contains(token, "on page")
732 && contains(token, "undefined")) {
735 } else if (contains(token, "run BibTeX")) {
737 } else if (contains(token, "run Biber")) {
740 } else if (contains(token, "Rerun LaTeX") ||
741 contains(token, "Please rerun LaTeX") ||
742 contains(token, "Rerun to get")) {
743 // at least longtable.sty and bibtopic.sty
745 LYXERR(Debug::LATEX, "We should rerun.");
748 } else if (prefixIs(token, "LETTRE WARNING:")) {
749 if (contains(token, "veuillez recompiler")) {
751 LYXERR(Debug::LATEX, "We should rerun.");
754 } else if (token[0] == '(') {
755 if (contains(token, "Rerun LaTeX") ||
756 contains(token, "Rerun to get")) {
758 LYXERR(Debug::LATEX, "We should rerun.");
761 } else if (prefixIs(token, "! ")
763 && regex_match(token, sub, file_line_error)
764 && !contains(token, "pdfTeX warning"))) {
765 // Ok, we have something that looks like a TeX Error
766 // but what do we really have.
768 // Just get the error description:
770 if (prefixIs(token, "! "))
771 desc = string(token, 2);
774 if (contains(token, "LaTeX Error:"))
775 retval |= LATEX_ERROR;
777 if (prefixIs(token, "! File ended while scanning")){
778 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
779 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
780 retval |= ERROR_RERUN;
781 LYXERR(Debug::LATEX, "Force rerun.");
783 // bug 6445. At this point its not clear we finish with error.
784 wait_for_error = desc;
789 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
790 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
791 retval |= ERROR_RERUN;
792 LYXERR(Debug::LATEX, "Force rerun.");
795 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
796 retval |= LATEX_ERROR;
799 errstr = wait_for_error;
801 if (!getline(ifs, tmp))
803 tmp = rtrim(tmp, "\r");
804 errstr += "\n" + tmp;
807 } while (!contains(tmp, "(job aborted"));
810 from_local8bit("Emergency stop"),
811 from_local8bit(errstr),
819 if (!getline(ifs, tmp))
821 tmp = rtrim(tmp, "\r");
824 } while (!prefixIs(tmp, "l."));
825 if (prefixIs(tmp, "l.")) {
826 // we have a latex error
829 "Package babel Error: You haven't defined the language")
831 "Package babel Error: You haven't loaded the option")
833 "Package babel Error: Unknown language"))
834 retval |= ERROR_RERUN;
835 // get the line number:
837 sscanf(tmp.c_str(), "l.%d", &line);
838 // get the rest of the message:
839 string errstr(tmp, tmp.find(' '));
842 tmp = rtrim(tmp, "\r");
843 while (!contains(errstr, "l.")
845 && !prefixIs(tmp, "! ")
846 && !contains(tmp, "(job aborted")) {
850 tmp = rtrim(tmp, "\r");
852 LYXERR(Debug::LATEX, "line: " << line << '\n'
853 << "Desc: " << desc << '\n' << "Text: " << errstr);
854 if (line == last_line)
860 if (line_count <= 5) {
862 // We have no idea what the encoding of
864 // It seems that the output from the
865 // latex compiler itself is pure ASCII,
866 // but it can include bits from the
867 // document, so whatever encoding we
868 // assume here it can be wrong.
869 terr.insertError(line,
870 from_local8bit(desc),
871 from_local8bit(errstr),
877 // information messages, TeX warnings and other
878 // warnings we have not caught earlier.
879 if (prefixIs(token, "Overfull ")) {
880 retval |= TEX_WARNING;
881 } else if (prefixIs(token, "Underfull ")) {
882 retval |= TEX_WARNING;
883 } else if (contains(token, "Rerun to get citations")) {
884 // Natbib seems to use this.
886 } else if (contains(token, "No pages of output")) {
887 // A dvi file was not created
889 } else if (contains(token, "That makes 100 errors")) {
890 // More than 100 errors were reprted
891 retval |= TOO_MANY_ERRORS;
892 } else if (prefixIs(token, "!pdfTeX error:")){
893 // otherwise we dont catch e.g.:
894 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
897 from_local8bit("pdfTeX Error"),
898 from_local8bit(token),
903 LYXERR(Debug::LATEX, "Log line: " << token);
910 bool insertIfExists(FileName const & absname, DepTable & head)
912 if (absname.exists() && !absname.isDirectory()) {
913 head.insert(absname, true);
920 bool handleFoundFile(string const & ff, DepTable & head)
922 // convert from native os path to unix path
923 string foundfile = os::internal_path(trim(ff));
925 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
927 // Ok now we found a file.
928 // Now we should make sure that this is a file that we can
929 // access through the normal paths.
930 // We will not try any fancy search methods to
933 // (1) foundfile is an
934 // absolute path and should
937 if (FileName::isAbsolute(foundfile)) {
938 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
939 // On initial insert we want to do the update at once
940 // since this file cannot be a file generated by
942 absname.set(foundfile);
943 if (!insertIfExists(absname, head)) {
945 string strippedfile = foundfile;
946 while (contains(strippedfile, " ")) {
947 // files with spaces are often enclosed in quotation
948 // marks; those have to be removed
949 string unquoted = subst(strippedfile, "\"", "");
950 absname.set(unquoted);
951 if (insertIfExists(absname, head))
953 // strip off part after last space and try again
954 string tmp = strippedfile;
955 string const stripoff =
956 rsplit(tmp, strippedfile, ' ');
957 absname.set(strippedfile);
958 if (insertIfExists(absname, head))
964 string onlyfile = onlyFileName(foundfile);
965 absname = makeAbsPath(onlyfile);
968 while (contains(foundfile, ' ')) {
969 if (absname.exists())
973 // files with spaces are often enclosed in quotation
974 // marks; those have to be removed
975 string unquoted = subst(foundfile, "\"", "");
976 absname = makeAbsPath(unquoted);
977 if (absname.exists())
979 // strip off part after last space and try again
981 string const stripoff =
982 rsplit(foundfile, strippedfile, ' ');
983 foundfile = strippedfile;
984 onlyfile = onlyFileName(strippedfile);
985 absname = makeAbsPath(onlyfile);
989 // (2) foundfile is in the tmpdir
990 // insert it into head
991 if (absname.exists() && !absname.isDirectory()) {
992 // FIXME: This regex contained glo, but glo is used by the old
993 // version of nomencl.sty. Do we need to put it back?
994 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
995 if (regex_match(onlyfile, unwanted)) {
996 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
997 << " in the dep file");
998 } else if (suffixIs(onlyfile, ".tex")) {
999 // This is a tex file generated by LyX
1000 // and latex is not likely to change this
1002 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1003 head.insert(absname, true);
1005 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1006 head.insert(absname);
1010 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1016 bool completeFilename(string const & ff, DepTable & head)
1018 // If we do not find a dot, we suspect
1019 // a fragmental file name
1020 if (!contains(ff, '.'))
1023 // if we have a dot, we let handleFoundFile decide
1024 return handleFoundFile(ff, head);
1028 int iterateLine(string const & token, regex const & reg, string const & closing,
1029 int fragment_pos, DepTable & head)
1032 string::const_iterator first = token.begin();
1033 string::const_iterator end = token.end();
1034 bool fragment = false;
1037 while (regex_search(first, end, what, reg)) {
1038 // if we have a dot, try to handle as file
1039 if (contains(what.str(1), '.')) {
1040 first = what[0].second;
1041 if (what.str(2) == closing) {
1042 handleFoundFile(what.str(1), head);
1043 // since we had a closing bracket,
1044 // do not investigate further
1047 // if we have no closing bracket,
1048 // try to handle as file nevertheless
1049 fragment = !handleFoundFile(
1050 what.str(1) + what.str(2), head);
1052 // if we do not have a dot, check if the line has
1053 // a closing bracket (else, we suspect a line break)
1054 else if (what.str(2) != closing) {
1055 first = what[0].second;
1058 // we have a closing bracket, so the content
1059 // is not a file name.
1060 // no need to investigate further
1061 first = what[0].second;
1064 last_match = what.str(1);
1067 // We need to consider the result from previous line iterations:
1068 // We might not find a fragment here, but another one might follow
1069 // E.g.: (filename.ext) <filenam
1070 // Vice versa, we consider the search completed if a real match
1071 // follows a potential fragment from a previous iteration.
1072 // E.g. <some text we considered a fragment (filename.ext)
1073 // result = -1 means we did not find a fragment!
1075 int last_match_pos = -1;
1076 if (!last_match.empty() && token.find(last_match) != string::npos)
1077 last_match_pos = int(token.find(last_match));
1079 if (last_match_pos > fragment_pos)
1080 result = last_match_pos;
1082 result = fragment_pos;
1084 if (last_match_pos < fragment_pos)
1085 result = fragment_pos;
1093 void LaTeX::deplog(DepTable & head)
1095 // This function reads the LaTeX log file end extracts all the
1096 // external files used by the LaTeX run. The files are then
1097 // entered into the dependency file.
1099 string const logfile =
1100 onlyFileName(changeExtension(file.absFileName(), ".log"));
1102 static regex const reg1("File: (.+).*");
1103 static regex const reg2("No file (.+)(.).*");
1104 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1105 // If an index should be created, MikTex does not write a line like
1106 // \openout# = 'sample.idx'.
1107 // but instead only a line like this into the log:
1108 // Writing index file sample.idx
1109 static regex const reg4("Writing index file (.+).*");
1110 static regex const regoldnomencl("Writing glossary file (.+).*");
1111 static regex const regnomencl("Writing nomenclature file (.+).*");
1112 // If a toc should be created, MikTex does not write a line like
1113 // \openout# = `sample.toc'.
1114 // but only a line like this into the log:
1116 // This line is also written by tetex.
1117 // This line is not present if no toc should be created.
1118 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1119 // file names can be enclosed in <...> (anywhere on the line)
1120 static regex const reg5(".*<[^>]+.*");
1121 // and also (...) anywhere on the line
1122 static regex const reg6(".*\\([^)]+.*");
1124 FileName const fn = makeAbsPath(logfile);
1125 ifstream ifs(fn.toFilesystemEncoding().c_str());
1128 // Ok, the scanning of files here is not sufficient.
1129 // Sometimes files are named by "File: xxx" only
1130 // Therefore we use some regexps to find files instead.
1131 // Note: all file names and paths might contains spaces.
1132 // Also, file names might be broken across lines. Therefore
1133 // we mark (potential) fragments and merge those lines.
1134 bool fragment = false;
1136 getline(ifs, token);
1137 // MikTeX sometimes inserts \0 in the log file. They can't be
1138 // removed directly with the existing string utility
1139 // functions, so convert them first to \r, and remove all
1140 // \r's afterwards, since we need to remove them anyway.
1141 token = subst(token, '\0', '\r');
1142 token = subst(token, "\r", "");
1143 if (token.empty() || token == ")") {
1144 lastline = string();
1148 // FIXME UNICODE: We assume that the file names in the log
1149 // file are in the file system encoding.
1150 token = to_utf8(from_filesystem8bit(token));
1152 // Sometimes, filenames are broken across lines.
1153 // We care for that and save suspicious lines.
1154 // Here we exclude some cases where we are sure
1155 // that there is no continued filename
1156 if (!lastline.empty()) {
1157 static regex const package_info("Package \\w+ Info: .*");
1158 static regex const package_warning("Package \\w+ Warning: .*");
1159 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1160 || prefixIs(token, "Package:")
1161 || prefixIs(token, "Language:")
1162 || prefixIs(token, "LaTeX Info:")
1163 || prefixIs(token, "LaTeX Font Info:")
1164 || prefixIs(token, "\\openout[")
1165 || prefixIs(token, "))")
1166 || regex_match(token, package_info)
1167 || regex_match(token, package_warning))
1168 lastline = string();
1171 if (!lastline.empty())
1172 // probably a continued filename from last line
1173 token = lastline + token;
1174 if (token.length() > 255) {
1175 // string too long. Cut off.
1176 token.erase(0, token.length() - 251);
1181 // (1) "File: file.ext"
1182 if (regex_match(token, sub, reg1)) {
1183 // is this a fragmental file name?
1184 fragment = !completeFilename(sub.str(1), head);
1186 if (suffixIs(token, ")"))
1187 // no fragment for sure
1189 // (2) "No file file.ext"
1190 } else if (regex_match(token, sub, reg2)) {
1191 // file names must contains a dot, line ends with dot
1192 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1193 fragment = !handleFoundFile(sub.str(1), head);
1195 // we suspect a line break
1197 // (3) "\openout<nr> = `file.ext'."
1198 } else if (regex_match(token, sub, reg3)) {
1199 // search for closing '. at the end of the line
1200 if (sub.str(2) == "\'.")
1201 fragment = !handleFoundFile(sub.str(1), head);
1203 // potential fragment
1205 // (4) "Writing index file file.ext"
1206 } else if (regex_match(token, sub, reg4))
1207 // fragmential file name?
1208 fragment = !completeFilename(sub.str(1), head);
1209 // (5) "Writing nomenclature file file.ext"
1210 else if (regex_match(token, sub, regnomencl) ||
1211 regex_match(token, sub, regoldnomencl))
1212 // fragmental file name?
1213 fragment= !completeFilename(sub.str(1), head);
1214 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1215 else if (regex_match(token, sub, miktexTocReg))
1216 fragment = !handleFoundFile(onlyFileName(changeExtension(
1217 file.absFileName(), ".toc")), head);
1219 // not found, but we won't check further
1222 int fragment_pos = -1;
1224 // We can have several of these on one line
1225 // (and in addition to those above)
1226 if (regex_match(token, sub, reg5)) {
1227 // search for strings in <...>
1228 static regex const reg5_1("<([^>]+)(.)");
1229 fragment_pos = iterateLine(token, reg5_1, ">",
1230 fragment_pos, head);
1231 fragment = (fragment_pos != -1);
1235 // We can have several of these on one line
1236 // this must be queried separated, because of
1237 // cases such as "File: file.ext (type eps)"
1238 // where "File: file.ext" would be skipped
1239 if (regex_match(token, sub, reg6)) {
1240 // search for strings in (...)
1241 static regex const reg6_1("\\(([^()]+)(.)");
1242 fragment_pos = iterateLine(token, reg6_1, ")",
1243 fragment_pos, head);
1244 fragment = (fragment_pos != -1);
1248 // probable linebreak within file name:
1252 // no linebreak: reset
1253 lastline = string();
1256 // Make sure that the main .tex file is in the dependency file.
1257 head.insert(file, true);
1261 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1263 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1264 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1266 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1268 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1269 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1270 static regex const bibtexError2("^(.*---while reading file).*$");
1271 static regex const bibtexError3("(A bad cross reference---).*");
1272 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1273 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1274 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1275 int retval = NO_ERRORS;
1278 while (getline(ifs, token)) {
1279 token = rtrim(token, "\r");
1281 // FIXME UNICODE: We assume that citation keys and filenames
1282 // in the aux file are in the file system encoding.
1283 token = to_utf8(from_filesystem8bit(token));
1284 if (regex_match(token, sub, reg1)) {
1285 string data = sub.str(3);
1286 if (!data.empty()) {
1287 LYXERR(Debug::LATEX, "Found bib file: " << data);
1288 handleFoundFile(data, dep);
1291 else if (regex_match(token, sub, bibtexError)
1292 || regex_match(token, sub, bibtexError2)
1293 || regex_match(token, sub, bibtexError4)
1294 || regex_match(token, sub, bibtexError5)) {
1295 retval |= BIBTEX_ERROR;
1296 string errstr = N_("BibTeX error: ") + token;
1298 if ((prefixIs(token, "while executing---line")
1299 || prefixIs(token, "---line ")
1300 || prefixIs(token, "*Please notify the BibTeX"))
1301 && !prevtoken.empty()) {
1302 errstr = N_("BibTeX error: ") + prevtoken;
1303 message = prevtoken + '\n';
1307 from_local8bit(errstr),
1308 from_local8bit(message));
1309 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1310 retval |= BIBTEX_ERROR;
1311 string errstr = N_("BibTeX error: ") + prevtoken;
1312 string message = prevtoken + '\n' + token;
1314 from_local8bit(errstr),
1315 from_local8bit(message));
1316 } else if (regex_match(token, sub, biberError)) {
1317 retval |= BIBTEX_ERROR;
1318 string errstr = N_("Biber error: ") + sub.str(2);
1319 string message = token;
1321 from_local8bit(errstr),
1322 from_local8bit(message));