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, string const & lp,
96 bool const clean_start)
97 : cmd(latex), file(f), path(p), lpath(lp), runparams(rp), biber(false)
100 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
101 depfile = FileName(file.absFileName() + ".dep-pdf");
103 FileName(changeExtension(file.absFileName(), ".pdf"));
105 depfile = FileName(file.absFileName() + ".dep");
107 FileName(changeExtension(file.absFileName(), ".dvi"));
110 removeAuxiliaryFiles();
114 void LaTeX::removeAuxiliaryFiles() const
116 // Note that we do not always call this function when there is an error.
117 // For example, if there is an error but an output file is produced we
118 // still would like to output (export/view) the file.
120 // What files do we have to delete?
122 // This will at least make latex do all the runs
123 depfile.removeFile();
125 // but the reason for the error might be in a generated file...
128 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
132 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
136 FileName const ind(changeExtension(file.absFileName(), ".ind"));
140 FileName const nls(changeExtension(file.absFileName(), ".nls"));
143 // nomencl file (old version of the package)
144 FileName const gls(changeExtension(file.absFileName(), ".gls"));
147 // Also remove the aux file
148 FileName const aux(changeExtension(file.absFileName(), ".aux"));
151 // Remove the output file, which is often generated even if error
152 output_file.removeFile();
156 int LaTeX::run(TeXErrors & terr)
157 // We know that this function will only be run if the lyx buffer
158 // has been changed. We also know that a newly written .tex file
159 // is always different from the previous one because of the date
160 // in it. However it seems safe to run latex (at least) one time
161 // each time the .tex file changes.
163 int scanres = NO_ERRORS;
164 int bscanres = NO_ERRORS;
165 unsigned int count = 0; // number of times run
166 num_errors = 0; // just to make sure.
167 unsigned int const MAX_RUN = 6;
168 DepTable head; // empty head
169 bool rerun = false; // rerun requested
171 // The class LaTeX does not know the temp path.
172 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
176 // first check if the file dependencies exist:
177 // ->If it does exist
178 // check if any of the files mentioned in it have
179 // changed (done using a checksum).
181 // run latex once and
182 // remake the dependency file
183 // -> if not changed:
184 // just return there is nothing to do for us.
185 // ->if it doesn't exist
187 // run latex once (we need to run latex once anyway) and
188 // remake the dependency file.
191 bool had_depfile = depfile.exists();
192 bool run_bibtex = false;
193 FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
196 LYXERR(Debug::DEPEND, "Dependency file exists");
197 // Read the dep file:
198 had_depfile = head.read(depfile);
202 // Update the checksums
204 // Can't just check if anything has changed because it might
205 // have aborted on error last time... in which cas we need
206 // to re-run latex and collect the error messages
207 // (even if they are the same).
208 if (!output_file.exists()) {
209 LYXERR(Debug::DEPEND,
210 "re-running LaTeX because output file doesn't exist.");
211 } else if (!head.sumchange()) {
212 LYXERR(Debug::DEPEND, "return no_change");
215 LYXERR(Debug::DEPEND, "Dependency file has changed");
218 if (head.extchanged(".bib") || head.extchanged(".bst"))
221 LYXERR(Debug::DEPEND,
222 "Dependency file does not exist, or has wrong format");
224 /// We scan the aux file even when had_depfile = false,
225 /// because we can run pdflatex on the file after running latex on it,
226 /// in which case we will not need to run bibtex again.
227 vector<AuxInfo> bibtex_info_old;
229 bibtex_info_old = scanAuxFiles(aux_file);
232 LYXERR(Debug::LATEX, "Run #" << count);
233 message(runMessage(count));
235 int const exit_code = startscript();
237 scanres = scanLogFile(terr);
238 if (scanres & ERROR_RERUN) {
239 LYXERR(Debug::LATEX, "Rerunning LaTeX");
241 scanres = scanLogFile(terr);
244 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
245 if (!run_bibtex && bibtex_info_old != bibtex_info)
248 // update the dependencies.
249 deplog(head); // reads the latex log
253 // At this point we must run external programs if needed.
254 // makeindex will be run if a .idx file changed or was generated.
255 // And if there were undefined citations or changes in references
256 // the .aux file is checked for signs of bibtex. Bibtex is then run
259 // memoir (at least) writes an empty *idx file in the first place.
260 // A second latex run is needed.
261 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
262 rerun = idxfile.exists() && idxfile.isFileEmpty();
265 if (head.haschanged(idxfile)) {
267 LYXERR(Debug::LATEX, "Running MakeIndex.");
268 message(_("Running Index Processor."));
269 // onlyFileName() is needed for cygwin
270 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
273 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
274 // If all nomencl entries are removed, nomencl writes an empty nlo file.
275 // DepTable::hasChanged() returns false in this case, since it does not
276 // distinguish empty files from non-existing files. This is why we need
277 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
278 // FIXME: Sort out the real problem in DepTable.
279 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
280 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
281 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
282 if (head.haschanged(glofile))
283 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
285 // check if we're using biber instead of bibtex
286 // biber writes no info to the aux file, so we just check
287 // if a bcf file exists (and if it was updated)
288 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
289 biber |= head.exist(bcffile);
292 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
293 if (scanres & UNDEF_CIT || run_bibtex) {
294 // Here we must scan the .aux file and look for
295 // "\bibdata" and/or "\bibstyle". If one of those
296 // tags is found -> run bibtex and set rerun = true;
298 LYXERR(Debug::LATEX, "Running BibTeX.");
299 message(_("Running BibTeX."));
300 updateBibtexDependencies(head, bibtex_info);
301 rerun |= runBibTeX(bibtex_info, runparams);
302 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
303 if (blgfile.exists())
304 bscanres = scanBlgFile(head, terr);
305 } else if (!had_depfile) {
306 /// If we run pdflatex on the file after running latex on it,
307 /// then we do not need to run bibtex, but we do need to
308 /// insert the .bib and .bst files into the .dep-pdf file.
309 updateBibtexDependencies(head, bibtex_info);
313 // we know on this point that latex has been run once (or we just
314 // returned) and the question now is to decide if we need to run
315 // it any more. This is done by asking if any of the files in the
316 // dependency file has changed. (remember that the checksum for
317 // a given file is reported to have changed if it just was created)
318 // -> if changed or rerun == true:
319 // run latex once more and
320 // update the dependency structure
321 // -> if not changed:
322 // we do nothing at this point
324 if (rerun || head.sumchange()) {
327 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
328 LYXERR(Debug::LATEX, "Run #" << count);
329 message(runMessage(count));
331 scanres = scanLogFile(terr);
333 // update the depedencies
334 deplog(head); // reads the latex log
337 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
342 // Complex bibliography packages such as Biblatex require
343 // an additional bibtex cycle sometimes.
344 if (scanres & UNDEF_CIT) {
345 // Here we must scan the .aux file and look for
346 // "\bibdata" and/or "\bibstyle". If one of those
347 // tags is found -> run bibtex and set rerun = true;
349 LYXERR(Debug::LATEX, "Running BibTeX.");
350 message(_("Running BibTeX."));
351 updateBibtexDependencies(head, bibtex_info);
352 rerun |= runBibTeX(bibtex_info, runparams);
353 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
354 if (blgfile.exists())
355 bscanres = scanBlgFile(head, terr);
359 // The inclusion of files generated by external programs such as
360 // makeindex or bibtex might have done changes to pagenumbering,
361 // etc. And because of this we must run the external programs
362 // again to make sure everything is redone correctly.
363 // Also there should be no need to run the external programs any
366 // run makeindex if the <file>.idx has changed or was generated.
367 if (head.haschanged(idxfile)) {
369 LYXERR(Debug::LATEX, "Running MakeIndex.");
370 message(_("Running Index Processor."));
371 // onlyFileName() is needed for cygwin
372 rerun = runMakeIndex(onlyFileName(changeExtension(
373 file.absFileName(), ".idx")), runparams);
376 // I am not pretty sure if need this twice.
377 if (head.haschanged(nlofile))
378 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
379 if (head.haschanged(glofile))
380 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
383 // we will only run latex more if the log file asks for it.
384 // or if the sumchange() is true.
385 // -> rerun asked for:
387 // remake the dependency file
388 // goto 2 or return if max runs are reached.
389 // -> rerun not asked for:
390 // just return (fall out of bottom of func)
392 while ((head.sumchange() || rerun || (scanres & RERUN))
393 && count < MAX_RUN) {
394 // Yes rerun until message goes away, or until
395 // MAX_RUNS are reached.
398 LYXERR(Debug::LATEX, "Run #" << count);
399 message(runMessage(count));
401 scanres = scanLogFile(terr);
407 // Write the dependencies to file.
411 scanres |= NONZERO_ERROR;
413 LYXERR(Debug::LATEX, "Done.");
415 if (bscanres & ERRORS)
416 return bscanres; // return on error
422 int LaTeX::startscript()
424 // onlyFileName() is needed for cygwin
425 string tmp = cmd + ' '
426 + quoteName(onlyFileName(file.toFilesystemEncoding()))
427 + " > " + os::nulldev();
429 return one.startscript(Systemcall::Wait, tmp, path, lpath);
433 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
434 string const & params)
436 string tmp = runparams.use_japanese ?
437 lyxrc.jindex_command : lyxrc.index_command;
439 if (!runparams.index_command.empty())
440 tmp = runparams.index_command;
443 "idx file has been made, running index processor ("
444 << tmp << ") on file " << f);
446 tmp = subst(tmp, "$$lang", runparams.document_language);
447 if (runparams.use_indices) {
448 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
450 "Multiple indices. Using splitindex command: " << tmp);
456 one.startscript(Systemcall::Wait, tmp, path, lpath);
461 bool LaTeX::runMakeIndexNomencl(FileName const & file,
462 string const & nlo, string const & nls)
464 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
465 message(_("Running MakeIndex for nomencl."));
466 string tmp = lyxrc.nomencl_command + ' ';
467 // onlyFileName() is needed for cygwin
468 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
470 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
472 one.startscript(Systemcall::Wait, tmp, path, lpath);
477 vector<AuxInfo> const
478 LaTeX::scanAuxFiles(FileName const & file)
480 vector<AuxInfo> result;
482 result.push_back(scanAuxFile(file));
484 string const basename = removeExtension(file.absFileName());
485 for (int i = 1; i < 1000; ++i) {
486 FileName const file2(basename
487 + '.' + convert<string>(i)
491 result.push_back(scanAuxFile(file2));
497 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
500 result.aux_file = file;
501 scanAuxFile(file, result);
506 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
508 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
510 ifstream ifs(file.toFilesystemEncoding().c_str());
512 static regex const reg1("\\\\citation\\{([^}]+)\\}");
513 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
514 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
515 static regex const reg4("\\\\@input\\{([^}]+)\\}");
517 while (getline(ifs, token)) {
518 token = rtrim(token, "\r");
520 // FIXME UNICODE: We assume that citation keys and filenames
521 // in the aux file are in the file system encoding.
522 token = to_utf8(from_filesystem8bit(token));
523 if (regex_match(token, sub, reg1)) {
524 string data = sub.str(1);
525 while (!data.empty()) {
527 data = split(data, citation, ',');
528 LYXERR(Debug::LATEX, "Citation: " << citation);
529 aux_info.citations.insert(citation);
531 } else if (regex_match(token, sub, reg2)) {
532 string data = sub.str(1);
533 // data is now all the bib files separated by ','
534 // get them one by one and pass them to the helper
535 while (!data.empty()) {
537 data = split(data, database, ',');
538 database = changeExtension(database, "bib");
539 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
540 aux_info.databases.insert(database);
542 } else if (regex_match(token, sub, reg3)) {
543 string style = sub.str(1);
544 // token is now the style file
545 // pass it to the helper
546 style = changeExtension(style, "bst");
547 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
548 aux_info.styles.insert(style);
549 } else if (regex_match(token, sub, reg4)) {
550 string const file2 = sub.str(1);
551 scanAuxFile(makeAbsPath(file2), aux_info);
557 void LaTeX::updateBibtexDependencies(DepTable & dep,
558 vector<AuxInfo> const & bibtex_info)
560 // Since a run of Bibtex mandates more latex runs it is ok to
561 // remove all ".bib" and ".bst" files.
562 dep.remove_files_with_extension(".bib");
563 dep.remove_files_with_extension(".bst");
564 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
566 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
567 it != bibtex_info.end(); ++it) {
568 for (set<string>::const_iterator it2 = it->databases.begin();
569 it2 != it->databases.end(); ++it2) {
570 FileName const file = findtexfile(*it2, "bib");
572 dep.insert(file, true);
575 for (set<string>::const_iterator it2 = it->styles.begin();
576 it2 != it->styles.end(); ++it2) {
577 FileName const file = findtexfile(*it2, "bst");
579 dep.insert(file, true);
583 // biber writes nothing into the aux file.
584 // Instead, we have to scan the blg file
587 scanBlgFile(dep, terr);
592 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
593 OutputParams const & runparams)
596 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
597 it != bibtex_info.end(); ++it) {
598 if (!biber && it->databases.empty())
602 string tmp = runparams.use_japanese ?
603 lyxrc.jbibtex_command : lyxrc.bibtex_command;
605 if (!runparams.bibtex_command.empty())
606 tmp = runparams.bibtex_command;
608 // onlyFileName() is needed for cygwin
609 tmp += quoteName(onlyFileName(removeExtension(
610 it->aux_file.absFileName())));
612 one.startscript(Systemcall::Wait, tmp, path, lpath);
614 // Return whether bibtex was run
619 int LaTeX::scanLogFile(TeXErrors & terr)
623 int retval = NO_ERRORS;
625 onlyFileName(changeExtension(file.absFileName(), ".log"));
626 LYXERR(Debug::LATEX, "Log file: " << tmp);
627 FileName const fn = FileName(makeAbsPath(tmp));
628 ifstream ifs(fn.toFilesystemEncoding().c_str());
629 bool fle_style = false;
630 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
631 static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
632 // Flag for 'File ended while scanning' message.
633 // We need to wait for subsequent processing.
634 string wait_for_error;
637 stack <pair<string, int> > child;
640 while (getline(ifs, token)) {
641 // MikTeX sometimes inserts \0 in the log file. They can't be
642 // removed directly with the existing string utility
643 // functions, so convert them first to \r, and remove all
644 // \r's afterwards, since we need to remove them anyway.
645 token = subst(token, '\0', '\r');
646 token = subst(token, "\r", "");
649 LYXERR(Debug::LATEX, "Log line: " << token);
654 // Track child documents
655 for (size_t i = 0; i < token.length(); ++i) {
656 if (token[i] == '(') {
658 size_t j = token.find('(', i + 1);
659 size_t len = j == string::npos
660 ? token.substr(i + 1).length()
662 string const substr = token.substr(i + 1, len);
663 if (regex_match(substr, sub, child_file)) {
664 string const name = sub.str(1);
665 child.push(make_pair(name, pnest));
668 } else if (token[i] == ')') {
670 && child.top().second == pnest)
675 child_name = child.empty() ? empty_string() : child.top().first;
677 if (contains(token, "file:line:error style messages enabled"))
680 if (prefixIs(token, "LaTeX Warning:") ||
681 prefixIs(token, "! pdfTeX warning")) {
682 // Here shall we handle different
684 retval |= LATEX_WARNING;
685 LYXERR(Debug::LATEX, "LaTeX Warning.");
686 if (contains(token, "Rerun to get cross-references")) {
688 LYXERR(Debug::LATEX, "We should rerun.");
689 // package clefval needs 2 latex runs before bibtex
690 } else if (contains(token, "Value of")
691 && contains(token, "on page")
692 && contains(token, "undefined")) {
693 retval |= ERROR_RERUN;
694 LYXERR(Debug::LATEX, "Force rerun.");
696 } else if (contains(token, "Etaremune labels have changed")) {
697 retval |= ERROR_RERUN;
698 LYXERR(Debug::LATEX, "Force rerun.");
699 } else if (contains(token, "Citation")
700 && contains(token, "on page")
701 && contains(token, "undefined")) {
703 } else if (contains(token, "Citation")
704 && contains(token, "on input line")
705 && contains(token, "undefined")) {
708 } else if (prefixIs(token, "Package")) {
710 retval |= PACKAGE_WARNING;
711 if (contains(token, "natbib Warning:")) {
713 if (contains(token, "Citation")
714 && contains(token, "on page")
715 && contains(token, "undefined")) {
718 } else if (contains(token, "run BibTeX")) {
720 } else if (contains(token, "run Biber")) {
723 } else if (contains(token, "Rerun LaTeX") ||
724 contains(token, "Please rerun LaTeX") ||
725 contains(token, "Rerun to get")) {
726 // at least longtable.sty and bibtopic.sty
728 LYXERR(Debug::LATEX, "We should rerun.");
731 } else if (prefixIs(token, "LETTRE WARNING:")) {
732 if (contains(token, "veuillez recompiler")) {
734 LYXERR(Debug::LATEX, "We should rerun.");
737 } else if (token[0] == '(') {
738 if (contains(token, "Rerun LaTeX") ||
739 contains(token, "Rerun to get")) {
741 LYXERR(Debug::LATEX, "We should rerun.");
744 } else if (prefixIs(token, "! ")
746 && regex_match(token, sub, file_line_error)
747 && !contains(token, "pdfTeX warning"))) {
748 // Ok, we have something that looks like a TeX Error
749 // but what do we really have.
751 // Just get the error description:
753 if (prefixIs(token, "! "))
754 desc = string(token, 2);
757 if (contains(token, "LaTeX Error:"))
758 retval |= LATEX_ERROR;
760 if (prefixIs(token, "! File ended while scanning")){
761 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
762 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
763 retval |= ERROR_RERUN;
764 LYXERR(Debug::LATEX, "Force rerun.");
766 // bug 6445. At this point its not clear we finish with error.
767 wait_for_error = desc;
772 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
773 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
774 retval |= ERROR_RERUN;
775 LYXERR(Debug::LATEX, "Force rerun.");
778 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
779 retval |= LATEX_ERROR;
782 errstr = wait_for_error;
784 if (!getline(ifs, tmp))
786 tmp = rtrim(tmp, "\r");
787 errstr += "\n" + tmp;
790 } while (!contains(tmp, "(job aborted"));
793 from_local8bit("Emergency stop"),
794 from_local8bit(errstr),
802 if (!getline(ifs, tmp))
804 tmp = rtrim(tmp, "\r");
805 // 15 is somewhat arbitrarily chosen, based on practice.
806 // We used 10 for 14 years and increased it to 15 when we
810 } while (!prefixIs(tmp, "l."));
811 if (prefixIs(tmp, "l.")) {
812 // we have a latex error
815 "Package babel Error: You haven't defined the language")
817 "Package babel Error: You haven't loaded the option")
819 "Package babel Error: Unknown language"))
820 retval |= ERROR_RERUN;
821 // get the line number:
823 sscanf(tmp.c_str(), "l.%d", &line);
824 // get the rest of the message:
825 string errstr(tmp, tmp.find(' '));
828 tmp = rtrim(tmp, "\r");
829 while (!contains(errstr, "l.")
831 && !prefixIs(tmp, "! ")
832 && !contains(tmp, "(job aborted")) {
836 tmp = rtrim(tmp, "\r");
838 LYXERR(Debug::LATEX, "line: " << line << '\n'
839 << "Desc: " << desc << '\n' << "Text: " << errstr);
840 if (line == last_line)
846 if (line_count <= 5) {
848 // We have no idea what the encoding of
850 // It seems that the output from the
851 // latex compiler itself is pure ASCII,
852 // but it can include bits from the
853 // document, so whatever encoding we
854 // assume here it can be wrong.
855 terr.insertError(line,
856 from_local8bit(desc),
857 from_local8bit(errstr),
863 // information messages, TeX warnings and other
864 // warnings we have not caught earlier.
865 if (prefixIs(token, "Overfull ")) {
866 retval |= TEX_WARNING;
867 } else if (prefixIs(token, "Underfull ")) {
868 retval |= TEX_WARNING;
869 } else if (contains(token, "Rerun to get citations")) {
870 // Natbib seems to use this.
872 } else if (contains(token, "No pages of output")) {
873 // A dvi file was not created
875 } else if (contains(token, "That makes 100 errors")) {
876 // More than 100 errors were reprted
877 retval |= TOO_MANY_ERRORS;
878 } else if (prefixIs(token, "!pdfTeX error:")) {
879 // otherwise we dont catch e.g.:
880 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
883 from_local8bit("pdfTeX Error"),
884 from_local8bit(token),
886 } else if (prefixIs(token, "Missing character: There is no ")) {
887 // XeTeX/LuaTeX error about missing glyph in selected font
889 retval |= LATEX_ERROR;
891 from_local8bit("Missing glyphs!"),
892 from_local8bit(token),
897 LYXERR(Debug::LATEX, "Log line: " << token);
904 bool insertIfExists(FileName const & absname, DepTable & head)
906 if (absname.exists() && !absname.isDirectory()) {
907 head.insert(absname, true);
914 bool handleFoundFile(string const & ff, DepTable & head)
916 // convert from native os path to unix path
917 string foundfile = os::internal_path(trim(ff));
919 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
921 // Ok now we found a file.
922 // Now we should make sure that this is a file that we can
923 // access through the normal paths.
924 // We will not try any fancy search methods to
927 // (1) foundfile is an
928 // absolute path and should
931 if (FileName::isAbsolute(foundfile)) {
932 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
933 // On initial insert we want to do the update at once
934 // since this file cannot be a file generated by
936 absname.set(foundfile);
937 if (!insertIfExists(absname, head)) {
939 string strippedfile = foundfile;
940 while (contains(strippedfile, " ")) {
941 // files with spaces are often enclosed in quotation
942 // marks; those have to be removed
943 string unquoted = subst(strippedfile, "\"", "");
944 absname.set(unquoted);
945 if (insertIfExists(absname, head))
947 // strip off part after last space and try again
948 string tmp = strippedfile;
949 string const stripoff =
950 rsplit(tmp, strippedfile, ' ');
951 absname.set(strippedfile);
952 if (insertIfExists(absname, head))
958 string onlyfile = onlyFileName(foundfile);
959 absname = makeAbsPath(onlyfile);
962 while (contains(foundfile, ' ')) {
963 if (absname.exists())
967 // files with spaces are often enclosed in quotation
968 // marks; those have to be removed
969 string unquoted = subst(foundfile, "\"", "");
970 absname = makeAbsPath(unquoted);
971 if (absname.exists())
973 // strip off part after last space and try again
975 string const stripoff =
976 rsplit(foundfile, strippedfile, ' ');
977 foundfile = strippedfile;
978 onlyfile = onlyFileName(strippedfile);
979 absname = makeAbsPath(onlyfile);
983 // (2) foundfile is in the tmpdir
984 // insert it into head
985 if (absname.exists() && !absname.isDirectory()) {
986 // FIXME: This regex contained glo, but glo is used by the old
987 // version of nomencl.sty. Do we need to put it back?
988 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
989 if (regex_match(onlyfile, unwanted)) {
990 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
991 << " in the dep file");
992 } else if (suffixIs(onlyfile, ".tex")) {
993 // This is a tex file generated by LyX
994 // and latex is not likely to change this
996 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
997 head.insert(absname, true);
999 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1000 head.insert(absname);
1004 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1010 bool completeFilename(string const & ff, DepTable & head)
1012 // If we do not find a dot, we suspect
1013 // a fragmental file name
1014 if (!contains(ff, '.'))
1017 // if we have a dot, we let handleFoundFile decide
1018 return handleFoundFile(ff, head);
1022 int iterateLine(string const & token, regex const & reg, string const & closing,
1023 int fragment_pos, DepTable & head)
1026 string::const_iterator first = token.begin();
1027 string::const_iterator end = token.end();
1028 bool fragment = false;
1031 while (regex_search(first, end, what, reg)) {
1032 // if we have a dot, try to handle as file
1033 if (contains(what.str(1), '.')) {
1034 first = what[0].second;
1035 if (what.str(2) == closing) {
1036 handleFoundFile(what.str(1), head);
1037 // since we had a closing bracket,
1038 // do not investigate further
1041 // if we have no closing bracket,
1042 // try to handle as file nevertheless
1043 fragment = !handleFoundFile(
1044 what.str(1) + what.str(2), head);
1046 // if we do not have a dot, check if the line has
1047 // a closing bracket (else, we suspect a line break)
1048 else if (what.str(2) != closing) {
1049 first = what[0].second;
1052 // we have a closing bracket, so the content
1053 // is not a file name.
1054 // no need to investigate further
1055 first = what[0].second;
1058 last_match = what.str(1);
1061 // We need to consider the result from previous line iterations:
1062 // We might not find a fragment here, but another one might follow
1063 // E.g.: (filename.ext) <filenam
1064 // Vice versa, we consider the search completed if a real match
1065 // follows a potential fragment from a previous iteration.
1066 // E.g. <some text we considered a fragment (filename.ext)
1067 // result = -1 means we did not find a fragment!
1069 int last_match_pos = -1;
1070 if (!last_match.empty() && token.find(last_match) != string::npos)
1071 last_match_pos = int(token.find(last_match));
1073 if (last_match_pos > fragment_pos)
1074 result = last_match_pos;
1076 result = fragment_pos;
1078 if (last_match_pos < fragment_pos)
1079 result = fragment_pos;
1087 void LaTeX::deplog(DepTable & head)
1089 // This function reads the LaTeX log file end extracts all the
1090 // external files used by the LaTeX run. The files are then
1091 // entered into the dependency file.
1093 string const logfile =
1094 onlyFileName(changeExtension(file.absFileName(), ".log"));
1096 static regex const reg1("File: (.+).*");
1097 static regex const reg2("No file (.+)(.).*");
1098 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1099 // If an index should be created, MikTex does not write a line like
1100 // \openout# = 'sample.idx'.
1101 // but instead only a line like this into the log:
1102 // Writing index file sample.idx
1103 static regex const reg4("Writing index file (.+).*");
1104 static regex const regoldnomencl("Writing glossary file (.+).*");
1105 static regex const regnomencl("Writing nomenclature file (.+).*");
1106 // If a toc should be created, MikTex does not write a line like
1107 // \openout# = `sample.toc'.
1108 // but only a line like this into the log:
1110 // This line is also written by tetex.
1111 // This line is not present if no toc should be created.
1112 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1113 // file names can be enclosed in <...> (anywhere on the line)
1114 static regex const reg5(".*<[^>]+.*");
1115 // and also (...) anywhere on the line
1116 static regex const reg6(".*\\([^)]+.*");
1118 FileName const fn = makeAbsPath(logfile);
1119 ifstream ifs(fn.toFilesystemEncoding().c_str());
1122 // Ok, the scanning of files here is not sufficient.
1123 // Sometimes files are named by "File: xxx" only
1124 // Therefore we use some regexps to find files instead.
1125 // Note: all file names and paths might contains spaces.
1126 // Also, file names might be broken across lines. Therefore
1127 // we mark (potential) fragments and merge those lines.
1128 bool fragment = false;
1130 getline(ifs, token);
1131 // MikTeX sometimes inserts \0 in the log file. They can't be
1132 // removed directly with the existing string utility
1133 // functions, so convert them first to \r, and remove all
1134 // \r's afterwards, since we need to remove them anyway.
1135 token = subst(token, '\0', '\r');
1136 token = subst(token, "\r", "");
1137 if (token.empty() || token == ")") {
1138 lastline = string();
1142 // FIXME UNICODE: We assume that the file names in the log
1143 // file are in the file system encoding.
1144 token = to_utf8(from_filesystem8bit(token));
1146 // Sometimes, filenames are broken across lines.
1147 // We care for that and save suspicious lines.
1148 // Here we exclude some cases where we are sure
1149 // that there is no continued filename
1150 if (!lastline.empty()) {
1151 static regex const package_info("Package \\w+ Info: .*");
1152 static regex const package_warning("Package \\w+ Warning: .*");
1153 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1154 || prefixIs(token, "Package:")
1155 || prefixIs(token, "Language:")
1156 || prefixIs(token, "LaTeX Info:")
1157 || prefixIs(token, "LaTeX Font Info:")
1158 || prefixIs(token, "\\openout[")
1159 || prefixIs(token, "))")
1160 || regex_match(token, package_info)
1161 || regex_match(token, package_warning))
1162 lastline = string();
1165 if (!lastline.empty())
1166 // probably a continued filename from last line
1167 token = lastline + token;
1168 if (token.length() > 255) {
1169 // string too long. Cut off.
1170 token.erase(0, token.length() - 251);
1175 // (1) "File: file.ext"
1176 if (regex_match(token, sub, reg1)) {
1177 // is this a fragmental file name?
1178 fragment = !completeFilename(sub.str(1), head);
1180 if (suffixIs(token, ")"))
1181 // no fragment for sure
1183 // (2) "No file file.ext"
1184 } else if (regex_match(token, sub, reg2)) {
1185 // file names must contains a dot, line ends with dot
1186 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1187 fragment = !handleFoundFile(sub.str(1), head);
1189 // we suspect a line break
1191 // (3) "\openout<nr> = `file.ext'."
1192 } else if (regex_match(token, sub, reg3)) {
1193 // search for closing '. at the end of the line
1194 if (sub.str(2) == "\'.")
1195 fragment = !handleFoundFile(sub.str(1), head);
1197 // potential fragment
1199 // (4) "Writing index file file.ext"
1200 } else if (regex_match(token, sub, reg4))
1201 // fragmential file name?
1202 fragment = !completeFilename(sub.str(1), head);
1203 // (5) "Writing nomenclature file file.ext"
1204 else if (regex_match(token, sub, regnomencl) ||
1205 regex_match(token, sub, regoldnomencl))
1206 // fragmental file name?
1207 fragment= !completeFilename(sub.str(1), head);
1208 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1209 else if (regex_match(token, sub, miktexTocReg))
1210 fragment = !handleFoundFile(onlyFileName(changeExtension(
1211 file.absFileName(), ".toc")), head);
1213 // not found, but we won't check further
1216 int fragment_pos = -1;
1218 // We can have several of these on one line
1219 // (and in addition to those above)
1220 if (regex_match(token, sub, reg5)) {
1221 // search for strings in <...>
1222 static regex const reg5_1("<([^>]+)(.)");
1223 fragment_pos = iterateLine(token, reg5_1, ">",
1224 fragment_pos, head);
1225 fragment = (fragment_pos != -1);
1229 // We can have several of these on one line
1230 // this must be queried separated, because of
1231 // cases such as "File: file.ext (type eps)"
1232 // where "File: file.ext" would be skipped
1233 if (regex_match(token, sub, reg6)) {
1234 // search for strings in (...)
1235 static regex const reg6_1("\\(([^()]+)(.)");
1236 fragment_pos = iterateLine(token, reg6_1, ")",
1237 fragment_pos, head);
1238 fragment = (fragment_pos != -1);
1242 // probable linebreak within file name:
1246 // no linebreak: reset
1247 lastline = string();
1250 // Make sure that the main .tex file is in the dependency file.
1251 head.insert(file, true);
1255 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1257 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1258 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1260 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1262 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1263 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1264 static regex const bibtexError2("^(.*---while reading file).*$");
1265 static regex const bibtexError3("(A bad cross reference---).*");
1266 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1267 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1268 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1269 int retval = NO_ERRORS;
1272 while (getline(ifs, token)) {
1273 token = rtrim(token, "\r");
1275 // FIXME UNICODE: We assume that citation keys and filenames
1276 // in the aux file are in the file system encoding.
1277 token = to_utf8(from_filesystem8bit(token));
1278 if (regex_match(token, sub, reg1)) {
1279 string data = sub.str(3);
1280 if (!data.empty()) {
1281 LYXERR(Debug::LATEX, "Found bib file: " << data);
1282 handleFoundFile(data, dep);
1285 else if (regex_match(token, sub, bibtexError)
1286 || regex_match(token, sub, bibtexError2)
1287 || regex_match(token, sub, bibtexError4)
1288 || regex_match(token, sub, bibtexError5)) {
1289 retval |= BIBTEX_ERROR;
1290 string errstr = N_("BibTeX error: ") + token;
1292 if ((prefixIs(token, "while executing---line")
1293 || prefixIs(token, "---line ")
1294 || prefixIs(token, "*Please notify the BibTeX"))
1295 && !prevtoken.empty()) {
1296 errstr = N_("BibTeX error: ") + prevtoken;
1297 message = prevtoken + '\n';
1301 from_local8bit(errstr),
1302 from_local8bit(message));
1303 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1304 retval |= BIBTEX_ERROR;
1305 string errstr = N_("BibTeX error: ") + prevtoken;
1306 string message = prevtoken + '\n' + token;
1308 from_local8bit(errstr),
1309 from_local8bit(message));
1310 } else if (regex_match(token, sub, biberError)) {
1311 retval |= BIBTEX_ERROR;
1312 string errstr = N_("Biber error: ") + sub.str(2);
1313 string message = token;
1315 from_local8bit(errstr),
1316 from_local8bit(message));