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, bool const clean_start)
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"));
109 removeAuxiliaryFiles();
113 void LaTeX::removeAuxiliaryFiles() const
115 // Note that we do not always call this function when there is an error.
116 // For example, if there is an error but an output file is produced we
117 // still would like to output (export/view) the file.
119 // What files do we have to delete?
121 // This will at least make latex do all the runs
122 depfile.removeFile();
124 // but the reason for the error might be in a generated file...
127 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
131 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
135 FileName const ind(changeExtension(file.absFileName(), ".ind"));
139 FileName const nls(changeExtension(file.absFileName(), ".nls"));
142 // nomencl file (old version of the package)
143 FileName const gls(changeExtension(file.absFileName(), ".gls"));
146 // Also remove the aux file
147 FileName const aux(changeExtension(file.absFileName(), ".aux"));
150 // Remove the output file, which is often generated even if error
151 output_file.removeFile();
155 int LaTeX::run(TeXErrors & terr)
156 // We know that this function will only be run if the lyx buffer
157 // has been changed. We also know that a newly written .tex file
158 // is always different from the previous one because of the date
159 // in it. However it seems safe to run latex (at least) one time
160 // each time the .tex file changes.
162 int scanres = NO_ERRORS;
163 int bscanres = NO_ERRORS;
164 unsigned int count = 0; // number of times run
165 num_errors = 0; // just to make sure.
166 unsigned int const MAX_RUN = 6;
167 DepTable head; // empty head
168 bool rerun = false; // rerun requested
170 // The class LaTeX does not know the temp path.
171 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
175 // first check if the file dependencies exist:
176 // ->If it does exist
177 // check if any of the files mentioned in it have
178 // changed (done using a checksum).
180 // run latex once and
181 // remake the dependency file
182 // -> if not changed:
183 // just return there is nothing to do for us.
184 // ->if it doesn't exist
186 // run latex once (we need to run latex once anyway) and
187 // remake the dependency file.
190 bool had_depfile = depfile.exists();
191 bool run_bibtex = false;
192 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
195 LYXERR(Debug::DEPEND, "Dependency file exists");
196 // Read the dep file:
197 had_depfile = head.read(depfile);
201 // Update the checksums
203 // Can't just check if anything has changed because it might
204 // have aborted on error last time... in which cas we need
205 // to re-run latex and collect the error messages
206 // (even if they are the same).
207 if (!output_file.exists()) {
208 LYXERR(Debug::DEPEND,
209 "re-running LaTeX because output file doesn't exist.");
210 } else if (!head.sumchange()) {
211 LYXERR(Debug::DEPEND, "return no_change");
214 LYXERR(Debug::DEPEND, "Dependency file has changed");
217 if (head.extchanged(".bib") || head.extchanged(".bst"))
220 LYXERR(Debug::DEPEND,
221 "Dependency file does not exist, or has wrong format");
223 /// We scan the aux file even when had_depfile = false,
224 /// because we can run pdflatex on the file after running latex on it,
225 /// in which case we will not need to run bibtex again.
226 vector<AuxInfo> bibtex_info_old;
228 bibtex_info_old = scanAuxFiles(aux_file);
231 LYXERR(Debug::LATEX, "Run #" << count);
232 message(runMessage(count));
234 int const exit_code = startscript();
236 scanres = scanLogFile(terr);
237 if (scanres & ERROR_RERUN) {
238 LYXERR(Debug::LATEX, "Rerunning LaTeX");
240 scanres = scanLogFile(terr);
243 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
244 if (!run_bibtex && bibtex_info_old != bibtex_info)
247 // update the dependencies.
248 deplog(head); // reads the latex log
252 // At this point we must run external programs if needed.
253 // makeindex will be run if a .idx file changed or was generated.
254 // And if there were undefined citations or changes in references
255 // the .aux file is checked for signs of bibtex. Bibtex is then run
258 // memoir (at least) writes an empty *idx file in the first place.
259 // A second latex run is needed.
260 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
261 rerun = idxfile.exists() && idxfile.isFileEmpty();
264 if (head.haschanged(idxfile)) {
266 LYXERR(Debug::LATEX, "Running MakeIndex.");
267 message(_("Running Index Processor."));
268 // onlyFileName() is needed for cygwin
269 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
272 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
273 // If all nomencl entries are removed, nomencl writes an empty nlo file.
274 // DepTable::hasChanged() returns false in this case, since it does not
275 // distinguish empty files from non-existing files. This is why we need
276 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
277 // FIXME: Sort out the real problem in DepTable.
278 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
279 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
280 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
281 if (head.haschanged(glofile))
282 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
284 // check if we're using biber instead of bibtex
285 // biber writes no info to the aux file, so we just check
286 // if a bcf file exists (and if it was updated)
287 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
288 biber |= head.exist(bcffile);
291 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
292 if (scanres & UNDEF_CIT || run_bibtex) {
293 // Here we must scan the .aux file and look for
294 // "\bibdata" and/or "\bibstyle". If one of those
295 // tags is found -> run bibtex and set rerun = true;
297 LYXERR(Debug::LATEX, "Running BibTeX.");
298 message(_("Running BibTeX."));
299 updateBibtexDependencies(head, bibtex_info);
300 rerun |= runBibTeX(bibtex_info, runparams);
301 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
302 if (blgfile.exists())
303 bscanres = scanBlgFile(head, terr);
304 } else if (!had_depfile) {
305 /// If we run pdflatex on the file after running latex on it,
306 /// then we do not need to run bibtex, but we do need to
307 /// insert the .bib and .bst files into the .dep-pdf file.
308 updateBibtexDependencies(head, bibtex_info);
312 // we know on this point that latex has been run once (or we just
313 // returned) and the question now is to decide if we need to run
314 // it any more. This is done by asking if any of the files in the
315 // dependency file has changed. (remember that the checksum for
316 // a given file is reported to have changed if it just was created)
317 // -> if changed or rerun == true:
318 // run latex once more and
319 // update the dependency structure
320 // -> if not changed:
321 // we do nothing at this point
323 if (rerun || head.sumchange()) {
326 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
327 LYXERR(Debug::LATEX, "Run #" << count);
328 message(runMessage(count));
330 scanres = scanLogFile(terr);
332 // update the depedencies
333 deplog(head); // reads the latex log
336 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
341 // Complex bibliography packages such as Biblatex require
342 // an additional bibtex cycle sometimes.
343 if (scanres & UNDEF_CIT) {
344 // Here we must scan the .aux file and look for
345 // "\bibdata" and/or "\bibstyle". If one of those
346 // tags is found -> run bibtex and set rerun = true;
348 LYXERR(Debug::LATEX, "Running BibTeX.");
349 message(_("Running BibTeX."));
350 updateBibtexDependencies(head, bibtex_info);
351 rerun |= runBibTeX(bibtex_info, runparams);
352 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
353 if (blgfile.exists())
354 bscanres = scanBlgFile(head, terr);
358 // The inclusion of files generated by external programs such as
359 // makeindex or bibtex might have done changes to pagenumbering,
360 // etc. And because of this we must run the external programs
361 // again to make sure everything is redone correctly.
362 // Also there should be no need to run the external programs any
365 // run makeindex if the <file>.idx has changed or was generated.
366 if (head.haschanged(idxfile)) {
368 LYXERR(Debug::LATEX, "Running MakeIndex.");
369 message(_("Running Index Processor."));
370 // onlyFileName() is needed for cygwin
371 rerun = runMakeIndex(onlyFileName(changeExtension(
372 file.absFileName(), ".idx")), runparams);
375 // I am not pretty sure if need this twice.
376 if (head.haschanged(nlofile))
377 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
378 if (head.haschanged(glofile))
379 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
382 // we will only run latex more if the log file asks for it.
383 // or if the sumchange() is true.
384 // -> rerun asked for:
386 // remake the dependency file
387 // goto 2 or return if max runs are reached.
388 // -> rerun not asked for:
389 // just return (fall out of bottom of func)
391 while ((head.sumchange() || rerun || (scanres & RERUN))
392 && count < MAX_RUN) {
393 // Yes rerun until message goes away, or until
394 // MAX_RUNS are reached.
397 LYXERR(Debug::LATEX, "Run #" << count);
398 message(runMessage(count));
400 scanres = scanLogFile(terr);
406 // Write the dependencies to file.
410 scanres |= NONZERO_ERROR;
412 LYXERR(Debug::LATEX, "Done.");
414 if (bscanres & ERRORS)
415 return bscanres; // return on error
421 int LaTeX::startscript()
423 // onlyFileName() is needed for cygwin
424 string tmp = cmd + ' '
425 + quoteName(onlyFileName(file.toFilesystemEncoding()))
426 + " > " + os::nulldev();
428 return one.startscript(Systemcall::Wait, tmp, path);
432 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
433 string const & params)
435 string tmp = runparams.use_japanese ?
436 lyxrc.jindex_command : lyxrc.index_command;
438 if (!runparams.index_command.empty())
439 tmp = runparams.index_command;
442 "idx file has been made, running index processor ("
443 << tmp << ") on file " << f);
445 tmp = subst(tmp, "$$lang", runparams.document_language);
446 if (runparams.use_indices) {
447 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
449 "Multiple indices. Using splitindex command: " << tmp);
455 one.startscript(Systemcall::Wait, tmp, path);
460 bool LaTeX::runMakeIndexNomencl(FileName const & file,
461 string const & nlo, string const & nls)
463 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
464 message(_("Running MakeIndex for nomencl."));
465 string tmp = lyxrc.nomencl_command + ' ';
466 // onlyFileName() is needed for cygwin
467 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
469 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
471 one.startscript(Systemcall::Wait, tmp, path);
476 vector<AuxInfo> const
477 LaTeX::scanAuxFiles(FileName const & file)
479 vector<AuxInfo> result;
481 result.push_back(scanAuxFile(file));
483 string const basename = removeExtension(file.absFileName());
484 for (int i = 1; i < 1000; ++i) {
485 FileName const file2(basename
486 + '.' + convert<string>(i)
490 result.push_back(scanAuxFile(file2));
496 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
499 result.aux_file = file;
500 scanAuxFile(file, result);
505 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
507 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
509 ifstream ifs(file.toFilesystemEncoding().c_str());
511 static regex const reg1("\\\\citation\\{([^}]+)\\}");
512 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
513 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
514 static regex const reg4("\\\\@input\\{([^}]+)\\}");
516 while (getline(ifs, token)) {
517 token = rtrim(token, "\r");
519 // FIXME UNICODE: We assume that citation keys and filenames
520 // in the aux file are in the file system encoding.
521 token = to_utf8(from_filesystem8bit(token));
522 if (regex_match(token, sub, reg1)) {
523 string data = sub.str(1);
524 while (!data.empty()) {
526 data = split(data, citation, ',');
527 LYXERR(Debug::LATEX, "Citation: " << citation);
528 aux_info.citations.insert(citation);
530 } else if (regex_match(token, sub, reg2)) {
531 string data = sub.str(1);
532 // data is now all the bib files separated by ','
533 // get them one by one and pass them to the helper
534 while (!data.empty()) {
536 data = split(data, database, ',');
537 database = changeExtension(database, "bib");
538 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
539 aux_info.databases.insert(database);
541 } else if (regex_match(token, sub, reg3)) {
542 string style = sub.str(1);
543 // token is now the style file
544 // pass it to the helper
545 style = changeExtension(style, "bst");
546 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
547 aux_info.styles.insert(style);
548 } else if (regex_match(token, sub, reg4)) {
549 string const file2 = sub.str(1);
550 scanAuxFile(makeAbsPath(file2), aux_info);
556 void LaTeX::updateBibtexDependencies(DepTable & dep,
557 vector<AuxInfo> const & bibtex_info)
559 // Since a run of Bibtex mandates more latex runs it is ok to
560 // remove all ".bib" and ".bst" files.
561 dep.remove_files_with_extension(".bib");
562 dep.remove_files_with_extension(".bst");
563 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
565 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
566 it != bibtex_info.end(); ++it) {
567 for (set<string>::const_iterator it2 = it->databases.begin();
568 it2 != it->databases.end(); ++it2) {
569 FileName const file = findtexfile(*it2, "bib");
571 dep.insert(file, true);
574 for (set<string>::const_iterator it2 = it->styles.begin();
575 it2 != it->styles.end(); ++it2) {
576 FileName const file = findtexfile(*it2, "bst");
578 dep.insert(file, true);
582 // biber writes nothing into the aux file.
583 // Instead, we have to scan the blg file
586 scanBlgFile(dep, terr);
591 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
592 OutputParams const & runparams)
595 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
596 it != bibtex_info.end(); ++it) {
597 if (!biber && it->databases.empty())
601 string tmp = runparams.use_japanese ?
602 lyxrc.jbibtex_command : lyxrc.bibtex_command;
604 if (!runparams.bibtex_command.empty())
605 tmp = runparams.bibtex_command;
607 // onlyFileName() is needed for cygwin
608 tmp += quoteName(onlyFileName(removeExtension(
609 it->aux_file.absFileName())));
611 one.startscript(Systemcall::Wait, tmp, path);
613 // Return whether bibtex was run
618 int LaTeX::scanLogFile(TeXErrors & terr)
622 int retval = NO_ERRORS;
624 onlyFileName(changeExtension(file.absFileName(), ".log"));
625 LYXERR(Debug::LATEX, "Log file: " << tmp);
626 FileName const fn = FileName(makeAbsPath(tmp));
627 ifstream ifs(fn.toFilesystemEncoding().c_str());
628 bool fle_style = false;
629 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
630 static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
631 // Flag for 'File ended while scanning' message.
632 // We need to wait for subsequent processing.
633 string wait_for_error;
636 stack <pair<string, int> > child;
639 while (getline(ifs, token)) {
640 // MikTeX sometimes inserts \0 in the log file. They can't be
641 // removed directly with the existing string utility
642 // functions, so convert them first to \r, and remove all
643 // \r's afterwards, since we need to remove them anyway.
644 token = subst(token, '\0', '\r');
645 token = subst(token, "\r", "");
648 LYXERR(Debug::LATEX, "Log line: " << token);
653 // Track child documents
654 for (size_t i = 0; i < token.length(); ++i) {
655 if (token[i] == '(') {
657 size_t j = token.find('(', i + 1);
658 size_t len = j == string::npos
659 ? token.substr(i + 1).length()
661 string const substr = token.substr(i + 1, len);
662 if (regex_match(substr, sub, child_file)) {
663 string const name = sub.str(1);
664 child.push(make_pair(name, pnest));
667 } else if (token[i] == ')') {
669 && child.top().second == pnest)
674 child_name = child.empty() ? empty_string() : child.top().first;
676 if (contains(token, "file:line:error style messages enabled"))
679 if (prefixIs(token, "LaTeX Warning:") ||
680 prefixIs(token, "! pdfTeX warning")) {
681 // Here shall we handle different
683 retval |= LATEX_WARNING;
684 LYXERR(Debug::LATEX, "LaTeX Warning.");
685 if (contains(token, "Rerun to get cross-references")) {
687 LYXERR(Debug::LATEX, "We should rerun.");
688 // package clefval needs 2 latex runs before bibtex
689 } else if (contains(token, "Value of")
690 && contains(token, "on page")
691 && contains(token, "undefined")) {
692 retval |= ERROR_RERUN;
693 LYXERR(Debug::LATEX, "Force rerun.");
695 } else if (contains(token, "Etaremune labels have changed")) {
696 retval |= ERROR_RERUN;
697 LYXERR(Debug::LATEX, "Force rerun.");
698 } else if (contains(token, "Citation")
699 && contains(token, "on page")
700 && contains(token, "undefined")) {
702 } else if (contains(token, "Citation")
703 && contains(token, "on input line")
704 && contains(token, "undefined")) {
707 } else if (prefixIs(token, "Package")) {
709 retval |= PACKAGE_WARNING;
710 if (contains(token, "natbib Warning:")) {
712 if (contains(token, "Citation")
713 && contains(token, "on page")
714 && contains(token, "undefined")) {
717 } else if (contains(token, "run BibTeX")) {
719 } else if (contains(token, "run Biber")) {
722 } else if (contains(token, "Rerun LaTeX") ||
723 contains(token, "Please rerun LaTeX") ||
724 contains(token, "Rerun to get")) {
725 // at least longtable.sty and bibtopic.sty
727 LYXERR(Debug::LATEX, "We should rerun.");
730 } else if (prefixIs(token, "LETTRE WARNING:")) {
731 if (contains(token, "veuillez recompiler")) {
733 LYXERR(Debug::LATEX, "We should rerun.");
736 } else if (token[0] == '(') {
737 if (contains(token, "Rerun LaTeX") ||
738 contains(token, "Rerun to get")) {
740 LYXERR(Debug::LATEX, "We should rerun.");
743 } else if (prefixIs(token, "! ")
745 && regex_match(token, sub, file_line_error)
746 && !contains(token, "pdfTeX warning"))) {
747 // Ok, we have something that looks like a TeX Error
748 // but what do we really have.
750 // Just get the error description:
752 if (prefixIs(token, "! "))
753 desc = string(token, 2);
756 if (contains(token, "LaTeX Error:"))
757 retval |= LATEX_ERROR;
759 if (prefixIs(token, "! File ended while scanning")){
760 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
761 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
762 retval |= ERROR_RERUN;
763 LYXERR(Debug::LATEX, "Force rerun.");
765 // bug 6445. At this point its not clear we finish with error.
766 wait_for_error = desc;
771 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
772 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
773 retval |= ERROR_RERUN;
774 LYXERR(Debug::LATEX, "Force rerun.");
777 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
778 retval |= LATEX_ERROR;
781 errstr = wait_for_error;
783 if (!getline(ifs, tmp))
785 tmp = rtrim(tmp, "\r");
786 errstr += "\n" + tmp;
789 } while (!contains(tmp, "(job aborted"));
792 from_local8bit("Emergency stop"),
793 from_local8bit(errstr),
801 if (!getline(ifs, tmp))
803 tmp = rtrim(tmp, "\r");
804 // 15 is somewhat arbitrarily chosen, based on practice.
805 // We used 10 for 14 years and increased it to 15 when we
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")
818 "Package babel Error: Unknown language"))
819 retval |= ERROR_RERUN;
820 // get the line number:
822 sscanf(tmp.c_str(), "l.%d", &line);
823 // get the rest of the message:
824 string errstr(tmp, tmp.find(' '));
827 tmp = rtrim(tmp, "\r");
828 while (!contains(errstr, "l.")
830 && !prefixIs(tmp, "! ")
831 && !contains(tmp, "(job aborted")) {
835 tmp = rtrim(tmp, "\r");
837 LYXERR(Debug::LATEX, "line: " << line << '\n'
838 << "Desc: " << desc << '\n' << "Text: " << errstr);
839 if (line == last_line)
845 if (line_count <= 5) {
847 // We have no idea what the encoding of
849 // It seems that the output from the
850 // latex compiler itself is pure ASCII,
851 // but it can include bits from the
852 // document, so whatever encoding we
853 // assume here it can be wrong.
854 terr.insertError(line,
855 from_local8bit(desc),
856 from_local8bit(errstr),
862 // information messages, TeX warnings and other
863 // warnings we have not caught earlier.
864 if (prefixIs(token, "Overfull ")) {
865 retval |= TEX_WARNING;
866 } else if (prefixIs(token, "Underfull ")) {
867 retval |= TEX_WARNING;
868 } else if (contains(token, "Rerun to get citations")) {
869 // Natbib seems to use this.
871 } else if (contains(token, "No pages of output")) {
872 // A dvi file was not created
874 } else if (contains(token, "That makes 100 errors")) {
875 // More than 100 errors were reprted
876 retval |= TOO_MANY_ERRORS;
877 } else if (prefixIs(token, "!pdfTeX error:")){
878 // otherwise we dont catch e.g.:
879 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
882 from_local8bit("pdfTeX Error"),
883 from_local8bit(token),
888 LYXERR(Debug::LATEX, "Log line: " << token);
895 bool insertIfExists(FileName const & absname, DepTable & head)
897 if (absname.exists() && !absname.isDirectory()) {
898 head.insert(absname, true);
905 bool handleFoundFile(string const & ff, DepTable & head)
907 // convert from native os path to unix path
908 string foundfile = os::internal_path(trim(ff));
910 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
912 // Ok now we found a file.
913 // Now we should make sure that this is a file that we can
914 // access through the normal paths.
915 // We will not try any fancy search methods to
918 // (1) foundfile is an
919 // absolute path and should
922 if (FileName::isAbsolute(foundfile)) {
923 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
924 // On initial insert we want to do the update at once
925 // since this file cannot be a file generated by
927 absname.set(foundfile);
928 if (!insertIfExists(absname, head)) {
930 string strippedfile = foundfile;
931 while (contains(strippedfile, " ")) {
932 // files with spaces are often enclosed in quotation
933 // marks; those have to be removed
934 string unquoted = subst(strippedfile, "\"", "");
935 absname.set(unquoted);
936 if (insertIfExists(absname, head))
938 // strip off part after last space and try again
939 string tmp = strippedfile;
940 string const stripoff =
941 rsplit(tmp, strippedfile, ' ');
942 absname.set(strippedfile);
943 if (insertIfExists(absname, head))
949 string onlyfile = onlyFileName(foundfile);
950 absname = makeAbsPath(onlyfile);
953 while (contains(foundfile, ' ')) {
954 if (absname.exists())
958 // files with spaces are often enclosed in quotation
959 // marks; those have to be removed
960 string unquoted = subst(foundfile, "\"", "");
961 absname = makeAbsPath(unquoted);
962 if (absname.exists())
964 // strip off part after last space and try again
966 string const stripoff =
967 rsplit(foundfile, strippedfile, ' ');
968 foundfile = strippedfile;
969 onlyfile = onlyFileName(strippedfile);
970 absname = makeAbsPath(onlyfile);
974 // (2) foundfile is in the tmpdir
975 // insert it into head
976 if (absname.exists() && !absname.isDirectory()) {
977 // FIXME: This regex contained glo, but glo is used by the old
978 // version of nomencl.sty. Do we need to put it back?
979 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
980 if (regex_match(onlyfile, unwanted)) {
981 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
982 << " in the dep file");
983 } else if (suffixIs(onlyfile, ".tex")) {
984 // This is a tex file generated by LyX
985 // and latex is not likely to change this
987 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
988 head.insert(absname, true);
990 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
991 head.insert(absname);
995 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1001 bool completeFilename(string const & ff, DepTable & head)
1003 // If we do not find a dot, we suspect
1004 // a fragmental file name
1005 if (!contains(ff, '.'))
1008 // if we have a dot, we let handleFoundFile decide
1009 return handleFoundFile(ff, head);
1013 int iterateLine(string const & token, regex const & reg, string const & closing,
1014 int fragment_pos, DepTable & head)
1017 string::const_iterator first = token.begin();
1018 string::const_iterator end = token.end();
1019 bool fragment = false;
1022 while (regex_search(first, end, what, reg)) {
1023 // if we have a dot, try to handle as file
1024 if (contains(what.str(1), '.')) {
1025 first = what[0].second;
1026 if (what.str(2) == closing) {
1027 handleFoundFile(what.str(1), head);
1028 // since we had a closing bracket,
1029 // do not investigate further
1032 // if we have no closing bracket,
1033 // try to handle as file nevertheless
1034 fragment = !handleFoundFile(
1035 what.str(1) + what.str(2), head);
1037 // if we do not have a dot, check if the line has
1038 // a closing bracket (else, we suspect a line break)
1039 else if (what.str(2) != closing) {
1040 first = what[0].second;
1043 // we have a closing bracket, so the content
1044 // is not a file name.
1045 // no need to investigate further
1046 first = what[0].second;
1049 last_match = what.str(1);
1052 // We need to consider the result from previous line iterations:
1053 // We might not find a fragment here, but another one might follow
1054 // E.g.: (filename.ext) <filenam
1055 // Vice versa, we consider the search completed if a real match
1056 // follows a potential fragment from a previous iteration.
1057 // E.g. <some text we considered a fragment (filename.ext)
1058 // result = -1 means we did not find a fragment!
1060 int last_match_pos = -1;
1061 if (!last_match.empty() && token.find(last_match) != string::npos)
1062 last_match_pos = int(token.find(last_match));
1064 if (last_match_pos > fragment_pos)
1065 result = last_match_pos;
1067 result = fragment_pos;
1069 if (last_match_pos < fragment_pos)
1070 result = fragment_pos;
1078 void LaTeX::deplog(DepTable & head)
1080 // This function reads the LaTeX log file end extracts all the
1081 // external files used by the LaTeX run. The files are then
1082 // entered into the dependency file.
1084 string const logfile =
1085 onlyFileName(changeExtension(file.absFileName(), ".log"));
1087 static regex const reg1("File: (.+).*");
1088 static regex const reg2("No file (.+)(.).*");
1089 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1090 // If an index should be created, MikTex does not write a line like
1091 // \openout# = 'sample.idx'.
1092 // but instead only a line like this into the log:
1093 // Writing index file sample.idx
1094 static regex const reg4("Writing index file (.+).*");
1095 static regex const regoldnomencl("Writing glossary file (.+).*");
1096 static regex const regnomencl("Writing nomenclature file (.+).*");
1097 // If a toc should be created, MikTex does not write a line like
1098 // \openout# = `sample.toc'.
1099 // but only a line like this into the log:
1101 // This line is also written by tetex.
1102 // This line is not present if no toc should be created.
1103 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1104 // file names can be enclosed in <...> (anywhere on the line)
1105 static regex const reg5(".*<[^>]+.*");
1106 // and also (...) anywhere on the line
1107 static regex const reg6(".*\\([^)]+.*");
1109 FileName const fn = makeAbsPath(logfile);
1110 ifstream ifs(fn.toFilesystemEncoding().c_str());
1113 // Ok, the scanning of files here is not sufficient.
1114 // Sometimes files are named by "File: xxx" only
1115 // Therefore we use some regexps to find files instead.
1116 // Note: all file names and paths might contains spaces.
1117 // Also, file names might be broken across lines. Therefore
1118 // we mark (potential) fragments and merge those lines.
1119 bool fragment = false;
1121 getline(ifs, token);
1122 // MikTeX sometimes inserts \0 in the log file. They can't be
1123 // removed directly with the existing string utility
1124 // functions, so convert them first to \r, and remove all
1125 // \r's afterwards, since we need to remove them anyway.
1126 token = subst(token, '\0', '\r');
1127 token = subst(token, "\r", "");
1128 if (token.empty() || token == ")") {
1129 lastline = string();
1133 // FIXME UNICODE: We assume that the file names in the log
1134 // file are in the file system encoding.
1135 token = to_utf8(from_filesystem8bit(token));
1137 // Sometimes, filenames are broken across lines.
1138 // We care for that and save suspicious lines.
1139 // Here we exclude some cases where we are sure
1140 // that there is no continued filename
1141 if (!lastline.empty()) {
1142 static regex const package_info("Package \\w+ Info: .*");
1143 static regex const package_warning("Package \\w+ Warning: .*");
1144 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1145 || prefixIs(token, "Package:")
1146 || prefixIs(token, "Language:")
1147 || prefixIs(token, "LaTeX Info:")
1148 || prefixIs(token, "LaTeX Font Info:")
1149 || prefixIs(token, "\\openout[")
1150 || prefixIs(token, "))")
1151 || regex_match(token, package_info)
1152 || regex_match(token, package_warning))
1153 lastline = string();
1156 if (!lastline.empty())
1157 // probably a continued filename from last line
1158 token = lastline + token;
1159 if (token.length() > 255) {
1160 // string too long. Cut off.
1161 token.erase(0, token.length() - 251);
1166 // (1) "File: file.ext"
1167 if (regex_match(token, sub, reg1)) {
1168 // is this a fragmental file name?
1169 fragment = !completeFilename(sub.str(1), head);
1171 if (suffixIs(token, ")"))
1172 // no fragment for sure
1174 // (2) "No file file.ext"
1175 } else if (regex_match(token, sub, reg2)) {
1176 // file names must contains a dot, line ends with dot
1177 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1178 fragment = !handleFoundFile(sub.str(1), head);
1180 // we suspect a line break
1182 // (3) "\openout<nr> = `file.ext'."
1183 } else if (regex_match(token, sub, reg3)) {
1184 // search for closing '. at the end of the line
1185 if (sub.str(2) == "\'.")
1186 fragment = !handleFoundFile(sub.str(1), head);
1188 // potential fragment
1190 // (4) "Writing index file file.ext"
1191 } else if (regex_match(token, sub, reg4))
1192 // fragmential file name?
1193 fragment = !completeFilename(sub.str(1), head);
1194 // (5) "Writing nomenclature file file.ext"
1195 else if (regex_match(token, sub, regnomencl) ||
1196 regex_match(token, sub, regoldnomencl))
1197 // fragmental file name?
1198 fragment= !completeFilename(sub.str(1), head);
1199 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1200 else if (regex_match(token, sub, miktexTocReg))
1201 fragment = !handleFoundFile(onlyFileName(changeExtension(
1202 file.absFileName(), ".toc")), head);
1204 // not found, but we won't check further
1207 int fragment_pos = -1;
1209 // We can have several of these on one line
1210 // (and in addition to those above)
1211 if (regex_match(token, sub, reg5)) {
1212 // search for strings in <...>
1213 static regex const reg5_1("<([^>]+)(.)");
1214 fragment_pos = iterateLine(token, reg5_1, ">",
1215 fragment_pos, head);
1216 fragment = (fragment_pos != -1);
1220 // We can have several of these on one line
1221 // this must be queried separated, because of
1222 // cases such as "File: file.ext (type eps)"
1223 // where "File: file.ext" would be skipped
1224 if (regex_match(token, sub, reg6)) {
1225 // search for strings in (...)
1226 static regex const reg6_1("\\(([^()]+)(.)");
1227 fragment_pos = iterateLine(token, reg6_1, ")",
1228 fragment_pos, head);
1229 fragment = (fragment_pos != -1);
1233 // probable linebreak within file name:
1237 // no linebreak: reset
1238 lastline = string();
1241 // Make sure that the main .tex file is in the dependency file.
1242 head.insert(file, true);
1246 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1248 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1249 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1251 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1253 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1254 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1255 static regex const bibtexError2("^(.*---while reading file).*$");
1256 static regex const bibtexError3("(A bad cross reference---).*");
1257 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1258 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1259 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1260 int retval = NO_ERRORS;
1263 while (getline(ifs, token)) {
1264 token = rtrim(token, "\r");
1266 // FIXME UNICODE: We assume that citation keys and filenames
1267 // in the aux file are in the file system encoding.
1268 token = to_utf8(from_filesystem8bit(token));
1269 if (regex_match(token, sub, reg1)) {
1270 string data = sub.str(3);
1271 if (!data.empty()) {
1272 LYXERR(Debug::LATEX, "Found bib file: " << data);
1273 handleFoundFile(data, dep);
1276 else if (regex_match(token, sub, bibtexError)
1277 || regex_match(token, sub, bibtexError2)
1278 || regex_match(token, sub, bibtexError4)
1279 || regex_match(token, sub, bibtexError5)) {
1280 retval |= BIBTEX_ERROR;
1281 string errstr = N_("BibTeX error: ") + token;
1283 if ((prefixIs(token, "while executing---line")
1284 || prefixIs(token, "---line ")
1285 || prefixIs(token, "*Please notify the BibTeX"))
1286 && !prevtoken.empty()) {
1287 errstr = N_("BibTeX error: ") + prevtoken;
1288 message = prevtoken + '\n';
1292 from_local8bit(errstr),
1293 from_local8bit(message));
1294 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1295 retval |= BIBTEX_ERROR;
1296 string errstr = N_("BibTeX error: ") + prevtoken;
1297 string message = prevtoken + '\n' + token;
1299 from_local8bit(errstr),
1300 from_local8bit(message));
1301 } else if (regex_match(token, sub, biberError)) {
1302 retval |= BIBTEX_ERROR;
1303 string errstr = N_("Biber error: ") + sub.str(2);
1304 string message = token;
1306 from_local8bit(errstr),
1307 from_local8bit(message));