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
12 * Full author contact details are available in file CREDITS.
17 #include "bufferlist.h"
24 #include "support/filetools.h"
25 #include "support/convert.h"
26 #include "support/lstrings.h"
27 #include "support/lyxlib.h"
28 #include "support/systemcall.h"
29 #include "support/os.h"
31 #include <boost/filesystem/operations.hpp>
32 #include <boost/regex.hpp>
39 using support::absolutePath;
40 using support::bformat;
41 using support::changeExtension;
42 using support::contains;
43 using support::findtexfile;
44 using support::getcwd;
45 using support::onlyFilename;
46 using support::prefixIs;
47 using support::quoteName;
51 using support::suffixIs;
52 using support::Systemcall;
53 using support::unlink;
56 namespace os = support::os;
57 namespace fs = boost::filesystem;
63 #ifndef CXX_GLOBAL_CSTD
74 // TODO: in no particular order
75 // - get rid of the call to
76 // BufferList::updateIncludedTeXfiles, this should either
77 // be done before calling LaTeX::funcs or in a completely
79 // - the makeindex style files should be taken care of with
80 // the dependency mechanism.
81 // - makeindex commandline options should be supported
82 // - somewhere support viewing of bibtex and makeindex log files.
83 // - we should perhaps also scan the bibtex log file
87 docstring runMessage(unsigned int count)
89 return bformat(_("Waiting for LaTeX run number %1$d"), count);
98 void TeXErrors::insertError(int line, docstring const & error_desc,
99 docstring const & error_text)
101 Error newerr(line, error_desc, error_text);
102 errors.push_back(newerr);
106 bool operator==(Aux_Info const & a, Aux_Info const & o)
108 return a.aux_file == o.aux_file &&
109 a.citations == o.citations &&
110 a.databases == o.databases &&
111 a.styles == o.styles;
115 bool operator!=(Aux_Info const & a, Aux_Info const & o)
125 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
126 string const & f, string const & p)
127 : cmd(latex), file(f), path(p), runparams(rp)
130 depfile = file + ".dep";
131 if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
133 output_file = changeExtension(file,".pdf");
135 output_file = changeExtension(file,".dvi");
140 void LaTeX::deleteFilesOnError() const
142 // currently just a dummy function.
144 // What files do we have to delete?
146 // This will at least make latex do all the runs
149 // but the reason for the error might be in a generated file...
151 string const ofname = onlyFilename(file);
154 string const bbl = changeExtension(ofname, ".bbl");
158 string const ind = changeExtension(ofname, ".ind");
162 string const nls = changeExtension(ofname, ".nls");
165 // Also remove the aux file
166 string const aux = changeExtension(ofname, ".aux");
171 int LaTeX::run(TeXErrors & terr)
172 // We know that this function will only be run if the lyx buffer
173 // has been changed. We also know that a newly written .tex file
174 // is always different from the previous one because of the date
175 // in it. However it seems safe to run latex (at least) on time each
176 // time the .tex file changes.
178 int scanres = NO_ERRORS;
179 unsigned int count = 0; // number of times run
180 num_errors = 0; // just to make sure.
181 unsigned int const MAX_RUN = 6;
182 DepTable head; // empty head
183 bool rerun = false; // rerun requested
185 // The class LaTeX does not know the temp path.
186 theBufferList().updateIncludedTeXfiles(getcwd(), runparams);
188 // Never write the depfile if an error was encountered.
191 // first check if the file dependencies exist:
192 // ->If it does exist
193 // check if any of the files mentioned in it have
194 // changed (done using a checksum).
196 // run latex once and
197 // remake the dependency file
198 // -> if not changed:
199 // just return there is nothing to do for us.
200 // ->if it doesn't exist
202 // run latex once (we need to run latex once anyway) and
203 // remake the dependency file.
206 bool had_depfile = fs::exists(depfile);
207 bool run_bibtex = false;
208 string aux_file = onlyFilename(changeExtension(file, "aux"));
211 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
212 // Read the dep file:
213 had_depfile = head.read(depfile);
217 // Update the checksums
219 // Can't just check if anything has changed because it might have aborted
220 // on error last time... in which cas we need to re-run latex
221 // and collect the error messages (even if they are the same).
222 if (!fs::exists(output_file)) {
223 lyxerr[Debug::DEPEND]
224 << "re-running LaTeX because output file doesn't exist." << endl;
225 } else if (!head.sumchange()) {
226 lyxerr[Debug::DEPEND] << "return no_change" << endl;
229 lyxerr[Debug::DEPEND]
230 << "Dependency file has changed" << endl;
233 if (head.extchanged(".bib") || head.extchanged(".bst"))
236 lyxerr[Debug::DEPEND]
237 << "Dependency file does not exist, or has wrong format" << endl;
239 /// We scan the aux file even when had_depfile = false,
240 /// because we can run pdflatex on the file after running latex on it,
241 /// in which case we will not need to run bibtex again.
242 vector<Aux_Info> bibtex_info_old;
244 bibtex_info_old = scanAuxFiles(aux_file);
247 lyxerr[Debug::LATEX] << "Run #" << count << endl;
248 message(runMessage(count));
251 scanres = scanLogFile(terr);
252 if (scanres & ERROR_RERUN) {
253 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
255 scanres = scanLogFile(terr);
258 if (scanres & ERRORS) {
259 deleteFilesOnError();
260 return scanres; // return on error
263 vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
264 if (!run_bibtex && bibtex_info_old != bibtex_info)
267 // update the dependencies.
268 deplog(head); // reads the latex log
272 // At this point we must run external programs if needed.
273 // makeindex will be run if a .idx file changed or was generated.
274 // And if there were undefined citations or changes in references
275 // the .aux file is checked for signs of bibtex. Bibtex is then run
278 // memoir (at least) writes an empty *idx file in the first place.
279 // A second latex run is needed.
280 rerun = fs::exists(changeExtension(file, ".idx"))
281 && fs::is_empty(changeExtension(file, ".idx"));
284 if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
286 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
287 message(_("Running MakeIndex."));
288 rerun |= runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
290 if (head.haschanged(onlyFilename(changeExtension(file, ".nlo")))) {
291 lyxerr[Debug::LATEX] << "Running MakeIndex for nomencl." << endl;
292 message(_("Running MakeIndex for nomencl."));
293 string const nomenclstr = " -s nomencl.ist -o " + changeExtension(file, ".nls");
294 rerun |= runMakeIndex(onlyFilename(changeExtension(file, ".nlo")), runparams, nomenclstr);
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." << endl;
305 message(_("Running BibTeX."));
306 updateBibtexDependencies(head, bibtex_info);
307 rerun |= runBibTeX(bibtex_info);
308 } else if (!had_depfile) {
309 /// If we run pdflatex on the file after running latex on it,
310 /// then we do not need to run bibtex, but we do need to
311 /// insert the .bib and .bst files into the .dep-pdf file.
312 updateBibtexDependencies(head, bibtex_info);
316 // we know on this point that latex has been run once (or we just
317 // returned) and the question now is to decide if we need to run
318 // it any more. This is done by asking if any of the files in the
319 // dependency file has changed. (remember that the checksum for
320 // a given file is reported to have changed if it just was created)
321 // -> if changed or rerun == true:
322 // run latex once more and
323 // update the dependency structure
324 // -> if not changed:
325 // we does nothing at this point
327 if (rerun || head.sumchange()) {
330 lyxerr[Debug::DEPEND]
331 << "Dep. file has changed or rerun requested" << endl;
333 << "Run #" << count << endl;
334 message(runMessage(count));
336 scanres = scanLogFile(terr);
337 if (scanres & ERRORS) {
338 deleteFilesOnError();
339 return scanres; // return on error
342 // update the depedencies
343 deplog(head); // reads the latex log
346 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
350 // The inclusion of files generated by external programs like
351 // makeindex or bibtex might have done changes to pagenumbering,
352 // etc. And because of this we must run the external programs
353 // again to make sure everything is redone correctly.
354 // Also there should be no need to run the external programs any
357 // run makeindex if the <file>.idx has changed or was generated.
358 if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
360 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
361 message(_("Running MakeIndex."));
362 rerun = runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
365 // I am not pretty sure if need this twice.
366 if (head.haschanged(onlyFilename(changeExtension(file, ".nlo")))) {
367 lyxerr[Debug::LATEX] << "Running MakeIndex for nomencl." << endl;
368 message(_("Running MakeIndex for nomencl."));
369 string nomenclstr = " -s nomencl.ist -o " + changeExtension(file, ".nls");
370 rerun |= runMakeIndex(onlyFilename(changeExtension(file, ".nlo")), runparams, nomenclstr);
374 // we will only run latex more if the log file asks for it.
375 // or if the sumchange() is true.
376 // -> rerun asked for:
378 // remake the dependency file
379 // goto 2 or return if max runs are reached.
380 // -> rerun not asked for:
381 // just return (fall out of bottom of func)
383 while ((head.sumchange() || rerun || (scanres & RERUN))
384 && count < MAX_RUN) {
385 // Yes rerun until message goes away, or until
386 // MAX_RUNS are reached.
389 lyxerr[Debug::LATEX] << "Run #" << count << endl;
390 message(runMessage(count));
392 scanres = scanLogFile(terr);
393 if (scanres & ERRORS) {
394 deleteFilesOnError();
395 return scanres; // return on error
402 // Write the dependencies to file.
404 lyxerr[Debug::LATEX] << "Done." << endl;
409 int LaTeX::startscript()
411 string tmp = cmd + ' ' + quoteName(file) + " > " + os::nulldev();
413 return one.startscript(Systemcall::Wait, tmp);
417 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
418 string const & params)
421 << "idx file has been made, running makeindex on file "
423 string tmp = lyxrc.index_command + ' ';
425 tmp = subst(tmp, "$$lang", runparams.document_language);
429 one.startscript(Systemcall::Wait, tmp);
434 vector<Aux_Info> const
435 LaTeX::scanAuxFiles(string const & file)
437 vector<Aux_Info> result;
439 result.push_back(scanAuxFile(file));
441 for (int i = 1; i < 1000; ++i) {
442 string const file2 = changeExtension(file, "")
443 + '.' + convert<string>(i)
445 if (!fs::exists(file2))
447 result.push_back(scanAuxFile(file2));
453 Aux_Info const LaTeX::scanAuxFile(string const & file)
456 result.aux_file = file;
457 scanAuxFile(file, result);
462 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
464 lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
466 ifstream ifs(file.c_str());
468 static regex const reg1("\\\\citation\\{([^}]+)\\}");
469 static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
470 static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
471 static regex const reg4("\\\\@input\\{([^}]+)\\}");
473 while (getline(ifs, token)) {
474 token = rtrim(token, "\r");
476 if (regex_match(token, sub, reg1)) {
477 string data = sub.str(1);
478 while (!data.empty()) {
480 data = split(data, citation, ',');
481 lyxerr[Debug::LATEX] << "Citation: "
483 aux_info.citations.insert(citation);
485 } else if (regex_match(token, sub, reg2)) {
486 string data = sub.str(1);
487 // data is now all the bib files separated by ','
488 // get them one by one and pass them to the helper
489 while (!data.empty()) {
491 data = split(data, database, ',');
492 database = changeExtension(database, "bib");
493 lyxerr[Debug::LATEX] << "BibTeX database: `"
494 << database << '\'' << endl;
495 aux_info.databases.insert(database);
497 } else if (regex_match(token, sub, reg3)) {
498 string style = sub.str(1);
499 // token is now the style file
500 // pass it to the helper
501 style = changeExtension(style, "bst");
502 lyxerr[Debug::LATEX] << "BibTeX style: `"
503 << style << '\'' << endl;
504 aux_info.styles.insert(style);
505 } else if (regex_match(token, sub, reg4)) {
506 string const file2 = sub.str(1);
507 scanAuxFile(file2, aux_info);
513 void LaTeX::updateBibtexDependencies(DepTable & dep,
514 vector<Aux_Info> const & bibtex_info)
516 // Since a run of Bibtex mandates more latex runs it is ok to
517 // remove all ".bib" and ".bst" files.
518 dep.remove_files_with_extension(".bib");
519 dep.remove_files_with_extension(".bst");
520 //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
522 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
523 it != bibtex_info.end(); ++it) {
524 for (set<string>::const_iterator it2 = it->databases.begin();
525 it2 != it->databases.end(); ++it2) {
526 string file = findtexfile(*it2, "bib");
528 dep.insert(file, true);
531 for (set<string>::const_iterator it2 = it->styles.begin();
532 it2 != it->styles.end(); ++it2) {
533 string file = findtexfile(*it2, "bst");
535 dep.insert(file, true);
541 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
544 for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
545 it != bibtex_info.end(); ++it) {
546 if (it->databases.empty())
550 string tmp = lyxrc.bibtex_command + " ";
551 tmp += quoteName(onlyFilename(changeExtension(it->aux_file, string())));
553 one.startscript(Systemcall::Wait, tmp);
555 // Return whether bibtex was run
560 int LaTeX::scanLogFile(TeXErrors & terr)
564 int retval = NO_ERRORS;
565 string tmp = onlyFilename(changeExtension(file, ".log"));
566 lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
567 ifstream ifs(tmp.c_str());
570 while (getline(ifs, token)) {
571 // MikTeX sometimes inserts \0 in the log file. They can't be
572 // removed directly with the existing string utility
573 // functions, so convert them first to \r, and remove all
574 // \r's afterwards, since we need to remove them anyway.
575 token = subst(token, '\0', '\r');
576 token = subst(token, "\r", "");
578 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
583 if (prefixIs(token, "LaTeX Warning:") ||
584 prefixIs(token, "! pdfTeX warning")) {
585 // Here shall we handle different
587 retval |= LATEX_WARNING;
588 lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
589 if (contains(token, "Rerun to get cross-references")) {
592 << "We should rerun." << endl;
593 } else if (contains(token, "Citation")
594 && contains(token, "on page")
595 && contains(token, "undefined")) {
598 } else if (prefixIs(token, "Package")) {
600 retval |= PACKAGE_WARNING;
601 if (contains(token, "natbib Warning:")) {
603 if (contains(token, "Citation")
604 && contains(token, "on page")
605 && contains(token, "undefined")) {
608 } else if (contains(token, "run BibTeX")) {
610 } else if (contains(token, "Rerun LaTeX") ||
611 contains(token, "Rerun to get")) {
612 // at least longtable.sty and bibtopic.sty
615 << "We should rerun." << endl;
618 } else if (token[0] == '(') {
619 if (contains(token, "Rerun LaTeX") ||
620 contains(token, "Rerun to get")) {
623 << "We should rerun." << endl;
626 } else if (prefixIs(token, "! ")) {
627 // Ok, we have something that looks like a TeX Error
628 // but what do we really have.
630 // Just get the error description:
631 string desc(token, 2);
632 if (contains(token, "LaTeX Error:"))
633 retval |= LATEX_ERROR;
638 if (!getline(ifs, tmp))
642 } while (!prefixIs(tmp, "l."));
643 if (prefixIs(tmp, "l.")) {
644 // we have a latex error
646 if (contains(desc, "Package babel Error: You haven't defined the language"))
647 retval |= ERROR_RERUN;
648 // get the line number:
650 sscanf(tmp.c_str(), "l.%d", &line);
651 // get the rest of the message:
652 string errstr(tmp, tmp.find(' '));
655 while (!contains(errstr, "l.")
657 && !prefixIs(tmp, "! ")
658 && !contains(tmp, "(job aborted")) {
664 << "line: " << line << '\n'
665 << "Desc: " << desc << '\n'
666 << "Text: " << errstr << endl;
667 if (line == last_line)
673 if (line_count <= 5) {
675 // We have no idea what the encoding of the log file is
676 // (probably pure ascii, but maybe some localized
677 // latex compilers or packages exist)
678 terr.insertError(line, from_utf8(desc), from_utf8(errstr));
683 // information messages, TeX warnings and other
684 // warnings we have not caught earlier.
685 if (prefixIs(token, "Overfull ")) {
686 retval |= TEX_WARNING;
687 } else if (prefixIs(token, "Underfull ")) {
688 retval |= TEX_WARNING;
689 } else if (contains(token, "Rerun to get citations")) {
690 // Natbib seems to use this.
692 } else if (contains(token, "No pages of output")) {
693 // A dvi file was not created
695 } else if (contains(token, "That makes 100 errors")) {
696 // More than 100 errors were reprted
697 retval |= TOO_MANY_ERRORS;
701 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
708 void handleFoundFile(string const & ff, DepTable & head)
710 // convert from native os path to unix path
711 string const foundfile = os::internal_path(trim(ff));
713 lyxerr[Debug::DEPEND] << "Found file: " << foundfile << endl;
715 // Ok now we found a file.
716 // Now we should make sure that this is a file that we can
717 // access through the normal paths.
718 // We will not try any fancy search methods to
721 // (1) foundfile is an
722 // absolute path and should
724 if (absolutePath(foundfile)) {
725 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
726 << foundfile << endl;
727 // On initial insert we want to do the update at once
728 // since this file can not be a file generated by
730 if (fs::exists(foundfile) && !fs::is_directory(foundfile))
731 head.insert(foundfile, true);
736 string const onlyfile = onlyFilename(foundfile);
738 // (2) foundfile is in the tmpdir
739 // insert it into head
740 if (fs::exists(onlyfile)) {
741 static regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
742 if (regex_match(onlyfile, unwanted)) {
743 lyxerr[Debug::DEPEND]
746 << " in the dep file"
748 } else if (suffixIs(onlyfile, ".tex")) {
749 // This is a tex file generated by LyX
750 // and latex is not likely to change this
752 lyxerr[Debug::DEPEND]
753 << "Tmpdir TeX file: "
756 head.insert(onlyfile, true);
758 lyxerr[Debug::DEPEND]
762 head.insert(onlyfile);
765 lyxerr[Debug::DEPEND]
766 << "Not a file or we are unable to find it."
773 void LaTeX::deplog(DepTable & head)
775 // This function reads the LaTeX log file end extracts all the external
776 // files used by the LaTeX run. The files are then entered into the
779 string const logfile = onlyFilename(changeExtension(file, ".log"));
781 static regex reg1(".*\\([^)]+.*");
782 static regex reg2("File: ([^ ]+).*");
783 static regex reg3("No file ([^ ]+)\\..*");
784 static regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
785 // If an index should be created, MikTex does not write a line like
786 // \openout# = 'sample.idx'.
787 // but instead only a line like this into the log:
788 // Writing index file sample.idx
789 static regex reg5("Writing index file ([^ ]+).*");
790 static regex regnomencl("Writing nomenclature file ([^ ]+).*");
791 // If a toc should be created, MikTex does not write a line like
792 // \openout# = `sample.toc'.
793 // but only a line like this into the log:
795 // This line is also written by tetex.
796 // This line is not present if no toc should be created.
797 static regex miktexTocReg("\\\\tf@toc=\\\\write.*");
799 ifstream ifs(logfile.c_str());
801 // Ok, the scanning of files here is not sufficient.
802 // Sometimes files are named by "File: xxx" only
803 // So I think we should use some regexps to find files instead.
804 // "(\([^ ]+\)" should match the "(file " variant, note
805 // that we can have several of these on one line.
806 // "File: \([^ ]+\)" should match the "File: file" variant
810 // MikTeX sometimes inserts \0 in the log file. They can't be
811 // removed directly with the existing string utility
812 // functions, so convert them first to \r, and remove all
813 // \r's afterwards, since we need to remove them anyway.
814 token = subst(token, '\0', '\r');
815 token = subst(token, "\r", "");
821 if (regex_match(token, sub, reg1)) {
822 static regex reg1_1("\\(([^()]+)");
824 string::const_iterator first = token.begin();
825 string::const_iterator end = token.end();
827 while (regex_search(first, end, what, reg1_1)) {
828 first = what[0].second;
829 handleFoundFile(what.str(1), head);
831 } else if (regex_match(token, sub, reg2))
832 handleFoundFile(sub.str(1), head);
833 else if (regex_match(token, sub, reg3))
834 handleFoundFile(sub.str(1), head);
835 else if (regex_match(token, sub, reg4))
836 handleFoundFile(sub.str(1), head);
837 else if (regex_match(token, sub, reg5))
838 handleFoundFile(sub.str(1), head);
839 else if (regex_match(token, sub, regnomencl))
840 handleFoundFile(sub.str(1), head);
841 else if (regex_match(token, sub, miktexTocReg))
842 handleFoundFile(changeExtension(file, ".toc"), head);
845 // Make sure that the main .tex file is in the dependancy file.
846 head.insert(onlyFilename(file), true);