3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author Jürgen Spitzmüller
13 * Full author contact details are available in file CREDITS.
18 #include "BufferList.h"
23 #include "support/debug.h"
24 #include "support/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/gettext.h"
28 #include "support/lstrings.h"
29 #include "support/Systemcall.h"
30 #include "support/os.h"
32 #include "support/regex.h"
39 using namespace lyx::support;
43 namespace os = support::os;
45 // TODO: in no particular order
46 // - get rid of the call to
47 // BufferList::updateIncludedTeXfiles, this should either
48 // be done before calling LaTeX::funcs or in a completely
50 // - the makeindex style files should be taken care of with
51 // the dependency mechanism.
55 docstring runMessage(unsigned int count)
57 return bformat(_("Waiting for LaTeX run number %1$d"), count);
66 void TeXErrors::insertError(int line, docstring const & error_desc,
67 docstring const & error_text,
68 string const & child_name)
70 Error newerr(line, error_desc, error_text, child_name);
71 errors.push_back(newerr);
75 bool operator==(AuxInfo const & a, AuxInfo const & o)
77 return a.aux_file == o.aux_file
78 && a.citations == o.citations
79 && a.databases == o.databases
80 && a.styles == o.styles;
84 bool operator!=(AuxInfo const & a, AuxInfo const & o)
94 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
95 FileName const & f, string const & p)
96 : cmd(latex), file(f), path(p), runparams(rp), biber(false)
99 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
100 depfile = FileName(file.absFileName() + ".dep-pdf");
102 FileName(changeExtension(file.absFileName(), ".pdf"));
104 depfile = FileName(file.absFileName() + ".dep");
106 FileName(changeExtension(file.absFileName(), ".dvi"));
111 void LaTeX::deleteFilesOnError() const
113 // Note that we do not always call this function when there is an error.
114 // For example, if there is an error but an output file is produced we
115 // still would like to output (export/view) the file.
117 // What files do we have to delete?
119 // This will at least make latex do all the runs
120 depfile.removeFile();
122 // but the reason for the error might be in a generated file...
125 FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
129 FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
133 FileName const ind(changeExtension(file.absFileName(), ".ind"));
137 FileName const nls(changeExtension(file.absFileName(), ".nls"));
140 // nomencl file (old version of the package)
141 FileName const gls(changeExtension(file.absFileName(), ".gls"));
144 // Also remove the aux file
145 FileName const aux(changeExtension(file.absFileName(), ".aux"));
148 // Remove the output file, which is often generated even if error
149 output_file.removeFile();
153 int LaTeX::run(TeXErrors & terr)
154 // We know that this function will only be run if the lyx buffer
155 // has been changed. We also know that a newly written .tex file
156 // is always different from the previous one because of the date
157 // in it. However it seems safe to run latex (at least) one time
158 // each time the .tex file changes.
160 int scanres = NO_ERRORS;
161 int bscanres = NO_ERRORS;
162 unsigned int count = 0; // number of times run
163 num_errors = 0; // just to make sure.
164 unsigned int const MAX_RUN = 6;
165 DepTable head; // empty head
166 bool rerun = false; // rerun requested
168 // The class LaTeX does not know the temp path.
169 theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
172 // Never write the depfile if an error was encountered.
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 if (scanres & ERRORS) {
244 // We no longer run deleteFilesOnError() here
245 // because we now show a resulting PDF even if
246 // there was an error.
247 return scanres; // return on error
250 vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
251 if (!run_bibtex && bibtex_info_old != bibtex_info)
254 // update the dependencies.
255 deplog(head); // reads the latex log
259 // At this point we must run external programs if needed.
260 // makeindex will be run if a .idx file changed or was generated.
261 // And if there were undefined citations or changes in references
262 // the .aux file is checked for signs of bibtex. Bibtex is then run
265 // memoir (at least) writes an empty *idx file in the first place.
266 // A second latex run is needed.
267 FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
268 rerun = idxfile.exists() && idxfile.isFileEmpty();
271 if (head.haschanged(idxfile)) {
273 LYXERR(Debug::LATEX, "Running MakeIndex.");
274 message(_("Running Index Processor."));
275 // onlyFileName() is needed for cygwin
276 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
279 FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
280 // If all nomencl entries are removed, nomencl writes an empty nlo file.
281 // DepTable::hasChanged() returns false in this case, since it does not
282 // distinguish empty files from non-existing files. This is why we need
283 // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
284 // FIXME: Sort out the real problem in DepTable.
285 if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
286 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
287 FileName const glofile(changeExtension(file.absFileName(), ".glo"));
288 if (head.haschanged(glofile))
289 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
291 // check if we're using biber instead of bibtex
292 // biber writes no info to the aux file, so we just check
293 // if a bcf file exists (and if it was updated)
294 FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
295 biber |= head.exist(bcffile);
298 // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
299 if (scanres & UNDEF_CIT || run_bibtex) {
300 // Here we must scan the .aux file and look for
301 // "\bibdata" and/or "\bibstyle". If one of those
302 // tags is found -> run bibtex and set rerun = true;
304 LYXERR(Debug::LATEX, "Running BibTeX.");
305 message(_("Running BibTeX."));
306 updateBibtexDependencies(head, bibtex_info);
307 rerun |= runBibTeX(bibtex_info, runparams);
308 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
309 if (blgfile.exists())
310 bscanres = scanBlgFile(head, terr);
311 } else if (!had_depfile) {
312 /// If we run pdflatex on the file after running latex on it,
313 /// then we do not need to run bibtex, but we do need to
314 /// insert the .bib and .bst files into the .dep-pdf file.
315 updateBibtexDependencies(head, bibtex_info);
319 // we know on this point that latex has been run once (or we just
320 // returned) and the question now is to decide if we need to run
321 // it any more. This is done by asking if any of the files in the
322 // dependency file has changed. (remember that the checksum for
323 // a given file is reported to have changed if it just was created)
324 // -> if changed or rerun == true:
325 // run latex once more and
326 // update the dependency structure
327 // -> if not changed:
328 // we do nothing at this point
330 if (rerun || head.sumchange()) {
333 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
334 LYXERR(Debug::LATEX, "Run #" << count);
335 message(runMessage(count));
337 scanres = scanLogFile(terr);
338 if (scanres & ERRORS)
339 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 bscanres = scanBlgFile(head, terr);
367 // The inclusion of files generated by external programs such as
368 // makeindex or bibtex might have done changes to pagenumbering,
369 // etc. And because of this we must run the external programs
370 // again to make sure everything is redone correctly.
371 // Also there should be no need to run the external programs any
374 // run makeindex if the <file>.idx has changed or was generated.
375 if (head.haschanged(idxfile)) {
377 LYXERR(Debug::LATEX, "Running MakeIndex.");
378 message(_("Running Index Processor."));
379 // onlyFileName() is needed for cygwin
380 rerun = runMakeIndex(onlyFileName(changeExtension(
381 file.absFileName(), ".idx")), runparams);
384 // I am not pretty sure if need this twice.
385 if (head.haschanged(nlofile))
386 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
387 if (head.haschanged(glofile))
388 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
391 // we will only run latex more if the log file asks for it.
392 // or if the sumchange() is true.
393 // -> rerun asked for:
395 // remake the dependency file
396 // goto 2 or return if max runs are reached.
397 // -> rerun not asked for:
398 // just return (fall out of bottom of func)
400 while ((head.sumchange() || rerun || (scanres & RERUN))
401 && count < MAX_RUN) {
402 // Yes rerun until message goes away, or until
403 // MAX_RUNS are reached.
406 LYXERR(Debug::LATEX, "Run #" << count);
407 message(runMessage(count));
409 scanres = scanLogFile(terr);
410 if (scanres & ERRORS)
411 return scanres; // return on error
417 // Write the dependencies to file.
420 if (scanres & NO_OUTPUT) {
421 // A previous run could have left a PDF and since
422 // no PDF is created if NO_OUTPUT, we remove any
423 // existing PDF and temporary files so that an
424 // incorrect PDF is not displayed, which could otherwise
425 // happen if View is run again because the checksum will
426 // be the same so any lingering PDF will be viewed.
427 deleteFilesOnError();
431 scanres |= NONZERO_ERROR;
433 LYXERR(Debug::LATEX, "Done.");
435 if (bscanres & ERRORS)
436 return bscanres; // return on error
442 int LaTeX::startscript()
444 // onlyFileName() is needed for cygwin
445 string tmp = cmd + ' '
446 + quoteName(onlyFileName(file.toFilesystemEncoding()))
447 + " > " + os::nulldev();
449 return one.startscript(Systemcall::Wait, tmp, path);
453 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
454 string const & params)
456 string tmp = runparams.use_japanese ?
457 lyxrc.jindex_command : lyxrc.index_command;
459 if (!runparams.index_command.empty())
460 tmp = runparams.index_command;
463 "idx file has been made, running index processor ("
464 << tmp << ") on file " << f);
466 tmp = subst(tmp, "$$lang", runparams.document_language);
467 if (runparams.use_indices) {
468 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
470 "Multiple indices. Using splitindex command: " << tmp);
476 one.startscript(Systemcall::Wait, tmp, path);
481 bool LaTeX::runMakeIndexNomencl(FileName const & file,
482 string const & nlo, string const & nls)
484 LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
485 message(_("Running MakeIndex for nomencl."));
486 string tmp = lyxrc.nomencl_command + ' ';
487 // onlyFileName() is needed for cygwin
488 tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
490 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
492 one.startscript(Systemcall::Wait, tmp, path);
497 vector<AuxInfo> const
498 LaTeX::scanAuxFiles(FileName const & file)
500 vector<AuxInfo> result;
502 result.push_back(scanAuxFile(file));
504 string const basename = removeExtension(file.absFileName());
505 for (int i = 1; i < 1000; ++i) {
506 FileName const file2(basename
507 + '.' + convert<string>(i)
511 result.push_back(scanAuxFile(file2));
517 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
520 result.aux_file = file;
521 scanAuxFile(file, result);
526 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
528 LYXERR(Debug::LATEX, "Scanning aux file: " << file);
530 ifstream ifs(file.toFilesystemEncoding().c_str());
532 static regex const reg1("\\\\citation\\{([^}]+)\\}");
533 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
534 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
535 static regex const reg4("\\\\@input\\{([^}]+)\\}");
537 while (getline(ifs, token)) {
538 token = rtrim(token, "\r");
540 // FIXME UNICODE: We assume that citation keys and filenames
541 // in the aux file are in the file system encoding.
542 token = to_utf8(from_filesystem8bit(token));
543 if (regex_match(token, sub, reg1)) {
544 string data = sub.str(1);
545 while (!data.empty()) {
547 data = split(data, citation, ',');
548 LYXERR(Debug::LATEX, "Citation: " << citation);
549 aux_info.citations.insert(citation);
551 } else if (regex_match(token, sub, reg2)) {
552 string data = sub.str(1);
553 // data is now all the bib files separated by ','
554 // get them one by one and pass them to the helper
555 while (!data.empty()) {
557 data = split(data, database, ',');
558 database = changeExtension(database, "bib");
559 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
560 aux_info.databases.insert(database);
562 } else if (regex_match(token, sub, reg3)) {
563 string style = sub.str(1);
564 // token is now the style file
565 // pass it to the helper
566 style = changeExtension(style, "bst");
567 LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
568 aux_info.styles.insert(style);
569 } else if (regex_match(token, sub, reg4)) {
570 string const file2 = sub.str(1);
571 scanAuxFile(makeAbsPath(file2), aux_info);
577 void LaTeX::updateBibtexDependencies(DepTable & dep,
578 vector<AuxInfo> const & bibtex_info)
580 // Since a run of Bibtex mandates more latex runs it is ok to
581 // remove all ".bib" and ".bst" files.
582 dep.remove_files_with_extension(".bib");
583 dep.remove_files_with_extension(".bst");
584 //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
586 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
587 it != bibtex_info.end(); ++it) {
588 for (set<string>::const_iterator it2 = it->databases.begin();
589 it2 != it->databases.end(); ++it2) {
590 FileName const file = findtexfile(*it2, "bib");
592 dep.insert(file, true);
595 for (set<string>::const_iterator it2 = it->styles.begin();
596 it2 != it->styles.end(); ++it2) {
597 FileName const file = findtexfile(*it2, "bst");
599 dep.insert(file, true);
603 // biber writes nothing into the aux file.
604 // Instead, we have to scan the blg file
607 scanBlgFile(dep, terr);
612 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
613 OutputParams const & runparams)
616 for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
617 it != bibtex_info.end(); ++it) {
618 if (!biber && it->databases.empty())
622 string tmp = runparams.use_japanese ?
623 lyxrc.jbibtex_command : lyxrc.bibtex_command;
625 if (!runparams.bibtex_command.empty())
626 tmp = runparams.bibtex_command;
628 // onlyFileName() is needed for cygwin
629 tmp += quoteName(onlyFileName(removeExtension(
630 it->aux_file.absFileName())));
632 one.startscript(Systemcall::Wait, tmp, path);
634 // Return whether bibtex was run
639 int LaTeX::scanLogFile(TeXErrors & terr)
643 int retval = NO_ERRORS;
645 onlyFileName(changeExtension(file.absFileName(), ".log"));
646 LYXERR(Debug::LATEX, "Log file: " << tmp);
647 FileName const fn = FileName(makeAbsPath(tmp));
648 ifstream ifs(fn.toFilesystemEncoding().c_str());
649 bool fle_style = false;
650 static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
651 static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
652 // Flag for 'File ended while scanning' message.
653 // We need to wait for subsequent processing.
654 string wait_for_error;
657 stack <pair<string, int> > child;
660 while (getline(ifs, token)) {
661 // MikTeX sometimes inserts \0 in the log file. They can't be
662 // removed directly with the existing string utility
663 // functions, so convert them first to \r, and remove all
664 // \r's afterwards, since we need to remove them anyway.
665 token = subst(token, '\0', '\r');
666 token = subst(token, "\r", "");
669 LYXERR(Debug::LATEX, "Log line: " << token);
674 // Track child documents
675 for (size_t i = 0; i < token.length(); ++i) {
676 if (token[i] == '(') {
678 size_t j = token.find('(', i + 1);
679 size_t len = j == string::npos
680 ? token.substr(i + 1).length()
682 string const substr = token.substr(i + 1, len);
683 if (regex_match(substr, sub, child_file)) {
684 string const name = sub.str(1);
685 child.push(make_pair(name, pnest));
688 } else if (token[i] == ')') {
690 && child.top().second == pnest)
695 child_name = child.empty() ? empty_string() : child.top().first;
697 if (contains(token, "file:line:error style messages enabled"))
700 if (prefixIs(token, "LaTeX Warning:") ||
701 prefixIs(token, "! pdfTeX warning")) {
702 // Here shall we handle different
704 retval |= LATEX_WARNING;
705 LYXERR(Debug::LATEX, "LaTeX Warning.");
706 if (contains(token, "Rerun to get cross-references")) {
708 LYXERR(Debug::LATEX, "We should rerun.");
709 // package clefval needs 2 latex runs before bibtex
710 } else if (contains(token, "Value of")
711 && contains(token, "on page")
712 && contains(token, "undefined")) {
713 retval |= ERROR_RERUN;
714 LYXERR(Debug::LATEX, "Force rerun.");
716 } else if (contains(token, "Etaremune labels have changed")) {
717 retval |= ERROR_RERUN;
718 LYXERR(Debug::LATEX, "Force rerun.");
719 } else if (contains(token, "Citation")
720 && contains(token, "on page")
721 && contains(token, "undefined")) {
723 } else if (contains(token, "Citation")
724 && contains(token, "on input line")
725 && contains(token, "undefined")) {
728 } else if (prefixIs(token, "Package")) {
730 retval |= PACKAGE_WARNING;
731 if (contains(token, "natbib Warning:")) {
733 if (contains(token, "Citation")
734 && contains(token, "on page")
735 && contains(token, "undefined")) {
738 } else if (contains(token, "run BibTeX")) {
740 } else if (contains(token, "run Biber")) {
743 } else if (contains(token, "Rerun LaTeX") ||
744 contains(token, "Please rerun LaTeX") ||
745 contains(token, "Rerun to get")) {
746 // at least longtable.sty and bibtopic.sty
748 LYXERR(Debug::LATEX, "We should rerun.");
751 } else if (prefixIs(token, "LETTRE WARNING:")) {
752 if (contains(token, "veuillez recompiler")) {
754 LYXERR(Debug::LATEX, "We should rerun.");
757 } else if (token[0] == '(') {
758 if (contains(token, "Rerun LaTeX") ||
759 contains(token, "Rerun to get")) {
761 LYXERR(Debug::LATEX, "We should rerun.");
764 } else if (prefixIs(token, "! ")
766 && regex_match(token, sub, file_line_error)
767 && !contains(token, "pdfTeX warning"))) {
768 // Ok, we have something that looks like a TeX Error
769 // but what do we really have.
771 // Just get the error description:
773 if (prefixIs(token, "! "))
774 desc = string(token, 2);
777 if (contains(token, "LaTeX Error:"))
778 retval |= LATEX_ERROR;
780 if (prefixIs(token, "! File ended while scanning")){
781 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
782 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
783 retval |= ERROR_RERUN;
784 LYXERR(Debug::LATEX, "Force rerun.");
786 // bug 6445. At this point its not clear we finish with error.
787 wait_for_error = desc;
792 if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
793 // bug 7344. We must rerun LaTeX if hyperref has been toggled.
794 retval |= ERROR_RERUN;
795 LYXERR(Debug::LATEX, "Force rerun.");
798 if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
799 retval |= LATEX_ERROR;
802 errstr = wait_for_error;
804 if (!getline(ifs, tmp))
806 tmp = rtrim(tmp, "\r");
807 errstr += "\n" + tmp;
810 } while (!contains(tmp, "(job aborted"));
813 from_local8bit("Emergency stop"),
814 from_local8bit(errstr),
822 if (!getline(ifs, tmp))
824 tmp = rtrim(tmp, "\r");
825 // 15 is somewhat arbitrarily chosen, based on practice.
826 // We used 10 for 14 years and increased it to 15 when we
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));