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 // Note that we do not always call this function when there is an error.
114 // For example, if there is an error but an output file is produced we
115 // still would like to output (export/view) the file.
117 // What files do we have to delete?
119 // This will at least make latex do all the runs
120 depfile.removeFile();
122 // but the reason for the error might be in a generated file...
125 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
129 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
133 FileName const ind(changeExtension(file.absFileName(), ".ind"));
137 FileName const nls(changeExtension(file.absFileName(), ".nls"));
140 // nomencl file (old version of the package)
141 FileName const gls(changeExtension(file.absFileName(), ".gls"));
144 // Also remove the aux file
145 FileName const aux(changeExtension(file.absFileName(), ".aux"));
148 // Remove the output file, which is often generated even if error
149 output_file.removeFile();
153 int LaTeX::run(TeXErrors & terr)
154 // We know that this function will only be run if the lyx buffer
155 // has been changed. We also know that a newly written .tex file
156 // is always different from the previous one because of the date
157 // in it. However it seems safe to run latex (at least) one time
158 // each time the .tex file changes.
160 int scanres = NO_ERRORS;
161 unsigned int count = 0; // number of times run
162 num_errors = 0; // just to make sure.
163 unsigned int const MAX_RUN = 6;
164 DepTable head; // empty head
165 bool rerun = false; // rerun requested
167 // The class LaTeX does not know the temp path.
168 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
171 // Never write the depfile if an error was encountered.
174 // first check if the file dependencies exist:
175 // ->If it does exist
176 // check if any of the files mentioned in it have
177 // changed (done using a checksum).
179 // run latex once and
180 // remake the dependency file
181 // -> if not changed:
182 // just return there is nothing to do for us.
183 // ->if it doesn't exist
185 // run latex once (we need to run latex once anyway) and
186 // remake the dependency file.
189 bool had_depfile = depfile.exists();
190 bool run_bibtex = false;
191 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
194 LYXERR(Debug::DEPEND, "Dependency file exists");
195 // Read the dep file:
196 had_depfile = head.read(depfile);
200 // Update the checksums
202 // Can't just check if anything has changed because it might
203 // have aborted on error last time... in which cas we need
204 // to re-run latex and collect the error messages
205 // (even if they are the same).
206 if (!output_file.exists()) {
207 LYXERR(Debug::DEPEND,
208 "re-running LaTeX because output file doesn't exist.");
209 } else if (!head.sumchange()) {
210 LYXERR(Debug::DEPEND, "return no_change");
213 LYXERR(Debug::DEPEND, "Dependency file has changed");
216 if (head.extchanged(".bib") || head.extchanged(".bst"))
219 LYXERR(Debug::DEPEND,
220 "Dependency file does not exist, or has wrong format");
222 /// We scan the aux file even when had_depfile = false,
223 /// because we can run pdflatex on the file after running latex on it,
224 /// in which case we will not need to run bibtex again.
225 vector<AuxInfo> bibtex_info_old;
227 bibtex_info_old = scanAuxFiles(aux_file);
230 LYXERR(Debug::LATEX, "Run #" << count);
231 message(runMessage(count));
233 int const exit_code = startscript();
235 scanres = scanLogFile(terr);
236 if (scanres & ERROR_RERUN) {
237 LYXERR(Debug::LATEX, "Rerunning LaTeX");
239 scanres = scanLogFile(terr);
242 if (scanres & ERRORS) {
243 // We no longer run deleteFilesOnError() here
244 // because we now show a resulting PDF even if
245 // there was an error.
246 return scanres; // return on error
249 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
250 if (!run_bibtex && bibtex_info_old != bibtex_info)
253 // update the dependencies.
254 deplog(head); // reads the latex log
258 // At this point we must run external programs if needed.
259 // makeindex will be run if a .idx file changed or was generated.
260 // And if there were undefined citations or changes in references
261 // the .aux file is checked for signs of bibtex. Bibtex is then run
264 // memoir (at least) writes an empty *idx file in the first place.
265 // A second latex run is needed.
266 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
267 rerun = idxfile.exists() && idxfile.isFileEmpty();
270 if (head.haschanged(idxfile)) {
272 LYXERR(Debug::LATEX, "Running MakeIndex.");
273 message(_("Running Index Processor."));
274 // onlyFileName() is needed for cygwin
275 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
278 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
279 // If all nomencl entries are removed, nomencl writes an empty nlo file.
280 // DepTable::hasChanged() returns false in this case, since it does not
281 // distinguish empty files from non-existing files. This is why we need
282 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
283 // FIXME: Sort out the real problem in DepTable.
284 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
285 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
286 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
287 if (head.haschanged(glofile))
288 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
290 // check if we're using biber instead of bibtex
291 // biber writes no info to the aux file, so we just check
292 // if a bcf file exists (and if it was updated)
293 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
294 biber |= head.exist(bcffile);
297 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
298 if (scanres & UNDEF_CIT || run_bibtex) {
299 // Here we must scan the .aux file and look for
300 // "\bibdata" and/or "\bibstyle". If one of those
301 // tags is found -> run bibtex and set rerun = true;
303 LYXERR(Debug::LATEX, "Running BibTeX.");
304 message(_("Running BibTeX."));
305 updateBibtexDependencies(head, bibtex_info);
306 rerun |= runBibTeX(bibtex_info, runparams);
307 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
308 if (blgfile.exists()) {
309 int bscanres = scanBlgFile(head, terr);
310 if (bscanres & ERRORS) {
311 deleteFilesOnError();
312 return bscanres; // return on error
315 } else if (!had_depfile) {
316 /// If we run pdflatex on the file after running latex on it,
317 /// then we do not need to run bibtex, but we do need to
318 /// insert the .bib and .bst files into the .dep-pdf file.
319 updateBibtexDependencies(head, bibtex_info);
323 // we know on this point that latex has been run once (or we just
324 // returned) and the question now is to decide if we need to run
325 // it any more. This is done by asking if any of the files in the
326 // dependency file has changed. (remember that the checksum for
327 // a given file is reported to have changed if it just was created)
328 // -> if changed or rerun == true:
329 // run latex once more and
330 // update the dependency structure
331 // -> if not changed:
332 // we do nothing at this point
334 if (rerun || head.sumchange()) {
337 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
338 LYXERR(Debug::LATEX, "Run #" << count);
339 message(runMessage(count));
341 scanres = scanLogFile(terr);
342 if (scanres & ERRORS) {
343 deleteFilesOnError();
344 return scanres; // return on error
347 // update the depedencies
348 deplog(head); // reads the latex log
351 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
356 // Complex bibliography packages such as Biblatex require
357 // an additional bibtex cycle sometimes.
358 if (scanres & UNDEF_CIT) {
359 // Here we must scan the .aux file and look for
360 // "\bibdata" and/or "\bibstyle". If one of those
361 // tags is found -> run bibtex and set rerun = true;
363 LYXERR(Debug::LATEX, "Running BibTeX.");
364 message(_("Running BibTeX."));
365 updateBibtexDependencies(head, bibtex_info);
366 rerun |= runBibTeX(bibtex_info, runparams);
367 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
368 if (blgfile.exists()) {
369 int bscanres = scanBlgFile(head, terr);
370 if (bscanres & ERRORS) {
371 deleteFilesOnError();
372 return bscanres; // return on error
378 // The inclusion of files generated by external programs such as
379 // makeindex or bibtex might have done changes to pagenumbering,
380 // etc. And because of this we must run the external programs
381 // again to make sure everything is redone correctly.
382 // Also there should be no need to run the external programs any
385 // run makeindex if the <file>.idx has changed or was generated.
386 if (head.haschanged(idxfile)) {
388 LYXERR(Debug::LATEX, "Running MakeIndex.");
389 message(_("Running Index Processor."));
390 // onlyFileName() is needed for cygwin
391 rerun = runMakeIndex(onlyFileName(changeExtension(
392 file.absFileName(), ".idx")), runparams);
395 // I am not pretty sure if need this twice.
396 if (head.haschanged(nlofile))
397 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
398 if (head.haschanged(glofile))
399 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
402 // we will only run latex more if the log file asks for it.
403 // or if the sumchange() is true.
404 // -> rerun asked for:
406 // remake the dependency file
407 // goto 2 or return if max runs are reached.
408 // -> rerun not asked for:
409 // just return (fall out of bottom of func)
411 while ((head.sumchange() || rerun || (scanres & RERUN))
412 && count < MAX_RUN) {
413 // Yes rerun until message goes away, or until
414 // MAX_RUNS are reached.
417 LYXERR(Debug::LATEX, "Run #" << count);
418 message(runMessage(count));
420 scanres = scanLogFile(terr);
421 if (scanres & ERRORS) {
422 deleteFilesOnError();
423 return scanres; // return on error
430 // Write the dependencies to file.
433 if (scanres & NO_OUTPUT) {
434 // A previous run could have left a PDF and since
435 // no PDF is created if NO_OUTPUT, we remove any
436 // existing PDF and temporary files so that an
437 // incorrect PDF is not displayed, which could otherwise
438 // happen if View is run again because the checksum will
439 // be the same so any lingering PDF will be viewed.
440 deleteFilesOnError();
444 scanres |= NONZERO_ERROR;
446 LYXERR(Debug::LATEX, "Done.");
451 int LaTeX::startscript()
453 // onlyFileName() is needed for cygwin
454 string tmp = cmd + ' '
455 + quoteName(onlyFileName(file.toFilesystemEncoding()))
456 + " > " + os::nulldev();
458 return one.startscript(Systemcall::Wait, tmp, path);
462 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
463 string const & params)
465 string tmp = runparams.use_japanese ?
466 lyxrc.jindex_command : lyxrc.index_command;
468 if (!runparams.index_command.empty())
469 tmp = runparams.index_command;
472 "idx file has been made, running index processor ("
473 << tmp << ") on file " << f);
475 tmp = subst(tmp, "$$lang", runparams.document_language);
476 if (runparams.use_indices) {
477 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
479 "Multiple indices. Using splitindex command: " << tmp);
485 one.startscript(Systemcall::Wait, tmp, path);
490 bool LaTeX::runMakeIndexNomencl(FileName const & file,
491 string const & nlo, string const & nls)
493 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
494 message(_("Running MakeIndex for nomencl."));
495 string tmp = lyxrc.nomencl_command + ' ';
496 // onlyFileName() is needed for cygwin
497 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
499 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
501 one.startscript(Systemcall::Wait, tmp, path);
506 vector<AuxInfo> const
507 LaTeX::scanAuxFiles(FileName const & file)
509 vector<AuxInfo> result;
511 result.push_back(scanAuxFile(file));
513 string const basename = removeExtension(file.absFileName());
514 for (int i = 1; i < 1000; ++i) {
515 FileName const file2(basename
516 + '.' + convert<string>(i)
520 result.push_back(scanAuxFile(file2));
526 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
529 result.aux_file = file;
530 scanAuxFile(file, result);
535 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
537 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
539 ifstream ifs(file.toFilesystemEncoding().c_str());
541 static regex const reg1("\\\\citation\\{([^}]+)\\}");
542 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
543 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
544 static regex const reg4("\\\\@input\\{([^}]+)\\}");
546 while (getline(ifs, token)) {
547 token = rtrim(token, "\r");
549 // FIXME UNICODE: We assume that citation keys and filenames
550 // in the aux file are in the file system encoding.
551 token = to_utf8(from_filesystem8bit(token));
552 if (regex_match(token, sub, reg1)) {
553 string data = sub.str(1);
554 while (!data.empty()) {
556 data = split(data, citation, ',');
557 LYXERR(Debug::LATEX, "Citation: " << citation);
558 aux_info.citations.insert(citation);
560 } else if (regex_match(token, sub, reg2)) {
561 string data = sub.str(1);
562 // data is now all the bib files separated by ','
563 // get them one by one and pass them to the helper
564 while (!data.empty()) {
566 data = split(data, database, ',');
567 database = changeExtension(database, "bib");
568 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
569 aux_info.databases.insert(database);
571 } else if (regex_match(token, sub, reg3)) {
572 string style = sub.str(1);
573 // token is now the style file
574 // pass it to the helper
575 style = changeExtension(style, "bst");
576 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
577 aux_info.styles.insert(style);
578 } else if (regex_match(token, sub, reg4)) {
579 string const file2 = sub.str(1);
580 scanAuxFile(makeAbsPath(file2), aux_info);
586 void LaTeX::updateBibtexDependencies(DepTable & dep,
587 vector<AuxInfo> const & bibtex_info)
589 // Since a run of Bibtex mandates more latex runs it is ok to
590 // remove all ".bib" and ".bst" files.
591 dep.remove_files_with_extension(".bib");
592 dep.remove_files_with_extension(".bst");
593 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
595 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
596 it != bibtex_info.end(); ++it) {
597 for (set<string>::const_iterator it2 = it->databases.begin();
598 it2 != it->databases.end(); ++it2) {
599 FileName const file = findtexfile(*it2, "bib");
601 dep.insert(file, true);
604 for (set<string>::const_iterator it2 = it->styles.begin();
605 it2 != it->styles.end(); ++it2) {
606 FileName const file = findtexfile(*it2, "bst");
608 dep.insert(file, true);
612 // biber writes nothing into the aux file.
613 // Instead, we have to scan the blg file
616 scanBlgFile(dep, terr);
621 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
622 OutputParams const & runparams)
625 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
626 it != bibtex_info.end(); ++it) {
627 if (!biber && it->databases.empty())
631 string tmp = runparams.use_japanese ?
632 lyxrc.jbibtex_command : lyxrc.bibtex_command;
634 if (!runparams.bibtex_command.empty())
635 tmp = runparams.bibtex_command;
637 // onlyFileName() is needed for cygwin
638 tmp += quoteName(onlyFileName(removeExtension(
639 it->aux_file.absFileName())));
641 one.startscript(Systemcall::Wait, tmp, path);
643 // Return whether bibtex was run
648 int LaTeX::scanLogFile(TeXErrors & terr)
652 int retval = NO_ERRORS;
654 onlyFileName(changeExtension(file.absFileName(), ".log"));
655 LYXERR(Debug::LATEX, "Log file: " << tmp);
656 FileName const fn = FileName(makeAbsPath(tmp));
657 ifstream ifs(fn.toFilesystemEncoding().c_str());
658 bool fle_style = false;
659 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
660 static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
661 // Flag for 'File ended while scanning' message.
662 // We need to wait for subsequent processing.
663 string wait_for_error;
666 stack <pair<string, int> > child;
669 while (getline(ifs, token)) {
670 // MikTeX sometimes inserts \0 in the log file. They can't be
671 // removed directly with the existing string utility
672 // functions, so convert them first to \r, and remove all
673 // \r's afterwards, since we need to remove them anyway.
674 token = subst(token, '\0', '\r');
675 token = subst(token, "\r", "");
678 LYXERR(Debug::LATEX, "Log line: " << token);
683 // Track child documents
684 for (size_t i = 0; i < token.length(); ++i) {
685 if (token[i] == '(') {
687 size_t j = token.find('(', i + 1);
688 size_t len = j == string::npos
689 ? token.substr(i + 1).length()
691 string const substr = token.substr(i + 1, len);
692 if (regex_match(substr, sub, child_file)) {
693 string const name = sub.str(1);
694 child.push(make_pair(name, pnest));
697 } else if (token[i] == ')') {
699 && child.top().second == pnest)
704 child_name = child.empty() ? empty_string() : child.top().first;
706 if (contains(token, "file:line:error style messages enabled"))
709 if (prefixIs(token, "LaTeX Warning:") ||
710 prefixIs(token, "! pdfTeX warning")) {
711 // Here shall we handle different
713 retval |= LATEX_WARNING;
714 LYXERR(Debug::LATEX, "LaTeX Warning.");
715 if (contains(token, "Rerun to get cross-references")) {
717 LYXERR(Debug::LATEX, "We should rerun.");
718 // package clefval needs 2 latex runs before bibtex
719 } else if (contains(token, "Value of")
720 && contains(token, "on page")
721 && contains(token, "undefined")) {
722 retval |= ERROR_RERUN;
723 LYXERR(Debug::LATEX, "Force rerun.");
725 } else if (contains(token, "Etaremune labels have changed")) {
726 retval |= ERROR_RERUN;
727 LYXERR(Debug::LATEX, "Force rerun.");
728 } else if (contains(token, "Citation")
729 && contains(token, "on page")
730 && contains(token, "undefined")) {
732 } else if (contains(token, "Citation")
733 && contains(token, "on input line")
734 && contains(token, "undefined")) {
737 } else if (prefixIs(token, "Package")) {
739 retval |= PACKAGE_WARNING;
740 if (contains(token, "natbib Warning:")) {
742 if (contains(token, "Citation")
743 && contains(token, "on page")
744 && contains(token, "undefined")) {
747 } else if (contains(token, "run BibTeX")) {
749 } else if (contains(token, "run Biber")) {
752 } else if (contains(token, "Rerun LaTeX") ||
753 contains(token, "Please rerun LaTeX") ||
754 contains(token, "Rerun to get")) {
755 // at least longtable.sty and bibtopic.sty
757 LYXERR(Debug::LATEX, "We should rerun.");
760 } else if (prefixIs(token, "LETTRE WARNING:")) {
761 if (contains(token, "veuillez recompiler")) {
763 LYXERR(Debug::LATEX, "We should rerun.");
766 } else if (token[0] == '(') {
767 if (contains(token, "Rerun LaTeX") ||
768 contains(token, "Rerun to get")) {
770 LYXERR(Debug::LATEX, "We should rerun.");
773 } else if (prefixIs(token, "! ")
775 && regex_match(token, sub, file_line_error)
776 && !contains(token, "pdfTeX warning"))) {
777 // Ok, we have something that looks like a TeX Error
778 // but what do we really have.
780 // Just get the error description:
782 if (prefixIs(token, "! "))
783 desc = string(token, 2);
786 if (contains(token, "LaTeX Error:"))
787 retval |= LATEX_ERROR;
789 if (prefixIs(token, "! File ended while scanning")){
790 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
791 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
792 retval |= ERROR_RERUN;
793 LYXERR(Debug::LATEX, "Force rerun.");
795 // bug 6445. At this point its not clear we finish with error.
796 wait_for_error = desc;
801 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
802 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
803 retval |= ERROR_RERUN;
804 LYXERR(Debug::LATEX, "Force rerun.");
807 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
808 retval |= LATEX_ERROR;
811 errstr = wait_for_error;
813 if (!getline(ifs, tmp))
815 tmp = rtrim(tmp, "\r");
816 errstr += "\n" + tmp;
819 } while (!contains(tmp, "(job aborted"));
822 from_local8bit("Emergency stop"),
823 from_local8bit(errstr),
831 if (!getline(ifs, tmp))
833 tmp = rtrim(tmp, "\r");
834 // 15 is somewhat arbitrarily chosen, based on practice.
835 // We used 10 for 14 years and increased it to 15 when we
839 } while (!prefixIs(tmp, "l."));
840 if (prefixIs(tmp, "l.")) {
841 // we have a latex error
844 "Package babel Error: You haven't defined the language")
846 "Package babel Error: You haven't loaded the option")
848 "Package babel Error: Unknown language"))
849 retval |= ERROR_RERUN;
850 // get the line number:
852 sscanf(tmp.c_str(), "l.%d", &line);
853 // get the rest of the message:
854 string errstr(tmp, tmp.find(' '));
857 tmp = rtrim(tmp, "\r");
858 while (!contains(errstr, "l.")
860 && !prefixIs(tmp, "! ")
861 && !contains(tmp, "(job aborted")) {
865 tmp = rtrim(tmp, "\r");
867 LYXERR(Debug::LATEX, "line: " << line << '\n'
868 << "Desc: " << desc << '\n' << "Text: " << errstr);
869 if (line == last_line)
875 if (line_count <= 5) {
877 // We have no idea what the encoding of
879 // It seems that the output from the
880 // latex compiler itself is pure ASCII,
881 // but it can include bits from the
882 // document, so whatever encoding we
883 // assume here it can be wrong.
884 terr.insertError(line,
885 from_local8bit(desc),
886 from_local8bit(errstr),
892 // information messages, TeX warnings and other
893 // warnings we have not caught earlier.
894 if (prefixIs(token, "Overfull ")) {
895 retval |= TEX_WARNING;
896 } else if (prefixIs(token, "Underfull ")) {
897 retval |= TEX_WARNING;
898 } else if (contains(token, "Rerun to get citations")) {
899 // Natbib seems to use this.
901 } else if (contains(token, "No pages of output")) {
902 // A dvi file was not 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),
918 LYXERR(Debug::LATEX, "Log line: " << token);
925 bool insertIfExists(FileName const & absname, DepTable & head)
927 if (absname.exists() && !absname.isDirectory()) {
928 head.insert(absname, true);
935 bool handleFoundFile(string const & ff, DepTable & head)
937 // convert from native os path to unix path
938 string foundfile = os::internal_path(trim(ff));
940 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
942 // Ok now we found a file.
943 // Now we should make sure that this is a file that we can
944 // access through the normal paths.
945 // We will not try any fancy search methods to
948 // (1) foundfile is an
949 // absolute path and should
952 if (FileName::isAbsolute(foundfile)) {
953 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
954 // On initial insert we want to do the update at once
955 // since this file cannot be a file generated by
957 absname.set(foundfile);
958 if (!insertIfExists(absname, head)) {
960 string strippedfile = foundfile;
961 while (contains(strippedfile, " ")) {
962 // files with spaces are often enclosed in quotation
963 // marks; those have to be removed
964 string unquoted = subst(strippedfile, "\"", "");
965 absname.set(unquoted);
966 if (insertIfExists(absname, head))
968 // strip off part after last space and try again
969 string tmp = strippedfile;
970 string const stripoff =
971 rsplit(tmp, strippedfile, ' ');
972 absname.set(strippedfile);
973 if (insertIfExists(absname, head))
979 string onlyfile = onlyFileName(foundfile);
980 absname = makeAbsPath(onlyfile);
983 while (contains(foundfile, ' ')) {
984 if (absname.exists())
988 // files with spaces are often enclosed in quotation
989 // marks; those have to be removed
990 string unquoted = subst(foundfile, "\"", "");
991 absname = makeAbsPath(unquoted);
992 if (absname.exists())
994 // strip off part after last space and try again
996 string const stripoff =
997 rsplit(foundfile, strippedfile, ' ');
998 foundfile = strippedfile;
999 onlyfile = onlyFileName(strippedfile);
1000 absname = makeAbsPath(onlyfile);
1004 // (2) foundfile is in the tmpdir
1005 // insert it into head
1006 if (absname.exists() && !absname.isDirectory()) {
1007 // FIXME: This regex contained glo, but glo is used by the old
1008 // version of nomencl.sty. Do we need to put it back?
1009 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1010 if (regex_match(onlyfile, unwanted)) {
1011 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1012 << " in the dep file");
1013 } else if (suffixIs(onlyfile, ".tex")) {
1014 // This is a tex file generated by LyX
1015 // and latex is not likely to change this
1017 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1018 head.insert(absname, true);
1020 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1021 head.insert(absname);
1025 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1031 bool completeFilename(string const & ff, DepTable & head)
1033 // If we do not find a dot, we suspect
1034 // a fragmental file name
1035 if (!contains(ff, '.'))
1038 // if we have a dot, we let handleFoundFile decide
1039 return handleFoundFile(ff, head);
1043 int iterateLine(string const & token, regex const & reg, string const & closing,
1044 int fragment_pos, DepTable & head)
1047 string::const_iterator first = token.begin();
1048 string::const_iterator end = token.end();
1049 bool fragment = false;
1052 while (regex_search(first, end, what, reg)) {
1053 // if we have a dot, try to handle as file
1054 if (contains(what.str(1), '.')) {
1055 first = what[0].second;
1056 if (what.str(2) == closing) {
1057 handleFoundFile(what.str(1), head);
1058 // since we had a closing bracket,
1059 // do not investigate further
1062 // if we have no closing bracket,
1063 // try to handle as file nevertheless
1064 fragment = !handleFoundFile(
1065 what.str(1) + what.str(2), head);
1067 // if we do not have a dot, check if the line has
1068 // a closing bracket (else, we suspect a line break)
1069 else if (what.str(2) != closing) {
1070 first = what[0].second;
1073 // we have a closing bracket, so the content
1074 // is not a file name.
1075 // no need to investigate further
1076 first = what[0].second;
1079 last_match = what.str(1);
1082 // We need to consider the result from previous line iterations:
1083 // We might not find a fragment here, but another one might follow
1084 // E.g.: (filename.ext) <filenam
1085 // Vice versa, we consider the search completed if a real match
1086 // follows a potential fragment from a previous iteration.
1087 // E.g. <some text we considered a fragment (filename.ext)
1088 // result = -1 means we did not find a fragment!
1090 int last_match_pos = -1;
1091 if (!last_match.empty() && token.find(last_match) != string::npos)
1092 last_match_pos = int(token.find(last_match));
1094 if (last_match_pos > fragment_pos)
1095 result = last_match_pos;
1097 result = fragment_pos;
1099 if (last_match_pos < fragment_pos)
1100 result = fragment_pos;
1108 void LaTeX::deplog(DepTable & head)
1110 // This function reads the LaTeX log file end extracts all the
1111 // external files used by the LaTeX run. The files are then
1112 // entered into the dependency file.
1114 string const logfile =
1115 onlyFileName(changeExtension(file.absFileName(), ".log"));
1117 static regex const reg1("File: (.+).*");
1118 static regex const reg2("No file (.+)(.).*");
1119 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1120 // If an index should be created, MikTex does not write a line like
1121 // \openout# = 'sample.idx'.
1122 // but instead only a line like this into the log:
1123 // Writing index file sample.idx
1124 static regex const reg4("Writing index file (.+).*");
1125 static regex const regoldnomencl("Writing glossary file (.+).*");
1126 static regex const regnomencl("Writing nomenclature file (.+).*");
1127 // If a toc should be created, MikTex does not write a line like
1128 // \openout# = `sample.toc'.
1129 // but only a line like this into the log:
1131 // This line is also written by tetex.
1132 // This line is not present if no toc should be created.
1133 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1134 // file names can be enclosed in <...> (anywhere on the line)
1135 static regex const reg5(".*<[^>]+.*");
1136 // and also (...) anywhere on the line
1137 static regex const reg6(".*\\([^)]+.*");
1139 FileName const fn = makeAbsPath(logfile);
1140 ifstream ifs(fn.toFilesystemEncoding().c_str());
1143 // Ok, the scanning of files here is not sufficient.
1144 // Sometimes files are named by "File: xxx" only
1145 // Therefore we use some regexps to find files instead.
1146 // Note: all file names and paths might contains spaces.
1147 // Also, file names might be broken across lines. Therefore
1148 // we mark (potential) fragments and merge those lines.
1149 bool fragment = false;
1151 getline(ifs, token);
1152 // MikTeX sometimes inserts \0 in the log file. They can't be
1153 // removed directly with the existing string utility
1154 // functions, so convert them first to \r, and remove all
1155 // \r's afterwards, since we need to remove them anyway.
1156 token = subst(token, '\0', '\r');
1157 token = subst(token, "\r", "");
1158 if (token.empty() || token == ")") {
1159 lastline = string();
1163 // FIXME UNICODE: We assume that the file names in the log
1164 // file are in the file system encoding.
1165 token = to_utf8(from_filesystem8bit(token));
1167 // Sometimes, filenames are broken across lines.
1168 // We care for that and save suspicious lines.
1169 // Here we exclude some cases where we are sure
1170 // that there is no continued filename
1171 if (!lastline.empty()) {
1172 static regex const package_info("Package \\w+ Info: .*");
1173 static regex const package_warning("Package \\w+ Warning: .*");
1174 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1175 || prefixIs(token, "Package:")
1176 || prefixIs(token, "Language:")
1177 || prefixIs(token, "LaTeX Info:")
1178 || prefixIs(token, "LaTeX Font Info:")
1179 || prefixIs(token, "\\openout[")
1180 || prefixIs(token, "))")
1181 || regex_match(token, package_info)
1182 || regex_match(token, package_warning))
1183 lastline = string();
1186 if (!lastline.empty())
1187 // probably a continued filename from last line
1188 token = lastline + token;
1189 if (token.length() > 255) {
1190 // string too long. Cut off.
1191 token.erase(0, token.length() - 251);
1196 // (1) "File: file.ext"
1197 if (regex_match(token, sub, reg1)) {
1198 // is this a fragmental file name?
1199 fragment = !completeFilename(sub.str(1), head);
1201 if (suffixIs(token, ")"))
1202 // no fragment for sure
1204 // (2) "No file file.ext"
1205 } else if (regex_match(token, sub, reg2)) {
1206 // file names must contains a dot, line ends with dot
1207 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1208 fragment = !handleFoundFile(sub.str(1), head);
1210 // we suspect a line break
1212 // (3) "\openout<nr> = `file.ext'."
1213 } else if (regex_match(token, sub, reg3)) {
1214 // search for closing '. at the end of the line
1215 if (sub.str(2) == "\'.")
1216 fragment = !handleFoundFile(sub.str(1), head);
1218 // potential fragment
1220 // (4) "Writing index file file.ext"
1221 } else if (regex_match(token, sub, reg4))
1222 // fragmential file name?
1223 fragment = !completeFilename(sub.str(1), head);
1224 // (5) "Writing nomenclature file file.ext"
1225 else if (regex_match(token, sub, regnomencl) ||
1226 regex_match(token, sub, regoldnomencl))
1227 // fragmental file name?
1228 fragment= !completeFilename(sub.str(1), head);
1229 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1230 else if (regex_match(token, sub, miktexTocReg))
1231 fragment = !handleFoundFile(onlyFileName(changeExtension(
1232 file.absFileName(), ".toc")), head);
1234 // not found, but we won't check further
1237 int fragment_pos = -1;
1239 // We can have several of these on one line
1240 // (and in addition to those above)
1241 if (regex_match(token, sub, reg5)) {
1242 // search for strings in <...>
1243 static regex const reg5_1("<([^>]+)(.)");
1244 fragment_pos = iterateLine(token, reg5_1, ">",
1245 fragment_pos, head);
1246 fragment = (fragment_pos != -1);
1250 // We can have several of these on one line
1251 // this must be queried separated, because of
1252 // cases such as "File: file.ext (type eps)"
1253 // where "File: file.ext" would be skipped
1254 if (regex_match(token, sub, reg6)) {
1255 // search for strings in (...)
1256 static regex const reg6_1("\\(([^()]+)(.)");
1257 fragment_pos = iterateLine(token, reg6_1, ")",
1258 fragment_pos, head);
1259 fragment = (fragment_pos != -1);
1263 // probable linebreak within file name:
1267 // no linebreak: reset
1268 lastline = string();
1271 // Make sure that the main .tex file is in the dependency file.
1272 head.insert(file, true);
1276 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1278 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1279 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1281 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1283 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1284 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1285 static regex const bibtexError2("^(.*---while reading file).*$");
1286 static regex const bibtexError3("(A bad cross reference---).*");
1287 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1288 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1289 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1290 int retval = NO_ERRORS;
1293 while (getline(ifs, token)) {
1294 token = rtrim(token, "\r");
1296 // FIXME UNICODE: We assume that citation keys and filenames
1297 // in the aux file are in the file system encoding.
1298 token = to_utf8(from_filesystem8bit(token));
1299 if (regex_match(token, sub, reg1)) {
1300 string data = sub.str(3);
1301 if (!data.empty()) {
1302 LYXERR(Debug::LATEX, "Found bib file: " << data);
1303 handleFoundFile(data, dep);
1306 else if (regex_match(token, sub, bibtexError)
1307 || regex_match(token, sub, bibtexError2)
1308 || regex_match(token, sub, bibtexError4)
1309 || regex_match(token, sub, bibtexError5)) {
1310 retval |= BIBTEX_ERROR;
1311 string errstr = N_("BibTeX error: ") + token;
1313 if ((prefixIs(token, "while executing---line")
1314 || prefixIs(token, "---line ")
1315 || prefixIs(token, "*Please notify the BibTeX"))
1316 && !prevtoken.empty()) {
1317 errstr = N_("BibTeX error: ") + prevtoken;
1318 message = prevtoken + '\n';
1322 from_local8bit(errstr),
1323 from_local8bit(message));
1324 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1325 retval |= BIBTEX_ERROR;
1326 string errstr = N_("BibTeX error: ") + prevtoken;
1327 string message = prevtoken + '\n' + token;
1329 from_local8bit(errstr),
1330 from_local8bit(message));
1331 } else if (regex_match(token, sub, biberError)) {
1332 retval |= BIBTEX_ERROR;
1333 string errstr = N_("Biber error: ") + sub.str(2);
1334 string message = token;
1336 from_local8bit(errstr),
1337 from_local8bit(message));