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");
828 // 15 is somewhat arbitrarily chosen, based on practice.
829 // We used 10 for 14 years and increased it to 15 when we
833 } while (!prefixIs(tmp, "l."));
834 if (prefixIs(tmp, "l.")) {
835 // we have a latex error
838 "Package babel Error: You haven't defined the language")
840 "Package babel Error: You haven't loaded the option")
842 "Package babel Error: Unknown language"))
843 retval |= ERROR_RERUN;
844 // get the line number:
846 sscanf(tmp.c_str(), "l.%d", &line);
847 // get the rest of the message:
848 string errstr(tmp, tmp.find(' '));
851 tmp = rtrim(tmp, "\r");
852 while (!contains(errstr, "l.")
854 && !prefixIs(tmp, "! ")
855 && !contains(tmp, "(job aborted")) {
859 tmp = rtrim(tmp, "\r");
861 LYXERR(Debug::LATEX, "line: " << line << '\n'
862 << "Desc: " << desc << '\n' << "Text: " << errstr);
863 if (line == last_line)
869 if (line_count <= 5) {
871 // We have no idea what the encoding of
873 // It seems that the output from the
874 // latex compiler itself is pure ASCII,
875 // but it can include bits from the
876 // document, so whatever encoding we
877 // assume here it can be wrong.
878 terr.insertError(line,
879 from_local8bit(desc),
880 from_local8bit(errstr),
886 // information messages, TeX warnings and other
887 // warnings we have not caught earlier.
888 if (prefixIs(token, "Overfull ")) {
889 retval |= TEX_WARNING;
890 } else if (prefixIs(token, "Underfull ")) {
891 retval |= TEX_WARNING;
892 } else if (contains(token, "Rerun to get citations")) {
893 // Natbib seems to use this.
895 } else if (contains(token, "No pages of output")) {
896 // A dvi file was not created
898 } else if (contains(token, "That makes 100 errors")) {
899 // More than 100 errors were reprted
900 retval |= TOO_MANY_ERRORS;
901 } else if (prefixIs(token, "!pdfTeX error:")){
902 // otherwise we dont catch e.g.:
903 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
906 from_local8bit("pdfTeX Error"),
907 from_local8bit(token),
912 LYXERR(Debug::LATEX, "Log line: " << token);
919 bool insertIfExists(FileName const & absname, DepTable & head)
921 if (absname.exists() && !absname.isDirectory()) {
922 head.insert(absname, true);
929 bool handleFoundFile(string const & ff, DepTable & head)
931 // convert from native os path to unix path
932 string foundfile = os::internal_path(trim(ff));
934 LYXERR(Debug::DEPEND, "Found file: " << foundfile);
936 // Ok now we found a file.
937 // Now we should make sure that this is a file that we can
938 // access through the normal paths.
939 // We will not try any fancy search methods to
942 // (1) foundfile is an
943 // absolute path and should
946 if (FileName::isAbsolute(foundfile)) {
947 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
948 // On initial insert we want to do the update at once
949 // since this file cannot be a file generated by
951 absname.set(foundfile);
952 if (!insertIfExists(absname, head)) {
954 string strippedfile = foundfile;
955 while (contains(strippedfile, " ")) {
956 // files with spaces are often enclosed in quotation
957 // marks; those have to be removed
958 string unquoted = subst(strippedfile, "\"", "");
959 absname.set(unquoted);
960 if (insertIfExists(absname, head))
962 // strip off part after last space and try again
963 string tmp = strippedfile;
964 string const stripoff =
965 rsplit(tmp, strippedfile, ' ');
966 absname.set(strippedfile);
967 if (insertIfExists(absname, head))
973 string onlyfile = onlyFileName(foundfile);
974 absname = makeAbsPath(onlyfile);
977 while (contains(foundfile, ' ')) {
978 if (absname.exists())
982 // files with spaces are often enclosed in quotation
983 // marks; those have to be removed
984 string unquoted = subst(foundfile, "\"", "");
985 absname = makeAbsPath(unquoted);
986 if (absname.exists())
988 // strip off part after last space and try again
990 string const stripoff =
991 rsplit(foundfile, strippedfile, ' ');
992 foundfile = strippedfile;
993 onlyfile = onlyFileName(strippedfile);
994 absname = makeAbsPath(onlyfile);
998 // (2) foundfile is in the tmpdir
999 // insert it into head
1000 if (absname.exists() && !absname.isDirectory()) {
1001 // FIXME: This regex contained glo, but glo is used by the old
1002 // version of nomencl.sty. Do we need to put it back?
1003 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1004 if (regex_match(onlyfile, unwanted)) {
1005 LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1006 << " in the dep file");
1007 } else if (suffixIs(onlyfile, ".tex")) {
1008 // This is a tex file generated by LyX
1009 // and latex is not likely to change this
1011 LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1012 head.insert(absname, true);
1014 LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1015 head.insert(absname);
1019 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1025 bool completeFilename(string const & ff, DepTable & head)
1027 // If we do not find a dot, we suspect
1028 // a fragmental file name
1029 if (!contains(ff, '.'))
1032 // if we have a dot, we let handleFoundFile decide
1033 return handleFoundFile(ff, head);
1037 int iterateLine(string const & token, regex const & reg, string const & closing,
1038 int fragment_pos, DepTable & head)
1041 string::const_iterator first = token.begin();
1042 string::const_iterator end = token.end();
1043 bool fragment = false;
1046 while (regex_search(first, end, what, reg)) {
1047 // if we have a dot, try to handle as file
1048 if (contains(what.str(1), '.')) {
1049 first = what[0].second;
1050 if (what.str(2) == closing) {
1051 handleFoundFile(what.str(1), head);
1052 // since we had a closing bracket,
1053 // do not investigate further
1056 // if we have no closing bracket,
1057 // try to handle as file nevertheless
1058 fragment = !handleFoundFile(
1059 what.str(1) + what.str(2), head);
1061 // if we do not have a dot, check if the line has
1062 // a closing bracket (else, we suspect a line break)
1063 else if (what.str(2) != closing) {
1064 first = what[0].second;
1067 // we have a closing bracket, so the content
1068 // is not a file name.
1069 // no need to investigate further
1070 first = what[0].second;
1073 last_match = what.str(1);
1076 // We need to consider the result from previous line iterations:
1077 // We might not find a fragment here, but another one might follow
1078 // E.g.: (filename.ext) <filenam
1079 // Vice versa, we consider the search completed if a real match
1080 // follows a potential fragment from a previous iteration.
1081 // E.g. <some text we considered a fragment (filename.ext)
1082 // result = -1 means we did not find a fragment!
1084 int last_match_pos = -1;
1085 if (!last_match.empty() && token.find(last_match) != string::npos)
1086 last_match_pos = int(token.find(last_match));
1088 if (last_match_pos > fragment_pos)
1089 result = last_match_pos;
1091 result = fragment_pos;
1093 if (last_match_pos < fragment_pos)
1094 result = fragment_pos;
1102 void LaTeX::deplog(DepTable & head)
1104 // This function reads the LaTeX log file end extracts all the
1105 // external files used by the LaTeX run. The files are then
1106 // entered into the dependency file.
1108 string const logfile =
1109 onlyFileName(changeExtension(file.absFileName(), ".log"));
1111 static regex const reg1("File: (.+).*");
1112 static regex const reg2("No file (.+)(.).*");
1113 static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1114 // If an index should be created, MikTex does not write a line like
1115 // \openout# = 'sample.idx'.
1116 // but instead only a line like this into the log:
1117 // Writing index file sample.idx
1118 static regex const reg4("Writing index file (.+).*");
1119 static regex const regoldnomencl("Writing glossary file (.+).*");
1120 static regex const regnomencl("Writing nomenclature file (.+).*");
1121 // If a toc should be created, MikTex does not write a line like
1122 // \openout# = `sample.toc'.
1123 // but only a line like this into the log:
1125 // This line is also written by tetex.
1126 // This line is not present if no toc should be created.
1127 static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1128 // file names can be enclosed in <...> (anywhere on the line)
1129 static regex const reg5(".*<[^>]+.*");
1130 // and also (...) anywhere on the line
1131 static regex const reg6(".*\\([^)]+.*");
1133 FileName const fn = makeAbsPath(logfile);
1134 ifstream ifs(fn.toFilesystemEncoding().c_str());
1137 // Ok, the scanning of files here is not sufficient.
1138 // Sometimes files are named by "File: xxx" only
1139 // Therefore we use some regexps to find files instead.
1140 // Note: all file names and paths might contains spaces.
1141 // Also, file names might be broken across lines. Therefore
1142 // we mark (potential) fragments and merge those lines.
1143 bool fragment = false;
1145 getline(ifs, token);
1146 // MikTeX sometimes inserts \0 in the log file. They can't be
1147 // removed directly with the existing string utility
1148 // functions, so convert them first to \r, and remove all
1149 // \r's afterwards, since we need to remove them anyway.
1150 token = subst(token, '\0', '\r');
1151 token = subst(token, "\r", "");
1152 if (token.empty() || token == ")") {
1153 lastline = string();
1157 // FIXME UNICODE: We assume that the file names in the log
1158 // file are in the file system encoding.
1159 token = to_utf8(from_filesystem8bit(token));
1161 // Sometimes, filenames are broken across lines.
1162 // We care for that and save suspicious lines.
1163 // Here we exclude some cases where we are sure
1164 // that there is no continued filename
1165 if (!lastline.empty()) {
1166 static regex const package_info("Package \\w+ Info: .*");
1167 static regex const package_warning("Package \\w+ Warning: .*");
1168 if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1169 || prefixIs(token, "Package:")
1170 || prefixIs(token, "Language:")
1171 || prefixIs(token, "LaTeX Info:")
1172 || prefixIs(token, "LaTeX Font Info:")
1173 || prefixIs(token, "\\openout[")
1174 || prefixIs(token, "))")
1175 || regex_match(token, package_info)
1176 || regex_match(token, package_warning))
1177 lastline = string();
1180 if (!lastline.empty())
1181 // probably a continued filename from last line
1182 token = lastline + token;
1183 if (token.length() > 255) {
1184 // string too long. Cut off.
1185 token.erase(0, token.length() - 251);
1190 // (1) "File: file.ext"
1191 if (regex_match(token, sub, reg1)) {
1192 // is this a fragmental file name?
1193 fragment = !completeFilename(sub.str(1), head);
1195 if (suffixIs(token, ")"))
1196 // no fragment for sure
1198 // (2) "No file file.ext"
1199 } else if (regex_match(token, sub, reg2)) {
1200 // file names must contains a dot, line ends with dot
1201 if (contains(sub.str(1), '.') && sub.str(2) == ".")
1202 fragment = !handleFoundFile(sub.str(1), head);
1204 // we suspect a line break
1206 // (3) "\openout<nr> = `file.ext'."
1207 } else if (regex_match(token, sub, reg3)) {
1208 // search for closing '. at the end of the line
1209 if (sub.str(2) == "\'.")
1210 fragment = !handleFoundFile(sub.str(1), head);
1212 // potential fragment
1214 // (4) "Writing index file file.ext"
1215 } else if (regex_match(token, sub, reg4))
1216 // fragmential file name?
1217 fragment = !completeFilename(sub.str(1), head);
1218 // (5) "Writing nomenclature file file.ext"
1219 else if (regex_match(token, sub, regnomencl) ||
1220 regex_match(token, sub, regoldnomencl))
1221 // fragmental file name?
1222 fragment= !completeFilename(sub.str(1), head);
1223 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1224 else if (regex_match(token, sub, miktexTocReg))
1225 fragment = !handleFoundFile(onlyFileName(changeExtension(
1226 file.absFileName(), ".toc")), head);
1228 // not found, but we won't check further
1231 int fragment_pos = -1;
1233 // We can have several of these on one line
1234 // (and in addition to those above)
1235 if (regex_match(token, sub, reg5)) {
1236 // search for strings in <...>
1237 static regex const reg5_1("<([^>]+)(.)");
1238 fragment_pos = iterateLine(token, reg5_1, ">",
1239 fragment_pos, head);
1240 fragment = (fragment_pos != -1);
1244 // We can have several of these on one line
1245 // this must be queried separated, because of
1246 // cases such as "File: file.ext (type eps)"
1247 // where "File: file.ext" would be skipped
1248 if (regex_match(token, sub, reg6)) {
1249 // search for strings in (...)
1250 static regex const reg6_1("\\(([^()]+)(.)");
1251 fragment_pos = iterateLine(token, reg6_1, ")",
1252 fragment_pos, head);
1253 fragment = (fragment_pos != -1);
1257 // probable linebreak within file name:
1261 // no linebreak: reset
1262 lastline = string();
1265 // Make sure that the main .tex file is in the dependency file.
1266 head.insert(file, true);
1270 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1272 FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1273 LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1275 ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1277 static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1278 static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1279 static regex const bibtexError2("^(.*---while reading file).*$");
1280 static regex const bibtexError3("(A bad cross reference---).*");
1281 static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1282 static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1283 static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1284 int retval = NO_ERRORS;
1287 while (getline(ifs, token)) {
1288 token = rtrim(token, "\r");
1290 // FIXME UNICODE: We assume that citation keys and filenames
1291 // in the aux file are in the file system encoding.
1292 token = to_utf8(from_filesystem8bit(token));
1293 if (regex_match(token, sub, reg1)) {
1294 string data = sub.str(3);
1295 if (!data.empty()) {
1296 LYXERR(Debug::LATEX, "Found bib file: " << data);
1297 handleFoundFile(data, dep);
1300 else if (regex_match(token, sub, bibtexError)
1301 || regex_match(token, sub, bibtexError2)
1302 || regex_match(token, sub, bibtexError4)
1303 || regex_match(token, sub, bibtexError5)) {
1304 retval |= BIBTEX_ERROR;
1305 string errstr = N_("BibTeX error: ") + token;
1307 if ((prefixIs(token, "while executing---line")
1308 || prefixIs(token, "---line ")
1309 || prefixIs(token, "*Please notify the BibTeX"))
1310 && !prevtoken.empty()) {
1311 errstr = N_("BibTeX error: ") + prevtoken;
1312 message = prevtoken + '\n';
1316 from_local8bit(errstr),
1317 from_local8bit(message));
1318 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1319 retval |= BIBTEX_ERROR;
1320 string errstr = N_("BibTeX error: ") + prevtoken;
1321 string message = prevtoken + '\n' + token;
1323 from_local8bit(errstr),
1324 from_local8bit(message));
1325 } else if (regex_match(token, sub, biberError)) {
1326 retval |= BIBTEX_ERROR;
1327 string errstr = N_("Biber error: ") + sub.str(2);
1328 string message = token;
1330 from_local8bit(errstr),
1331 from_local8bit(message));