3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author Jürgen Spitzmüller
13 * Full author contact details are available in file CREDITS.
18 #include "BufferList.h"
23 #include "support/debug.h"
24 #include "support/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/gettext.h"
28 #include "support/lstrings.h"
29 #include "support/Systemcall.h"
30 #include "support/os.h"
32 #include "support/regex.h"
39 using namespace lyx::support;
43 namespace os = support::os;
45 // TODO: in no particular order
46 // - get rid of the call to
47 // BufferList::updateIncludedTeXfiles, this should either
48 // be done before calling LaTeX::funcs or in a completely
50 // - the makeindex style files should be taken care of with
51 // the dependency mechanism.
55 docstring runMessage(unsigned int count)
57 return bformat(_("Waiting for LaTeX run number %1$d"), count);
66 void TeXErrors::insertError(int line, docstring const & error_desc,
67 docstring const & error_text,
68 string const & child_name)
70 Error newerr(line, error_desc, error_text, child_name);
71 errors.push_back(newerr);
75 bool operator==(AuxInfo const & a, AuxInfo const & o)
77 return a.aux_file == o.aux_file
78 && a.citations == o.citations
79 && a.databases == o.databases
80 && a.styles == o.styles;
84 bool operator!=(AuxInfo const & a, AuxInfo const & o)
94 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
95 FileName const & f, string const & p)
96 : cmd(latex), file(f), path(p), runparams(rp), biber(false)
99 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
100 depfile = FileName(file.absFileName() + ".dep-pdf");
102 FileName(changeExtension(file.absFileName(), ".pdf"));
104 depfile = FileName(file.absFileName() + ".dep");
106 FileName(changeExtension(file.absFileName(), ".dvi"));
111 void LaTeX::deleteFilesOnError() const
113 // What files do we have to delete?
115 // This will at least make latex do all the runs
116 depfile.removeFile();
118 // but the reason for the error might be in a generated file...
121 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
125 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
129 FileName const ind(changeExtension(file.absFileName(), ".ind"));
133 FileName const nls(changeExtension(file.absFileName(), ".nls"));
136 // nomencl file (old version of the package)
137 FileName const gls(changeExtension(file.absFileName(), ".gls"));
140 // Also remove the aux file
141 FileName const aux(changeExtension(file.absFileName(), ".aux"));
144 // Remove the output file, which is often generated even if error
145 output_file.removeFile();
149 int LaTeX::run(TeXErrors & terr)
150 // We know that this function will only be run if the lyx buffer
151 // has been changed. We also know that a newly written .tex file
152 // is always different from the previous one because of the date
153 // in it. However it seems safe to run latex (at least) one time
154 // each time the .tex file changes.
156 int scanres = NO_ERRORS;
157 unsigned int count = 0; // number of times run
158 num_errors = 0; // just to make sure.
159 unsigned int const MAX_RUN = 6;
160 DepTable head; // empty head
161 bool rerun = false; // rerun requested
163 // The class LaTeX does not know the temp path.
164 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
167 // Never write the depfile if an error was encountered.
170 // first check if the file dependencies exist:
171 // ->If it does exist
172 // check if any of the files mentioned in it have
173 // changed (done using a checksum).
175 // run latex once and
176 // remake the dependency file
177 // -> if not changed:
178 // just return there is nothing to do for us.
179 // ->if it doesn't exist
181 // run latex once (we need to run latex once anyway) and
182 // remake the dependency file.
185 bool had_depfile = depfile.exists();
186 bool run_bibtex = false;
187 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
190 LYXERR(Debug::DEPEND, "Dependency file exists");
191 // Read the dep file:
192 had_depfile = head.read(depfile);
196 // Update the checksums
198 // Can't just check if anything has changed because it might
199 // have aborted on error last time... in which cas we need
200 // to re-run latex and collect the error messages
201 // (even if they are the same).
202 if (!output_file.exists()) {
203 LYXERR(Debug::DEPEND,
204 "re-running LaTeX because output file doesn't exist.");
205 } else if (!head.sumchange()) {
206 LYXERR(Debug::DEPEND, "return no_change");
209 LYXERR(Debug::DEPEND, "Dependency file has changed");
212 if (head.extchanged(".bib") || head.extchanged(".bst"))
215 LYXERR(Debug::DEPEND,
216 "Dependency file does not exist, or has wrong format");
218 /// We scan the aux file even when had_depfile = false,
219 /// because we can run pdflatex on the file after running latex on it,
220 /// in which case we will not need to run bibtex again.
221 vector<AuxInfo> bibtex_info_old;
223 bibtex_info_old = scanAuxFiles(aux_file);
226 LYXERR(Debug::LATEX, "Run #" << count);
227 message(runMessage(count));
229 int const exit_code = startscript();
231 scanres = scanLogFile(terr);
232 if (scanres & ERROR_RERUN) {
233 LYXERR(Debug::LATEX, "Rerunning LaTeX");
235 scanres = scanLogFile(terr);
238 if (scanres & ERRORS) {
239 deleteFilesOnError();
240 return scanres; // return on error
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 int bscanres = scanBlgFile(head, terr);
304 if (bscanres & ERRORS) {
305 deleteFilesOnError();
306 return bscanres; // return on error
309 } else if (!had_depfile) {
310 /// If we run pdflatex on the file after running latex on it,
311 /// then we do not need to run bibtex, but we do need to
312 /// insert the .bib and .bst files into the .dep-pdf file.
313 updateBibtexDependencies(head, bibtex_info);
317 // we know on this point that latex has been run once (or we just
318 // returned) and the question now is to decide if we need to run
319 // it any more. This is done by asking if any of the files in the
320 // dependency file has changed. (remember that the checksum for
321 // a given file is reported to have changed if it just was created)
322 // -> if changed or rerun == true:
323 // run latex once more and
324 // update the dependency structure
325 // -> if not changed:
326 // we do nothing at this point
328 if (rerun || head.sumchange()) {
331 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
332 LYXERR(Debug::LATEX, "Run #" << count);
333 message(runMessage(count));
335 scanres = scanLogFile(terr);
336 if (scanres & ERRORS) {
337 deleteFilesOnError();
338 return scanres; // return on error
341 // update the depedencies
342 deplog(head); // reads the latex log
345 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
350 // Complex bibliography packages such as Biblatex require
351 // an additional bibtex cycle sometimes.
352 if (scanres & UNDEF_CIT) {
353 // Here we must scan the .aux file and look for
354 // "\bibdata" and/or "\bibstyle". If one of those
355 // tags is found -> run bibtex and set rerun = true;
357 LYXERR(Debug::LATEX, "Running BibTeX.");
358 message(_("Running BibTeX."));
359 updateBibtexDependencies(head, bibtex_info);
360 rerun |= runBibTeX(bibtex_info, runparams);
361 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
362 if (blgfile.exists()) {
363 int bscanres = scanBlgFile(head, terr);
364 if (bscanres & ERRORS) {
365 deleteFilesOnError();
366 return bscanres; // return on error
372 // The inclusion of files generated by external programs such as
373 // makeindex or bibtex might have done changes to pagenumbering,
374 // etc. And because of this we must run the external programs
375 // again to make sure everything is redone correctly.
376 // Also there should be no need to run the external programs any
379 // run makeindex if the <file>.idx has changed or was generated.
380 if (head.haschanged(idxfile)) {
382 LYXERR(Debug::LATEX, "Running MakeIndex.");
383 message(_("Running Index Processor."));
384 // onlyFileName() is needed for cygwin
385 rerun = runMakeIndex(onlyFileName(changeExtension(
386 file.absFileName(), ".idx")), runparams);
389 // I am not pretty sure if need this twice.
390 if (head.haschanged(nlofile))
391 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
392 if (head.haschanged(glofile))
393 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
396 // we will only run latex more if the log file asks for it.
397 // or if the sumchange() is true.
398 // -> rerun asked for:
400 // remake the dependency file
401 // goto 2 or return if max runs are reached.
402 // -> rerun not asked for:
403 // just return (fall out of bottom of func)
405 while ((head.sumchange() || rerun || (scanres & RERUN))
406 && count < MAX_RUN) {
407 // Yes rerun until message goes away, or until
408 // MAX_RUNS are reached.
411 LYXERR(Debug::LATEX, "Run #" << count);
412 message(runMessage(count));
414 scanres = scanLogFile(terr);
415 if (scanres & ERRORS) {
416 deleteFilesOnError();
417 return scanres; // return on error
424 // Write the dependencies to file.
427 if (scanres & NO_OUTPUT) {
428 // A previous run could have left a PDF and since
429 // no PDF is created if NO_OUTPUT, we remove any
430 // existing PDF and temporary files so that an
431 // incorrect PDF is not displayed, which could otherwise
432 // happen if View is run again because the checksum will
433 // be the same so any lingering PDF will be viewed.
434 deleteFilesOnError();
438 scanres |= NONZERO_ERROR;
440 LYXERR(Debug::LATEX, "Done.");
445 int LaTeX::startscript()
447 // onlyFileName() is needed for cygwin
448 string tmp = cmd + ' '
449 + quoteName(onlyFileName(file.toFilesystemEncoding()))
450 + " > " + os::nulldev();
452 return one.startscript(Systemcall::Wait, tmp, path);
456 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
457 string const & params)
459 string tmp = runparams.use_japanese ?
460 lyxrc.jindex_command : lyxrc.index_command;
462 if (!runparams.index_command.empty())
463 tmp = runparams.index_command;
466 "idx file has been made, running index processor ("
467 << tmp << ") on file " << f);
469 tmp = subst(tmp, "$$lang", runparams.document_language);
470 if (runparams.use_indices) {
471 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
473 "Multiple indices. Using splitindex command: " << tmp);
479 one.startscript(Systemcall::Wait, tmp, path);
484 bool LaTeX::runMakeIndexNomencl(FileName const & file,
485 string const & nlo, string const & nls)
487 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
488 message(_("Running MakeIndex for nomencl."));
489 string tmp = lyxrc.nomencl_command + ' ';
490 // onlyFileName() is needed for cygwin
491 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
493 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
495 one.startscript(Systemcall::Wait, tmp, path);
500 vector<AuxInfo> const
501 LaTeX::scanAuxFiles(FileName const & file)
503 vector<AuxInfo> result;
505 result.push_back(scanAuxFile(file));
507 string const basename = removeExtension(file.absFileName());
508 for (int i = 1; i < 1000; ++i) {
509 FileName const file2(basename
510 + '.' + convert<string>(i)
514 result.push_back(scanAuxFile(file2));
520 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
523 result.aux_file = file;
524 scanAuxFile(file, result);
529 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
531 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
533 ifstream ifs(file.toFilesystemEncoding().c_str());
535 static regex const reg1("\\\\citation\\{([^}]+)\\}");
536 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
537 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
538 static regex const reg4("\\\\@input\\{([^}]+)\\}");
540 while (getline(ifs, token)) {
541 token = rtrim(token, "\r");
543 // FIXME UNICODE: We assume that citation keys and filenames
544 // in the aux file are in the file system encoding.
545 token = to_utf8(from_filesystem8bit(token));
546 if (regex_match(token, sub, reg1)) {
547 string data = sub.str(1);
548 while (!data.empty()) {
550 data = split(data, citation, ',');
551 LYXERR(Debug::LATEX, "Citation: " << citation);
552 aux_info.citations.insert(citation);
554 } else if (regex_match(token, sub, reg2)) {
555 string data = sub.str(1);
556 // data is now all the bib files separated by ','
557 // get them one by one and pass them to the helper
558 while (!data.empty()) {
560 data = split(data, database, ',');
561 database = changeExtension(database, "bib");
562 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
563 aux_info.databases.insert(database);
565 } else if (regex_match(token, sub, reg3)) {
566 string style = sub.str(1);
567 // token is now the style file
568 // pass it to the helper
569 style = changeExtension(style, "bst");
570 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
571 aux_info.styles.insert(style);
572 } else if (regex_match(token, sub, reg4)) {
573 string const file2 = sub.str(1);
574 scanAuxFile(makeAbsPath(file2), aux_info);
580 void LaTeX::updateBibtexDependencies(DepTable & dep,
581 vector<AuxInfo> const & bibtex_info)
583 // Since a run of Bibtex mandates more latex runs it is ok to
584 // remove all ".bib" and ".bst" files.
585 dep.remove_files_with_extension(".bib");
586 dep.remove_files_with_extension(".bst");
587 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
589 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
590 it != bibtex_info.end(); ++it) {
591 for (set<string>::const_iterator it2 = it->databases.begin();
592 it2 != it->databases.end(); ++it2) {
593 FileName const file = findtexfile(*it2, "bib");
595 dep.insert(file, true);
598 for (set<string>::const_iterator it2 = it->styles.begin();
599 it2 != it->styles.end(); ++it2) {
600 FileName const file = findtexfile(*it2, "bst");
602 dep.insert(file, true);
606 // biber writes nothing into the aux file.
607 // Instead, we have to scan the blg file
610 scanBlgFile(dep, terr);
615 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
616 OutputParams const & runparams)
619 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
620 it != bibtex_info.end(); ++it) {
621 if (!biber && it->databases.empty())
625 string tmp = runparams.use_japanese ?
626 lyxrc.jbibtex_command : lyxrc.bibtex_command;
628 if (!runparams.bibtex_command.empty())
629 tmp = runparams.bibtex_command;
631 // onlyFileName() is needed for cygwin
632 tmp += quoteName(onlyFileName(removeExtension(
633 it->aux_file.absFileName())));
635 one.startscript(Systemcall::Wait, tmp, path);
637 // Return whether bibtex was run
642 int LaTeX::scanLogFile(TeXErrors & terr)
646 int retval = NO_ERRORS;
648 onlyFileName(changeExtension(file.absFileName(), ".log"));
649 LYXERR(Debug::LATEX, "Log file: " << tmp);
650 FileName const fn = FileName(makeAbsPath(tmp));
651 ifstream ifs(fn.toFilesystemEncoding().c_str());
652 bool fle_style = false;
653 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
654 static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
655 // Flag for 'File ended while scanning' message.
656 // We need to wait for subsequent processing.
657 string wait_for_error;
660 stack <pair<string, int> > child;
663 while (getline(ifs, token)) {
664 // MikTeX sometimes inserts \0 in the log file. They can't be
665 // removed directly with the existing string utility
666 // functions, so convert them first to \r, and remove all
667 // \r's afterwards, since we need to remove them anyway.
668 token = subst(token, '\0', '\r');
669 token = subst(token, "\r", "");
672 LYXERR(Debug::LATEX, "Log line: " << token);
677 // Track child documents
678 for (size_t i = 0; i < token.length(); ++i) {
679 if (token[i] == '(') {
681 size_t j = token.find('(', i + 1);
682 size_t len = j == string::npos
683 ? token.substr(i + 1).length()
685 string const substr = token.substr(i + 1, len);
686 if (regex_match(substr, sub, child_file)) {
687 string const name = sub.str(1);
688 child.push(make_pair(name, pnest));
691 } else if (token[i] == ')') {
693 && child.top().second == pnest)
698 child_name = child.empty() ? empty_string() : child.top().first;
700 if (contains(token, "file:line:error style messages enabled"))
703 if (prefixIs(token, "LaTeX Warning:") ||
704 prefixIs(token, "! pdfTeX warning")) {
705 // Here shall we handle different
707 retval |= LATEX_WARNING;
708 LYXERR(Debug::LATEX, "LaTeX Warning.");
709 if (contains(token, "Rerun to get cross-references")) {
711 LYXERR(Debug::LATEX, "We should rerun.");
712 // package clefval needs 2 latex runs before bibtex
713 } else if (contains(token, "Value of")
714 && contains(token, "on page")
715 && contains(token, "undefined")) {
716 retval |= ERROR_RERUN;
717 LYXERR(Debug::LATEX, "Force rerun.");
719 } else if (contains(token, "Etaremune labels have changed")) {
720 retval |= ERROR_RERUN;
721 LYXERR(Debug::LATEX, "Force rerun.");
722 } else if (contains(token, "Citation")
723 && contains(token, "on page")
724 && contains(token, "undefined")) {
726 } else if (contains(token, "Citation")
727 && contains(token, "on input line")
728 && contains(token, "undefined")) {
731 } else if (prefixIs(token, "Package")) {
733 retval |= PACKAGE_WARNING;
734 if (contains(token, "natbib Warning:")) {
736 if (contains(token, "Citation")
737 && contains(token, "on page")
738 && contains(token, "undefined")) {
741 } else if (contains(token, "run BibTeX")) {
743 } else if (contains(token, "run Biber")) {
746 } else if (contains(token, "Rerun LaTeX") ||
747 contains(token, "Please rerun LaTeX") ||
748 contains(token, "Rerun to get")) {
749 // at least longtable.sty and bibtopic.sty
751 LYXERR(Debug::LATEX, "We should rerun.");
754 } else if (prefixIs(token, "LETTRE WARNING:")) {
755 if (contains(token, "veuillez recompiler")) {
757 LYXERR(Debug::LATEX, "We should rerun.");
760 } else if (token[0] == '(') {
761 if (contains(token, "Rerun LaTeX") ||
762 contains(token, "Rerun to get")) {
764 LYXERR(Debug::LATEX, "We should rerun.");
767 } else if (prefixIs(token, "! ")
769 && regex_match(token, sub, file_line_error)
770 && !contains(token, "pdfTeX warning"))) {
771 // Ok, we have something that looks like a TeX Error
772 // but what do we really have.
774 // Just get the error description:
776 if (prefixIs(token, "! "))
777 desc = string(token, 2);
780 if (contains(token, "LaTeX Error:"))
781 retval |= LATEX_ERROR;
783 if (prefixIs(token, "! File ended while scanning")){
784 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
785 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
786 retval |= ERROR_RERUN;
787 LYXERR(Debug::LATEX, "Force rerun.");
789 // bug 6445. At this point its not clear we finish with error.
790 wait_for_error = desc;
795 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
796 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
797 retval |= ERROR_RERUN;
798 LYXERR(Debug::LATEX, "Force rerun.");
801 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
802 retval |= LATEX_ERROR;
805 errstr = wait_for_error;
807 if (!getline(ifs, tmp))
809 tmp = rtrim(tmp, "\r");
810 errstr += "\n" + tmp;
813 } while (!contains(tmp, "(job aborted"));
816 from_local8bit("Emergency stop"),
817 from_local8bit(errstr),
825 if (!getline(ifs, tmp))
827 tmp = rtrim(tmp, "\r");
830 } while (!prefixIs(tmp, "l."));
831 if (prefixIs(tmp, "l.")) {
832 // we have a latex error
835 "Package babel Error: You haven't defined the language")
837 "Package babel Error: You haven't loaded the option")
839 "Package babel Error: Unknown language"))
840 retval |= ERROR_RERUN;
841 // get the line number:
843 sscanf(tmp.c_str(), "l.%d", &line);
844 // get the rest of the message:
845 string errstr(tmp, tmp.find(' '));
848 tmp = rtrim(tmp, "\r");
849 while (!contains(errstr, "l.")
851 && !prefixIs(tmp, "! ")
852 && !contains(tmp, "(job aborted")) {
856 tmp = rtrim(tmp, "\r");
858 LYXERR(Debug::LATEX, "line: " << line << '\n'
859 << "Desc: " << desc << '\n' << "Text: " << errstr);
860 if (line == last_line)
866 if (line_count <= 5) {
868 // We have no idea what the encoding of
870 // It seems that the output from the
871 // latex compiler itself is pure ASCII,
872 // but it can include bits from the
873 // document, so whatever encoding we
874 // assume here it can be wrong.
875 terr.insertError(line,
876 from_local8bit(desc),
877 from_local8bit(errstr),
883 // information messages, TeX warnings and other
884 // warnings we have not caught earlier.
885 if (prefixIs(token, "Overfull ")) {
886 retval |= TEX_WARNING;
887 } else if (prefixIs(token, "Underfull ")) {
888 retval |= TEX_WARNING;
889 } else if (contains(token, "Rerun to get citations")) {
890 // Natbib seems to use this.
892 } else if (contains(token, "No pages of output")) {
893 // A dvi file was not created
895 } else if (contains(token, "That makes 100 errors")) {
896 // More than 100 errors were reprted
897 retval |= TOO_MANY_ERRORS;
898 } else if (prefixIs(token, "!pdfTeX error:")){
899 // otherwise we dont catch e.g.:
900 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
903 from_local8bit("pdfTeX Error"),
904 from_local8bit(token),
909 LYXERR(Debug::LATEX, "Log line: " << token);
916 bool insertIfExists(FileName const & absname, DepTable & head)
918 if (absname.exists() && !absname.isDirectory()) {
919 head.insert(absname, true);
926 bool handleFoundFile(string const & ff, DepTable & head)
928 // convert from native os path to unix path
929 string foundfile = os::internal_path(trim(ff));
931 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
933 // Ok now we found a file.
934 // Now we should make sure that this is a file that we can
935 // access through the normal paths.
936 // We will not try any fancy search methods to
939 // (1) foundfile is an
940 // absolute path and should
943 if (FileName::isAbsolute(foundfile)) {
944 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
945 // On initial insert we want to do the update at once
946 // since this file cannot be a file generated by
948 absname.set(foundfile);
949 if (!insertIfExists(absname, head)) {
951 string strippedfile = foundfile;
952 while (contains(strippedfile, " ")) {
953 // files with spaces are often enclosed in quotation
954 // marks; those have to be removed
955 string unquoted = subst(strippedfile, "\"", "");
956 absname.set(unquoted);
957 if (insertIfExists(absname, head))
959 // strip off part after last space and try again
960 string tmp = strippedfile;
961 string const stripoff =
962 rsplit(tmp, strippedfile, ' ');
963 absname.set(strippedfile);
964 if (insertIfExists(absname, head))
970 string onlyfile = onlyFileName(foundfile);
971 absname = makeAbsPath(onlyfile);
974 while (contains(foundfile, ' ')) {
975 if (absname.exists())
979 // files with spaces are often enclosed in quotation
980 // marks; those have to be removed
981 string unquoted = subst(foundfile, "\"", "");
982 absname = makeAbsPath(unquoted);
983 if (absname.exists())
985 // strip off part after last space and try again
987 string const stripoff =
988 rsplit(foundfile, strippedfile, ' ');
989 foundfile = strippedfile;
990 onlyfile = onlyFileName(strippedfile);
991 absname = makeAbsPath(onlyfile);
995 // (2) foundfile is in the tmpdir
996 // insert it into head
997 if (absname.exists() && !absname.isDirectory()) {
998 // FIXME: This regex contained glo, but glo is used by the old
999 // version of nomencl.sty. Do we need to put it back?
1000 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1001 if (regex_match(onlyfile, unwanted)) {
1002 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1003 << " in the dep file");
1004 } else if (suffixIs(onlyfile, ".tex")) {
1005 // This is a tex file generated by LyX
1006 // and latex is not likely to change this
1008 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1009 head.insert(absname, true);
1011 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1012 head.insert(absname);
1016 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1022 bool completeFilename(string const & ff, DepTable & head)
1024 // If we do not find a dot, we suspect
1025 // a fragmental file name
1026 if (!contains(ff, '.'))
1029 // if we have a dot, we let handleFoundFile decide
1030 return handleFoundFile(ff, head);
1034 int iterateLine(string const & token, regex const & reg, string const & closing,
1035 int fragment_pos, DepTable & head)
1038 string::const_iterator first = token.begin();
1039 string::const_iterator end = token.end();
1040 bool fragment = false;
1043 while (regex_search(first, end, what, reg)) {
1044 // if we have a dot, try to handle as file
1045 if (contains(what.str(1), '.')) {
1046 first = what[0].second;
1047 if (what.str(2) == closing) {
1048 handleFoundFile(what.str(1), head);
1049 // since we had a closing bracket,
1050 // do not investigate further
1053 // if we have no closing bracket,
1054 // try to handle as file nevertheless
1055 fragment = !handleFoundFile(
1056 what.str(1) + what.str(2), head);
1058 // if we do not have a dot, check if the line has
1059 // a closing bracket (else, we suspect a line break)
1060 else if (what.str(2) != closing) {
1061 first = what[0].second;
1064 // we have a closing bracket, so the content
1065 // is not a file name.
1066 // no need to investigate further
1067 first = what[0].second;
1070 last_match = what.str(1);
1073 // We need to consider the result from previous line iterations:
1074 // We might not find a fragment here, but another one might follow
1075 // E.g.: (filename.ext) <filenam
1076 // Vice versa, we consider the search completed if a real match
1077 // follows a potential fragment from a previous iteration.
1078 // E.g. <some text we considered a fragment (filename.ext)
1079 // result = -1 means we did not find a fragment!
1081 int last_match_pos = -1;
1082 if (!last_match.empty() && token.find(last_match) != string::npos)
1083 last_match_pos = int(token.find(last_match));
1085 if (last_match_pos > fragment_pos)
1086 result = last_match_pos;
1088 result = fragment_pos;
1090 if (last_match_pos < fragment_pos)
1091 result = fragment_pos;
1099 void LaTeX::deplog(DepTable & head)
1101 // This function reads the LaTeX log file end extracts all the
1102 // external files used by the LaTeX run. The files are then
1103 // entered into the dependency file.
1105 string const logfile =
1106 onlyFileName(changeExtension(file.absFileName(), ".log"));
1108 static regex const reg1("File: (.+).*");
1109 static regex const reg2("No file (.+)(.).*");
1110 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1111 // If an index should be created, MikTex does not write a line like
1112 // \openout# = 'sample.idx'.
1113 // but instead only a line like this into the log:
1114 // Writing index file sample.idx
1115 static regex const reg4("Writing index file (.+).*");
1116 static regex const regoldnomencl("Writing glossary file (.+).*");
1117 static regex const regnomencl("Writing nomenclature file (.+).*");
1118 // If a toc should be created, MikTex does not write a line like
1119 // \openout# = `sample.toc'.
1120 // but only a line like this into the log:
1122 // This line is also written by tetex.
1123 // This line is not present if no toc should be created.
1124 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1125 // file names can be enclosed in <...> (anywhere on the line)
1126 static regex const reg5(".*<[^>]+.*");
1127 // and also (...) anywhere on the line
1128 static regex const reg6(".*\\([^)]+.*");
1130 FileName const fn = makeAbsPath(logfile);
1131 ifstream ifs(fn.toFilesystemEncoding().c_str());
1134 // Ok, the scanning of files here is not sufficient.
1135 // Sometimes files are named by "File: xxx" only
1136 // Therefore we use some regexps to find files instead.
1137 // Note: all file names and paths might contains spaces.
1138 // Also, file names might be broken across lines. Therefore
1139 // we mark (potential) fragments and merge those lines.
1140 bool fragment = false;
1142 getline(ifs, token);
1143 // MikTeX sometimes inserts \0 in the log file. They can't be
1144 // removed directly with the existing string utility
1145 // functions, so convert them first to \r, and remove all
1146 // \r's afterwards, since we need to remove them anyway.
1147 token = subst(token, '\0', '\r');
1148 token = subst(token, "\r", "");
1149 if (token.empty() || token == ")") {
1150 lastline = string();
1154 // FIXME UNICODE: We assume that the file names in the log
1155 // file are in the file system encoding.
1156 token = to_utf8(from_filesystem8bit(token));
1158 // Sometimes, filenames are broken across lines.
1159 // We care for that and save suspicious lines.
1160 // Here we exclude some cases where we are sure
1161 // that there is no continued filename
1162 if (!lastline.empty()) {
1163 static regex const package_info("Package \\w+ Info: .*");
1164 static regex const package_warning("Package \\w+ Warning: .*");
1165 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1166 || prefixIs(token, "Package:")
1167 || prefixIs(token, "Language:")
1168 || prefixIs(token, "LaTeX Info:")
1169 || prefixIs(token, "LaTeX Font Info:")
1170 || prefixIs(token, "\\openout[")
1171 || prefixIs(token, "))")
1172 || regex_match(token, package_info)
1173 || regex_match(token, package_warning))
1174 lastline = string();
1177 if (!lastline.empty())
1178 // probably a continued filename from last line
1179 token = lastline + token;
1180 if (token.length() > 255) {
1181 // string too long. Cut off.
1182 token.erase(0, token.length() - 251);
1187 // (1) "File: file.ext"
1188 if (regex_match(token, sub, reg1)) {
1189 // is this a fragmental file name?
1190 fragment = !completeFilename(sub.str(1), head);
1192 if (suffixIs(token, ")"))
1193 // no fragment for sure
1195 // (2) "No file file.ext"
1196 } else if (regex_match(token, sub, reg2)) {
1197 // file names must contains a dot, line ends with dot
1198 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1199 fragment = !handleFoundFile(sub.str(1), head);
1201 // we suspect a line break
1203 // (3) "\openout<nr> = `file.ext'."
1204 } else if (regex_match(token, sub, reg3)) {
1205 // search for closing '. at the end of the line
1206 if (sub.str(2) == "\'.")
1207 fragment = !handleFoundFile(sub.str(1), head);
1209 // potential fragment
1211 // (4) "Writing index file file.ext"
1212 } else if (regex_match(token, sub, reg4))
1213 // fragmential file name?
1214 fragment = !completeFilename(sub.str(1), head);
1215 // (5) "Writing nomenclature file file.ext"
1216 else if (regex_match(token, sub, regnomencl) ||
1217 regex_match(token, sub, regoldnomencl))
1218 // fragmental file name?
1219 fragment= !completeFilename(sub.str(1), head);
1220 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1221 else if (regex_match(token, sub, miktexTocReg))
1222 fragment = !handleFoundFile(onlyFileName(changeExtension(
1223 file.absFileName(), ".toc")), head);
1225 // not found, but we won't check further
1228 int fragment_pos = -1;
1230 // We can have several of these on one line
1231 // (and in addition to those above)
1232 if (regex_match(token, sub, reg5)) {
1233 // search for strings in <...>
1234 static regex const reg5_1("<([^>]+)(.)");
1235 fragment_pos = iterateLine(token, reg5_1, ">",
1236 fragment_pos, head);
1237 fragment = (fragment_pos != -1);
1241 // We can have several of these on one line
1242 // this must be queried separated, because of
1243 // cases such as "File: file.ext (type eps)"
1244 // where "File: file.ext" would be skipped
1245 if (regex_match(token, sub, reg6)) {
1246 // search for strings in (...)
1247 static regex const reg6_1("\\(([^()]+)(.)");
1248 fragment_pos = iterateLine(token, reg6_1, ")",
1249 fragment_pos, head);
1250 fragment = (fragment_pos != -1);
1254 // probable linebreak within file name:
1258 // no linebreak: reset
1259 lastline = string();
1262 // Make sure that the main .tex file is in the dependency file.
1263 head.insert(file, true);
1267 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1269 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1270 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1272 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1274 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1275 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1276 static regex const bibtexError2("^(.*---while reading file).*$");
1277 static regex const bibtexError3("(A bad cross reference---).*");
1278 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1279 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1280 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1281 int retval = NO_ERRORS;
1284 while (getline(ifs, token)) {
1285 token = rtrim(token, "\r");
1287 // FIXME UNICODE: We assume that citation keys and filenames
1288 // in the aux file are in the file system encoding.
1289 token = to_utf8(from_filesystem8bit(token));
1290 if (regex_match(token, sub, reg1)) {
1291 string data = sub.str(3);
1292 if (!data.empty()) {
1293 LYXERR(Debug::LATEX, "Found bib file: " << data);
1294 handleFoundFile(data, dep);
1297 else if (regex_match(token, sub, bibtexError)
1298 || regex_match(token, sub, bibtexError2)
1299 || regex_match(token, sub, bibtexError4)
1300 || regex_match(token, sub, bibtexError5)) {
1301 retval |= BIBTEX_ERROR;
1302 string errstr = N_("BibTeX error: ") + token;
1304 if ((prefixIs(token, "while executing---line")
1305 || prefixIs(token, "---line ")
1306 || prefixIs(token, "*Please notify the BibTeX"))
1307 && !prevtoken.empty()) {
1308 errstr = N_("BibTeX error: ") + prevtoken;
1309 message = prevtoken + '\n';
1313 from_local8bit(errstr),
1314 from_local8bit(message));
1315 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1316 retval |= BIBTEX_ERROR;
1317 string errstr = N_("BibTeX error: ") + prevtoken;
1318 string message = prevtoken + '\n' + token;
1320 from_local8bit(errstr),
1321 from_local8bit(message));
1322 } else if (regex_match(token, sub, biberError)) {
1323 retval |= BIBTEX_ERROR;
1324 string errstr = N_("Biber error: ") + sub.str(2);
1325 string message = token;
1327 from_local8bit(errstr),
1328 from_local8bit(message));