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 (head.haschanged(nlofile))
272 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
273 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
274 if (head.haschanged(glofile))
275 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
277 // check if we're using biber instead of bibtex
278 // biber writes no info to the aux file, so we just check
279 // if a bcf file exists (and if it was updated)
280 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
281 biber |= head.exist(bcffile);
284 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
285 if (scanres & UNDEF_CIT || run_bibtex) {
286 // Here we must scan the .aux file and look for
287 // "\bibdata" and/or "\bibstyle". If one of those
288 // tags is found -> run bibtex and set rerun = true;
290 LYXERR(Debug::LATEX, "Running BibTeX.");
291 message(_("Running BibTeX."));
292 updateBibtexDependencies(head, bibtex_info);
293 rerun |= runBibTeX(bibtex_info, runparams);
294 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
295 if (blgfile.exists()) {
296 int bscanres = scanBlgFile(head, terr);
297 if (bscanres & ERRORS) {
298 deleteFilesOnError();
299 return bscanres; // return on error
302 } else if (!had_depfile) {
303 /// If we run pdflatex on the file after running latex on it,
304 /// then we do not need to run bibtex, but we do need to
305 /// insert the .bib and .bst files into the .dep-pdf file.
306 updateBibtexDependencies(head, bibtex_info);
310 // we know on this point that latex has been run once (or we just
311 // returned) and the question now is to decide if we need to run
312 // it any more. This is done by asking if any of the files in the
313 // dependency file has changed. (remember that the checksum for
314 // a given file is reported to have changed if it just was created)
315 // -> if changed or rerun == true:
316 // run latex once more and
317 // update the dependency structure
318 // -> if not changed:
319 // we do nothing at this point
321 if (rerun || head.sumchange()) {
324 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
325 LYXERR(Debug::LATEX, "Run #" << count);
326 message(runMessage(count));
328 scanres = scanLogFile(terr);
329 if (scanres & ERRORS) {
330 deleteFilesOnError();
331 return scanres; // return on error
334 // update the depedencies
335 deplog(head); // reads the latex log
338 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
343 // Complex bibliography packages such as Biblatex require
344 // an additional bibtex cycle sometimes.
345 if (scanres & UNDEF_CIT) {
346 // Here we must scan the .aux file and look for
347 // "\bibdata" and/or "\bibstyle". If one of those
348 // tags is found -> run bibtex and set rerun = true;
350 LYXERR(Debug::LATEX, "Running BibTeX.");
351 message(_("Running BibTeX."));
352 updateBibtexDependencies(head, bibtex_info);
353 rerun |= runBibTeX(bibtex_info, runparams);
354 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
355 if (blgfile.exists()) {
356 int bscanres = scanBlgFile(head, terr);
357 if (bscanres & ERRORS) {
358 deleteFilesOnError();
359 return bscanres; // return on error
365 // The inclusion of files generated by external programs such as
366 // makeindex or bibtex might have done changes to pagenumbering,
367 // etc. And because of this we must run the external programs
368 // again to make sure everything is redone correctly.
369 // Also there should be no need to run the external programs any
372 // run makeindex if the <file>.idx has changed or was generated.
373 if (head.haschanged(idxfile)) {
375 LYXERR(Debug::LATEX, "Running MakeIndex.");
376 message(_("Running Index Processor."));
377 // onlyFileName() is needed for cygwin
378 rerun = runMakeIndex(onlyFileName(changeExtension(
379 file.absFileName(), ".idx")), runparams);
382 // I am not pretty sure if need this twice.
383 if (head.haschanged(nlofile))
384 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
385 if (head.haschanged(glofile))
386 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
389 // we will only run latex more if the log file asks for it.
390 // or if the sumchange() is true.
391 // -> rerun asked for:
393 // remake the dependency file
394 // goto 2 or return if max runs are reached.
395 // -> rerun not asked for:
396 // just return (fall out of bottom of func)
398 while ((head.sumchange() || rerun || (scanres & RERUN))
399 && count < MAX_RUN) {
400 // Yes rerun until message goes away, or until
401 // MAX_RUNS are reached.
404 LYXERR(Debug::LATEX, "Run #" << count);
405 message(runMessage(count));
407 scanres = scanLogFile(terr);
408 if (scanres & ERRORS) {
409 deleteFilesOnError();
410 return scanres; // return on error
417 // Write the dependencies to file.
419 LYXERR(Debug::LATEX, "Done.");
424 int LaTeX::startscript()
426 // onlyFileName() is needed for cygwin
427 string tmp = cmd + ' '
428 + quoteName(onlyFileName(file.toFilesystemEncoding()))
429 + " > " + os::nulldev();
431 return one.startscript(Systemcall::Wait, tmp, path);
435 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
436 string const & params)
438 string tmp = runparams.use_japanese ?
439 lyxrc.jindex_command : lyxrc.index_command;
441 if (!runparams.index_command.empty())
442 tmp = runparams.index_command;
445 "idx file has been made, running index processor ("
446 << tmp << ") on file " << f);
448 tmp = subst(tmp, "$$lang", runparams.document_language);
449 if (runparams.use_indices) {
450 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
452 "Multiple indices. Using splitindex command: " << tmp);
458 one.startscript(Systemcall::Wait, tmp, path);
463 bool LaTeX::runMakeIndexNomencl(FileName const & file,
464 string const & nlo, string const & nls)
466 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
467 message(_("Running MakeIndex for nomencl."));
468 string tmp = lyxrc.nomencl_command + ' ';
469 // onlyFileName() is needed for cygwin
470 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
472 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
474 one.startscript(Systemcall::Wait, tmp, path);
479 vector<AuxInfo> const
480 LaTeX::scanAuxFiles(FileName const & file)
482 vector<AuxInfo> result;
484 result.push_back(scanAuxFile(file));
486 string const basename = removeExtension(file.absFileName());
487 for (int i = 1; i < 1000; ++i) {
488 FileName const file2(basename
489 + '.' + convert<string>(i)
493 result.push_back(scanAuxFile(file2));
499 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
502 result.aux_file = file;
503 scanAuxFile(file, result);
508 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
510 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
512 ifstream ifs(file.toFilesystemEncoding().c_str());
514 static regex const reg1("\\\\citation\\{([^}]+)\\}");
515 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
516 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
517 static regex const reg4("\\\\@input\\{([^}]+)\\}");
519 while (getline(ifs, token)) {
520 token = rtrim(token, "\r");
522 // FIXME UNICODE: We assume that citation keys and filenames
523 // in the aux file are in the file system encoding.
524 token = to_utf8(from_filesystem8bit(token));
525 if (regex_match(token, sub, reg1)) {
526 string data = sub.str(1);
527 while (!data.empty()) {
529 data = split(data, citation, ',');
530 LYXERR(Debug::LATEX, "Citation: " << citation);
531 aux_info.citations.insert(citation);
533 } else if (regex_match(token, sub, reg2)) {
534 string data = sub.str(1);
535 // data is now all the bib files separated by ','
536 // get them one by one and pass them to the helper
537 while (!data.empty()) {
539 data = split(data, database, ',');
540 database = changeExtension(database, "bib");
541 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
542 aux_info.databases.insert(database);
544 } else if (regex_match(token, sub, reg3)) {
545 string style = sub.str(1);
546 // token is now the style file
547 // pass it to the helper
548 style = changeExtension(style, "bst");
549 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
550 aux_info.styles.insert(style);
551 } else if (regex_match(token, sub, reg4)) {
552 string const file2 = sub.str(1);
553 scanAuxFile(makeAbsPath(file2), aux_info);
559 void LaTeX::updateBibtexDependencies(DepTable & dep,
560 vector<AuxInfo> const & bibtex_info)
562 // Since a run of Bibtex mandates more latex runs it is ok to
563 // remove all ".bib" and ".bst" files.
564 dep.remove_files_with_extension(".bib");
565 dep.remove_files_with_extension(".bst");
566 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
568 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
569 it != bibtex_info.end(); ++it) {
570 for (set<string>::const_iterator it2 = it->databases.begin();
571 it2 != it->databases.end(); ++it2) {
572 FileName const file = findtexfile(*it2, "bib");
574 dep.insert(file, true);
577 for (set<string>::const_iterator it2 = it->styles.begin();
578 it2 != it->styles.end(); ++it2) {
579 FileName const file = findtexfile(*it2, "bst");
581 dep.insert(file, true);
585 // biber writes nothing into the aux file.
586 // Instead, we have to scan the blg file
589 scanBlgFile(dep, terr);
594 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
595 OutputParams const & runparams)
598 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
599 it != bibtex_info.end(); ++it) {
600 if (!biber && it->databases.empty())
604 string tmp = runparams.use_japanese ?
605 lyxrc.jbibtex_command : lyxrc.bibtex_command;
607 if (!runparams.bibtex_command.empty())
608 tmp = runparams.bibtex_command;
610 // onlyFileName() is needed for cygwin
611 tmp += quoteName(onlyFileName(removeExtension(
612 it->aux_file.absFileName())));
614 one.startscript(Systemcall::Wait, tmp, path);
616 // Return whether bibtex was run
621 int LaTeX::scanLogFile(TeXErrors & terr)
625 int retval = NO_ERRORS;
627 onlyFileName(changeExtension(file.absFileName(), ".log"));
628 LYXERR(Debug::LATEX, "Log file: " << tmp);
629 FileName const fn = FileName(makeAbsPath(tmp));
630 ifstream ifs(fn.toFilesystemEncoding().c_str());
631 bool fle_style = false;
632 static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
633 static regex child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
634 // Flag for 'File ended while scanning' message.
635 // We need to wait for subsequent processing.
636 string wait_for_error;
639 stack <pair<string, int> > child;
642 while (getline(ifs, token)) {
643 // MikTeX sometimes inserts \0 in the log file. They can't be
644 // removed directly with the existing string utility
645 // functions, so convert them first to \r, and remove all
646 // \r's afterwards, since we need to remove them anyway.
647 token = subst(token, '\0', '\r');
648 token = subst(token, "\r", "");
651 LYXERR(Debug::LATEX, "Log line: " << token);
656 // Track child documents
657 for (size_t i = 0; i < token.length(); ++i) {
658 if (token[i] == '(') {
660 size_t j = token.find('(', i + 1);
661 size_t len = j == string::npos
662 ? token.substr(i + 1).length()
664 if (regex_match(token.substr(i + 1, len),
666 string const name = sub.str(1);
667 child.push(make_pair(name, pnest));
670 } else if (token[i] == ')') {
672 && child.top().second == pnest)
677 child_name = child.empty() ? empty_string() : child.top().first;
679 if (contains(token, "file:line:error style messages enabled"))
682 if (prefixIs(token, "LaTeX Warning:") ||
683 prefixIs(token, "! pdfTeX warning")) {
684 // Here shall we handle different
686 retval |= LATEX_WARNING;
687 LYXERR(Debug::LATEX, "LaTeX Warning.");
688 if (contains(token, "Rerun to get cross-references")) {
690 LYXERR(Debug::LATEX, "We should rerun.");
691 // package clefval needs 2 latex runs before bibtex
692 } else if (contains(token, "Value of")
693 && contains(token, "on page")
694 && contains(token, "undefined")) {
695 retval |= ERROR_RERUN;
696 LYXERR(Debug::LATEX, "Force rerun.");
698 } else if (contains(token, "Etaremune labels have changed")) {
699 retval |= ERROR_RERUN;
700 LYXERR(Debug::LATEX, "Force rerun.");
701 } else if (contains(token, "Citation")
702 && contains(token, "on page")
703 && contains(token, "undefined")) {
705 } else if (contains(token, "Citation")
706 && contains(token, "on input line")
707 && contains(token, "undefined")) {
710 } else if (prefixIs(token, "Package")) {
712 retval |= PACKAGE_WARNING;
713 if (contains(token, "natbib Warning:")) {
715 if (contains(token, "Citation")
716 && contains(token, "on page")
717 && contains(token, "undefined")) {
720 } else if (contains(token, "run BibTeX")) {
722 } else if (contains(token, "run Biber")) {
725 } else if (contains(token, "Rerun LaTeX") ||
726 contains(token, "Please rerun LaTeX") ||
727 contains(token, "Rerun to get")) {
728 // at least longtable.sty and bibtopic.sty
730 LYXERR(Debug::LATEX, "We should rerun.");
733 } else if (prefixIs(token, "LETTRE WARNING:")) {
734 if (contains(token, "veuillez recompiler")) {
736 LYXERR(Debug::LATEX, "We should rerun.");
739 } else if (token[0] == '(') {
740 if (contains(token, "Rerun LaTeX") ||
741 contains(token, "Rerun to get")) {
743 LYXERR(Debug::LATEX, "We should rerun.");
746 } else if (prefixIs(token, "! ")
748 && regex_match(token, sub, file_line_error)
749 && !contains(token, "pdfTeX warning"))) {
750 // Ok, we have something that looks like a TeX Error
751 // but what do we really have.
753 // Just get the error description:
755 if (prefixIs(token, "! "))
756 desc = string(token, 2);
759 if (contains(token, "LaTeX Error:"))
760 retval |= LATEX_ERROR;
762 if (prefixIs(token, "! File ended while scanning")){
763 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
764 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
765 retval |= ERROR_RERUN;
766 LYXERR(Debug::LATEX, "Force rerun.");
768 // bug 6445. At this point its not clear we finish with error.
769 wait_for_error = desc;
774 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
775 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
776 retval |= ERROR_RERUN;
777 LYXERR(Debug::LATEX, "Force rerun.");
780 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
781 retval |= LATEX_ERROR;
784 errstr = wait_for_error;
786 if (!getline(ifs, tmp))
788 tmp = rtrim(tmp, "\r");
789 errstr += "\n" + tmp;
792 } while (!contains(tmp, "(job aborted"));
795 from_local8bit("Emergency stop"),
796 from_local8bit(errstr),
804 if (!getline(ifs, tmp))
806 tmp = rtrim(tmp, "\r");
809 } while (!prefixIs(tmp, "l."));
810 if (prefixIs(tmp, "l.")) {
811 // we have a latex error
814 "Package babel Error: You haven't defined the language") ||
816 "Package babel Error: You haven't loaded the option"))
817 retval |= ERROR_RERUN;
818 // get the line number:
820 sscanf(tmp.c_str(), "l.%d", &line);
821 // get the rest of the message:
822 string errstr(tmp, tmp.find(' '));
825 tmp = rtrim(tmp, "\r");
826 while (!contains(errstr, "l.")
828 && !prefixIs(tmp, "! ")
829 && !contains(tmp, "(job aborted")) {
833 tmp = rtrim(tmp, "\r");
835 LYXERR(Debug::LATEX, "line: " << line << '\n'
836 << "Desc: " << desc << '\n' << "Text: " << errstr);
837 if (line == last_line)
843 if (line_count <= 5) {
845 // We have no idea what the encoding of
847 // It seems that the output from the
848 // latex compiler itself is pure ASCII,
849 // but it can include bits from the
850 // document, so whatever encoding we
851 // assume here it can be wrong.
852 terr.insertError(line,
853 from_local8bit(desc),
854 from_local8bit(errstr),
860 // information messages, TeX warnings and other
861 // warnings we have not caught earlier.
862 if (prefixIs(token, "Overfull ")) {
863 retval |= TEX_WARNING;
864 } else if (prefixIs(token, "Underfull ")) {
865 retval |= TEX_WARNING;
866 } else if (contains(token, "Rerun to get citations")) {
867 // Natbib seems to use this.
869 } else if (contains(token, "No pages of output")) {
870 // A dvi file was not created
872 } else if (contains(token, "That makes 100 errors")) {
873 // More than 100 errors were reprted
874 retval |= TOO_MANY_ERRORS;
875 } else if (prefixIs(token, "!pdfTeX error:")){
876 // otherwise we dont catch e.g.:
877 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
880 from_local8bit("pdfTeX Error"),
881 from_local8bit(token),
886 LYXERR(Debug::LATEX, "Log line: " << token);
893 bool insertIfExists(FileName const & absname, DepTable & head)
895 if (absname.exists() && !absname.isDirectory()) {
896 head.insert(absname, true);
903 bool handleFoundFile(string const & ff, DepTable & head)
905 // convert from native os path to unix path
906 string foundfile = os::internal_path(trim(ff));
908 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
910 // Ok now we found a file.
911 // Now we should make sure that this is a file that we can
912 // access through the normal paths.
913 // We will not try any fancy search methods to
916 // (1) foundfile is an
917 // absolute path and should
920 if (FileName::isAbsolute(foundfile)) {
921 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
922 // On initial insert we want to do the update at once
923 // since this file cannot be a file generated by
925 absname.set(foundfile);
926 if (!insertIfExists(absname, head)) {
928 string strippedfile = foundfile;
929 while (contains(strippedfile, " ")) {
930 // files with spaces are often enclosed in quotation
931 // marks; those have to be removed
932 string unquoted = subst(strippedfile, "\"", "");
933 absname.set(unquoted);
934 if (insertIfExists(absname, head))
936 // strip off part after last space and try again
937 string tmp = strippedfile;
938 string const stripoff =
939 rsplit(tmp, strippedfile, ' ');
940 absname.set(strippedfile);
941 if (insertIfExists(absname, head))
947 string onlyfile = onlyFileName(foundfile);
948 absname = makeAbsPath(onlyfile);
951 while (contains(foundfile, ' ')) {
952 if (absname.exists())
956 // files with spaces are often enclosed in quotation
957 // marks; those have to be removed
958 string unquoted = subst(foundfile, "\"", "");
959 absname = makeAbsPath(unquoted);
960 if (absname.exists())
962 // strip off part after last space and try again
964 string const stripoff =
965 rsplit(foundfile, strippedfile, ' ');
966 foundfile = strippedfile;
967 onlyfile = onlyFileName(strippedfile);
968 absname = makeAbsPath(onlyfile);
972 // (2) foundfile is in the tmpdir
973 // insert it into head
974 if (absname.exists() && !absname.isDirectory()) {
975 // FIXME: This regex contained glo, but glo is used by the old
976 // version of nomencl.sty. Do we need to put it back?
977 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
978 if (regex_match(onlyfile, unwanted)) {
979 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
980 << " in the dep file");
981 } else if (suffixIs(onlyfile, ".tex")) {
982 // This is a tex file generated by LyX
983 // and latex is not likely to change this
985 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
986 head.insert(absname, true);
988 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
989 head.insert(absname);
993 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
999 bool completeFilename(string const & ff, DepTable & head)
1001 // If we do not find a dot, we suspect
1002 // a fragmental file name
1003 if (!contains(ff, '.'))
1006 // if we have a dot, we let handleFoundFile decide
1007 return handleFoundFile(ff, head);
1011 int iterateLine(string const token, regex const reg, string const & closing,
1012 int fragment_pos, DepTable & head)
1015 string::const_iterator first = token.begin();
1016 string::const_iterator end = token.end();
1017 bool fragment = false;
1020 while (regex_search(first, end, what, reg)) {
1021 // if we have a dot, try to handle as file
1022 if (contains(what.str(1), '.')) {
1023 first = what[0].second;
1024 if (what.str(2) == closing) {
1025 handleFoundFile(what.str(1), head);
1026 // since we had a closing bracket,
1027 // do not investigate further
1030 // if we have no closing bracket,
1031 // try to handle as file nevertheless
1032 fragment = !handleFoundFile(
1033 what.str(1) + what.str(2), head);
1035 // if we do not have a dot, check if the line has
1036 // a closing bracket (else, we suspect a line break)
1037 else if (what.str(2) != closing) {
1038 first = what[0].second;
1041 // we have a closing bracket, so the content
1042 // is not a file name.
1043 // no need to investigate further
1044 first = what[0].second;
1047 last_match = what.str(1);
1050 // We need to consider the result from previous line iterations:
1051 // We might not find a fragment here, but another one might follow
1052 // E.g.: (filename.ext) <filenam
1053 // Vice versa, we consider the search completed if a real match
1054 // follows a potential fragment from a previous iteration.
1055 // E.g. <some text we considered a fragment (filename.ext)
1056 // result = -1 means we did not find a fragment!
1058 int last_match_pos = -1;
1059 if (!last_match.empty() && token.find(last_match) != string::npos)
1060 last_match_pos = int(token.find(last_match));
1062 if (last_match_pos > fragment_pos)
1063 result = last_match_pos;
1065 result = fragment_pos;
1067 if (last_match_pos < fragment_pos)
1068 result = fragment_pos;
1076 void LaTeX::deplog(DepTable & head)
1078 // This function reads the LaTeX log file end extracts all the
1079 // external files used by the LaTeX run. The files are then
1080 // entered into the dependency file.
1082 string const logfile =
1083 onlyFileName(changeExtension(file.absFileName(), ".log"));
1085 static regex const reg1("File: (.+).*");
1086 static regex const reg2("No file (.+)(.).*");
1087 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1088 // If an index should be created, MikTex does not write a line like
1089 // \openout# = 'sample.idx'.
1090 // but instead only a line like this into the log:
1091 // Writing index file sample.idx
1092 static regex const reg4("Writing index file (.+).*");
1093 static regex const regoldnomencl("Writing glossary file (.+).*");
1094 static regex const regnomencl("Writing nomenclature file (.+).*");
1095 // If a toc should be created, MikTex does not write a line like
1096 // \openout# = `sample.toc'.
1097 // but only a line like this into the log:
1099 // This line is also written by tetex.
1100 // This line is not present if no toc should be created.
1101 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1102 // file names can be enclosed in <...> (anywhere on the line)
1103 static regex const reg5(".*<[^>]+.*");
1104 // and also (...) anywhere on the line
1105 static regex const reg6(".*\\([^)]+.*");
1107 FileName const fn = makeAbsPath(logfile);
1108 ifstream ifs(fn.toFilesystemEncoding().c_str());
1111 // Ok, the scanning of files here is not sufficient.
1112 // Sometimes files are named by "File: xxx" only
1113 // Therefore we use some regexps to find files instead.
1114 // Note: all file names and paths might contains spaces.
1115 // Also, file names might be broken across lines. Therefore
1116 // we mark (potential) fragments and merge those lines.
1117 bool fragment = false;
1119 getline(ifs, token);
1120 // MikTeX sometimes inserts \0 in the log file. They can't be
1121 // removed directly with the existing string utility
1122 // functions, so convert them first to \r, and remove all
1123 // \r's afterwards, since we need to remove them anyway.
1124 token = subst(token, '\0', '\r');
1125 token = subst(token, "\r", "");
1126 if (token.empty() || token == ")") {
1127 lastline = string();
1131 // FIXME UNICODE: We assume that the file names in the log
1132 // file are in the file system encoding.
1133 token = to_utf8(from_filesystem8bit(token));
1135 // Sometimes, filenames are broken across lines.
1136 // We care for that and save suspicious lines.
1137 // Here we exclude some cases where we are sure
1138 // that there is no continued filename
1139 if (!lastline.empty()) {
1140 static regex const package_info("Package \\w+ Info: .*");
1141 static regex const package_warning("Package \\w+ Warning: .*");
1142 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1143 || prefixIs(token, "Package:")
1144 || prefixIs(token, "Language:")
1145 || prefixIs(token, "LaTeX Info:")
1146 || prefixIs(token, "LaTeX Font Info:")
1147 || prefixIs(token, "\\openout[")
1148 || prefixIs(token, "))")
1149 || regex_match(token, package_info)
1150 || regex_match(token, package_warning))
1151 lastline = string();
1154 if (!lastline.empty())
1155 // probably a continued filename from last line
1156 token = lastline + token;
1157 if (token.length() > 255) {
1158 // string too long. Cut off.
1159 token.erase(0, token.length() - 251);
1164 // (1) "File: file.ext"
1165 if (regex_match(token, sub, reg1)) {
1166 // is this a fragmental file name?
1167 fragment = !completeFilename(sub.str(1), head);
1169 if (suffixIs(token, ")"))
1170 // no fragment for sure
1172 // (2) "No file file.ext"
1173 } else if (regex_match(token, sub, reg2)) {
1174 // file names must contains a dot, line ends with dot
1175 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1176 fragment = !handleFoundFile(sub.str(1), head);
1178 // we suspect a line break
1180 // (3) "\openout<nr> = `file.ext'."
1181 } else if (regex_match(token, sub, reg3)) {
1182 // search for closing '. at the end of the line
1183 if (sub.str(2) == "\'.")
1184 fragment = !handleFoundFile(sub.str(1), head);
1186 // potential fragment
1188 // (4) "Writing index file file.ext"
1189 } else if (regex_match(token, sub, reg4))
1190 // fragmential file name?
1191 fragment = !completeFilename(sub.str(1), head);
1192 // (5) "Writing nomenclature file file.ext"
1193 else if (regex_match(token, sub, regnomencl) ||
1194 regex_match(token, sub, regoldnomencl))
1195 // fragmental file name?
1196 fragment= !completeFilename(sub.str(1), head);
1197 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1198 else if (regex_match(token, sub, miktexTocReg))
1199 fragment = !handleFoundFile(onlyFileName(changeExtension(
1200 file.absFileName(), ".toc")), head);
1202 // not found, but we won't check further
1205 int fragment_pos = -1;
1207 // We can have several of these on one line
1208 // (and in addition to those above)
1209 if (regex_match(token, sub, reg5)) {
1210 // search for strings in <...>
1211 static regex reg5_1("<([^>]+)(.)");
1212 fragment_pos = iterateLine(token, reg5_1, ">",
1213 fragment_pos, head);
1214 fragment = (fragment_pos != -1);
1218 // We can have several of these on one line
1219 // this must be queried separated, because of
1220 // cases such as "File: file.ext (type eps)"
1221 // where "File: file.ext" would be skipped
1222 if (regex_match(token, sub, reg6)) {
1223 // search for strings in (...)
1224 static regex reg6_1("\\(([^()]+)(.)");
1225 fragment_pos = iterateLine(token, reg6_1, ")",
1226 fragment_pos, head);
1227 fragment = (fragment_pos != -1);
1231 // probable linebreak within file name:
1235 // no linebreak: reset
1236 lastline = string();
1239 // Make sure that the main .tex file is in the dependency file.
1240 head.insert(file, true);
1244 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1246 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1247 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1249 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1251 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1252 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1253 static regex const bibtexError2("^(.*---while reading file).*$");
1254 static regex const bibtexError3("(A bad cross reference---).*");
1255 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1256 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1257 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1258 int retval = NO_ERRORS;
1261 while (getline(ifs, token)) {
1262 token = rtrim(token, "\r");
1264 // FIXME UNICODE: We assume that citation keys and filenames
1265 // in the aux file are in the file system encoding.
1266 token = to_utf8(from_filesystem8bit(token));
1267 if (regex_match(token, sub, reg1)) {
1268 string data = sub.str(3);
1269 if (!data.empty()) {
1270 LYXERR(Debug::LATEX, "Found bib file: " << data);
1271 handleFoundFile(data, dep);
1274 else if (regex_match(token, sub, bibtexError)
1275 || regex_match(token, sub, bibtexError2)
1276 || regex_match(token, sub, bibtexError4)
1277 || regex_match(token, sub, bibtexError5)) {
1278 retval |= BIBTEX_ERROR;
1279 string errstr = N_("BibTeX error: ") + token;
1281 if ((prefixIs(token, "while executing---line")
1282 || prefixIs(token, "---line ")
1283 || prefixIs(token, "*Please notify the BibTeX"))
1284 && !prevtoken.empty()) {
1285 errstr = N_("BibTeX error: ") + prevtoken;
1286 message = prevtoken + '\n';
1290 from_local8bit(errstr),
1291 from_local8bit(message));
1292 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1293 retval |= BIBTEX_ERROR;
1294 string errstr = N_("BibTeX error: ") + prevtoken;
1295 string message = prevtoken + '\n' + token;
1297 from_local8bit(errstr),
1298 from_local8bit(message));
1299 } else if (regex_match(token, sub, biberError)) {
1300 retval |= BIBTEX_ERROR;
1301 string errstr = N_("Biber error: ") + sub.str(2);
1302 string message = token;
1304 from_local8bit(errstr),
1305 from_local8bit(message));