]> git.lyx.org Git - lyx.git/blob - src/LaTeX.C
Oops, committed an old version. This one links.
[lyx.git] / src / LaTeX.C
1 /**
2  * \file LaTeX.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Dekel Tsur
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "bufferlist.h"
18 #include "LaTeX.h"
19 #include "gettext.h"
20 #include "lyxrc.h"
21 #include "debug.h"
22 #include "DepTable.h"
23
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"
30
31 #include <boost/filesystem/operations.hpp>
32 #include <boost/regex.hpp>
33
34 #include <fstream>
35
36
37 namespace lyx {
38
39 using support::absolutePath;
40 using support::bformat;
41 using support::changeExtension;
42 using support::contains;
43 using support::FileName;
44 using support::findtexfile;
45 using support::getcwd;
46 using support::makeAbsPath;
47 using support::onlyFilename;
48 using support::prefixIs;
49 using support::quoteName;
50 using support::removeExtension;
51 using support::rtrim;
52 using support::split;
53 using support::subst;
54 using support::suffixIs;
55 using support::Systemcall;
56 using support::unlink;
57 using support::trim;
58
59 namespace os = support::os;
60 namespace fs = boost::filesystem;
61
62 using boost::regex;
63 using boost::smatch;
64
65
66 #ifndef CXX_GLOBAL_CSTD
67 using std::sscanf;
68 #endif
69
70 using std::endl;
71 using std::getline;
72 using std::string;
73 using std::ifstream;
74 using std::set;
75 using std::vector;
76
77 // TODO: in no particular order
78 // - get rid of the call to
79 //   BufferList::updateIncludedTeXfiles, this should either
80 //   be done before calling LaTeX::funcs or in a completely
81 //   different way.
82 // - the makeindex style files should be taken care of with
83 //   the dependency mechanism.
84 // - makeindex commandline options should be supported
85 // - somewhere support viewing of bibtex and makeindex log files.
86 // - we should perhaps also scan the bibtex log file
87
88 namespace {
89
90 docstring runMessage(unsigned int count)
91 {
92         return bformat(_("Waiting for LaTeX run number %1$d"), count);
93 }
94
95 } // anon namespace
96
97 /*
98  * CLASS TEXERRORS
99  */
100
101 void TeXErrors::insertError(int line, docstring const & error_desc,
102                             docstring const & error_text)
103 {
104         Error newerr(line, error_desc, error_text);
105         errors.push_back(newerr);
106 }
107
108
109 bool operator==(Aux_Info const & a, Aux_Info const & o)
110 {
111         return a.aux_file == o.aux_file &&
112                 a.citations == o.citations &&
113                 a.databases == o.databases &&
114                 a.styles == o.styles;
115 }
116
117
118 bool operator!=(Aux_Info const & a, Aux_Info const & o)
119 {
120         return !(a == o);
121 }
122
123
124 /*
125  * CLASS LaTeX
126  */
127
128 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
129              FileName const & f)
130         : cmd(latex), file(f), runparams(rp)
131 {
132         num_errors = 0;
133         if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
134                 depfile = FileName(file.absFilename() + ".dep-pdf");
135                 output_file = FileName(changeExtension(file.absFilename(), ".pdf"));
136         } else {
137                 depfile = FileName(file.absFilename() + ".dep");
138                 output_file = FileName(changeExtension(file.absFilename(), ".dvi"));
139         }
140 }
141
142
143 void LaTeX::deleteFilesOnError() const
144 {
145         // currently just a dummy function.
146
147         // What files do we have to delete?
148
149         // This will at least make latex do all the runs
150         unlink(depfile);
151
152         // but the reason for the error might be in a generated file...
153
154         // bibtex file
155         FileName const bbl(changeExtension(file.absFilename(), ".bbl"));
156         unlink(bbl);
157
158         // makeindex file
159         FileName const ind(changeExtension(file.absFilename(), ".ind"));
160         unlink(ind);
161
162         // nomencl file
163         FileName const nls(changeExtension(file.absFilename(), ".nls"));
164         unlink(nls);
165
166         // Also remove the aux file
167         FileName const aux(changeExtension(file.absFilename(), ".aux"));
168         unlink(aux);
169 }
170
171
172 int LaTeX::run(TeXErrors & terr)
173         // We know that this function will only be run if the lyx buffer
174         // has been changed. We also know that a newly written .tex file
175         // is always different from the previous one because of the date
176         // in it. However it seems safe to run latex (at least) on time each
177         // time the .tex file changes.
178 {
179         int scanres = NO_ERRORS;
180         unsigned int count = 0; // number of times run
181         num_errors = 0; // just to make sure.
182         unsigned int const MAX_RUN = 6;
183         DepTable head; // empty head
184         bool rerun = false; // rerun requested
185
186         // The class LaTeX does not know the temp path.
187         theBufferList().updateIncludedTeXfiles(getcwd(), runparams);
188
189         // Never write the depfile if an error was encountered.
190
191         // 0
192         // first check if the file dependencies exist:
193         //     ->If it does exist
194         //             check if any of the files mentioned in it have
195         //             changed (done using a checksum).
196         //                 -> if changed:
197         //                        run latex once and
198         //                        remake the dependency file
199         //                 -> if not changed:
200         //                        just return there is nothing to do for us.
201         //     ->if it doesn't exist
202         //             make it and
203         //             run latex once (we need to run latex once anyway) and
204         //             remake the dependency file.
205         //
206
207         bool had_depfile = fs::exists(depfile.toFilesystemEncoding());
208         bool run_bibtex = false;
209         FileName const aux_file(changeExtension(file.absFilename(), "aux"));
210
211         if (had_depfile) {
212                 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
213                 // Read the dep file:
214                 had_depfile = head.read(depfile);
215         }
216
217         if (had_depfile) {
218                 // Update the checksums
219                 head.update();
220                 // Can't just check if anything has changed because it might have aborted
221                 // on error last time... in which cas we need to re-run latex
222                 // and collect the error messages (even if they are the same).
223                 if (!fs::exists(output_file.toFilesystemEncoding())) {
224                         lyxerr[Debug::DEPEND]
225                                 << "re-running LaTeX because output file doesn't exist." << endl;
226                 } else if (!head.sumchange()) {
227                         lyxerr[Debug::DEPEND] << "return no_change" << endl;
228                         return NO_CHANGE;
229                 } else {
230                         lyxerr[Debug::DEPEND]
231                                 << "Dependency file has changed" << endl;
232                 }
233
234                 if (head.extchanged(".bib") || head.extchanged(".bst"))
235                         run_bibtex = true;
236         } else
237                 lyxerr[Debug::DEPEND]
238                         << "Dependency file does not exist, or has wrong format" << endl;
239
240         /// We scan the aux file even when had_depfile = false,
241         /// because we can run pdflatex on the file after running latex on it,
242         /// in which case we will not need to run bibtex again.
243         vector<Aux_Info> bibtex_info_old;
244         if (!run_bibtex)
245                 bibtex_info_old = scanAuxFiles(aux_file);
246
247         ++count;
248         lyxerr[Debug::LATEX] << "Run #" << count << endl;
249         message(runMessage(count));
250
251         startscript();
252         scanres = scanLogFile(terr);
253         if (scanres & ERROR_RERUN) {
254                 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
255                 startscript();
256                 scanres = scanLogFile(terr);
257         }
258
259         if (scanres & ERRORS) {
260                 deleteFilesOnError();
261                 return scanres; // return on error
262         }
263
264         vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
265         if (!run_bibtex && bibtex_info_old != bibtex_info)
266                 run_bibtex = true;
267
268         // update the dependencies.
269         deplog(head); // reads the latex log
270         head.update();
271
272         // 0.5
273         // At this point we must run external programs if needed.
274         // makeindex will be run if a .idx file changed or was generated.
275         // And if there were undefined citations or changes in references
276         // the .aux file is checked for signs of bibtex. Bibtex is then run
277         // if needed.
278
279         // memoir (at least) writes an empty *idx file in the first place.
280         // A second latex run is needed.
281         FileName const idxfile(changeExtension(file.absFilename(), ".idx"));
282         rerun = fs::exists(idxfile.toFilesystemEncoding()) &&
283                 fs::is_empty(idxfile.toFilesystemEncoding());
284
285         // run makeindex
286         if (head.haschanged(idxfile)) {
287                 // no checks for now
288                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
289                 message(_("Running MakeIndex."));
290                 rerun |= runMakeIndex(onlyFilename(idxfile.absFilename()), runparams);
291         }
292         if (head.haschanged(FileName(changeExtension(file.absFilename(), ".nlo")))) {
293                 lyxerr[Debug::LATEX] << "Running MakeIndex for nomencl." << endl;
294                 message(_("Running MakeIndex for nomencl."));
295                 string const nomenclstr = " -s nomencl.ist -o " + changeExtension(file.toFilesystemEncoding(), ".nls");
296                 rerun |= runMakeIndex(onlyFilename(changeExtension(file.absFilename(), ".nlo")), runparams, nomenclstr);
297         }
298
299         // run bibtex
300         // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
301         if (scanres & UNDEF_CIT || run_bibtex) {
302                 // Here we must scan the .aux file and look for
303                 // "\bibdata" and/or "\bibstyle". If one of those
304                 // tags is found -> run bibtex and set rerun = true;
305                 // no checks for now
306                 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
307                 message(_("Running BibTeX."));
308                 updateBibtexDependencies(head, bibtex_info);
309                 rerun |= runBibTeX(bibtex_info);
310         } else if (!had_depfile) {
311                 /// If we run pdflatex on the file after running latex on it,
312                 /// then we do not need to run bibtex, but we do need to
313                 /// insert the .bib and .bst files into the .dep-pdf file.
314                 updateBibtexDependencies(head, bibtex_info);
315         }
316
317         // 1
318         // we know on this point that latex has been run once (or we just
319         // returned) and the question now is to decide if we need to run
320         // it any more. This is done by asking if any of the files in the
321         // dependency file has changed. (remember that the checksum for
322         // a given file is reported to have changed if it just was created)
323         //     -> if changed or rerun == true:
324         //             run latex once more and
325         //             update the dependency structure
326         //     -> if not changed:
327         //             we does nothing at this point
328         //
329         if (rerun || head.sumchange()) {
330                 rerun = false;
331                 ++count;
332                 lyxerr[Debug::DEPEND]
333                         << "Dep. file has changed or rerun requested" << endl;
334                 lyxerr[Debug::LATEX]
335                         << "Run #" << count << endl;
336                 message(runMessage(count));
337                 startscript();
338                 scanres = scanLogFile(terr);
339                 if (scanres & ERRORS) {
340                         deleteFilesOnError();
341                         return scanres; // return on error
342                 }
343
344                 // update the depedencies
345                 deplog(head); // reads the latex log
346                 head.update();
347         } else {
348                 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
349         }
350
351         // 1.5
352         // The inclusion of files generated by external programs like
353         // makeindex or bibtex might have done changes to pagenumbering,
354         // etc. And because of this we must run the external programs
355         // again to make sure everything is redone correctly.
356         // Also there should be no need to run the external programs any
357         // more after this.
358
359         // run makeindex if the <file>.idx has changed or was generated.
360         if (head.haschanged(FileName(changeExtension(file.absFilename(), ".idx")))) {
361                 // no checks for now
362                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
363                 message(_("Running MakeIndex."));
364                 rerun = runMakeIndex(onlyFilename(changeExtension(file.absFilename(), ".idx")), runparams);
365         }
366
367         // I am not pretty sure if need this twice. 
368         if (head.haschanged(FileName(changeExtension(file.absFilename(), ".nlo")))) {
369                 lyxerr[Debug::LATEX] << "Running MakeIndex for nomencl." << endl;
370                 message(_("Running MakeIndex for nomencl."));
371                 string nomenclstr = " -s nomencl.ist -o " + changeExtension(file.toFilesystemEncoding(), ".nls");
372                 rerun |= runMakeIndex(onlyFilename(changeExtension(file.absFilename(), ".nlo")), runparams, nomenclstr);
373         }
374
375         // 2
376         // we will only run latex more if the log file asks for it.
377         // or if the sumchange() is true.
378         //     -> rerun asked for:
379         //             run latex and
380         //             remake the dependency file
381         //             goto 2 or return if max runs are reached.
382         //     -> rerun not asked for:
383         //             just return (fall out of bottom of func)
384         //
385         while ((head.sumchange() || rerun || (scanres & RERUN))
386                && count < MAX_RUN) {
387                 // Yes rerun until message goes away, or until
388                 // MAX_RUNS are reached.
389                 rerun = false;
390                 ++count;
391                 lyxerr[Debug::LATEX] << "Run #" << count << endl;
392                 message(runMessage(count));
393                 startscript();
394                 scanres = scanLogFile(terr);
395                 if (scanres & ERRORS) {
396                         deleteFilesOnError();
397                         return scanres; // return on error
398                 }
399
400                 // keep this updated
401                 head.update();
402         }
403
404         // Write the dependencies to file.
405         head.write(depfile);
406         lyxerr[Debug::LATEX] << "Done." << endl;
407         return scanres;
408 }
409
410
411 int LaTeX::startscript()
412 {
413         string tmp = cmd + ' ' + quoteName(file.toFilesystemEncoding()) + " > " + os::nulldev();
414         Systemcall one;
415         return one.startscript(Systemcall::Wait, tmp);
416 }
417
418
419 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
420                          string const & params)
421 {
422         lyxerr[Debug::LATEX]
423                 << "idx file has been made, running makeindex on file "
424                 << f << endl;
425         string tmp = lyxrc.index_command + ' ';
426         
427         tmp = subst(tmp, "$$lang", runparams.document_language);
428         tmp += quoteName(f);
429         tmp += params;
430         Systemcall one;
431         one.startscript(Systemcall::Wait, tmp);
432         return true;
433 }
434
435
436 vector<Aux_Info> const
437 LaTeX::scanAuxFiles(FileName const & file)
438 {
439         vector<Aux_Info> result;
440
441         result.push_back(scanAuxFile(file));
442
443         string const basename = removeExtension(file.absFilename());
444         for (int i = 1; i < 1000; ++i) {
445                 FileName const file2(basename
446                         + '.' + convert<string>(i)
447                         + ".aux");
448                 if (!fs::exists(file2.toFilesystemEncoding()))
449                         break;
450                 result.push_back(scanAuxFile(file2));
451         }
452         return result;
453 }
454
455
456 Aux_Info const LaTeX::scanAuxFile(FileName const & file)
457 {
458         Aux_Info result;
459         result.aux_file = file;
460         scanAuxFile(file, result);
461         return result;
462 }
463
464
465 void LaTeX::scanAuxFile(FileName const & file, Aux_Info & aux_info)
466 {
467         lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
468
469         ifstream ifs(file.toFilesystemEncoding().c_str());
470         string token;
471         static regex const reg1("\\\\citation\\{([^}]+)\\}");
472         static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
473         static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
474         static regex const reg4("\\\\@input\\{([^}]+)\\}");
475
476         while (getline(ifs, token)) {
477                 token = rtrim(token, "\r");
478                 smatch sub;
479                 if (regex_match(token, sub, reg1)) {
480                         string data = sub.str(1);
481                         while (!data.empty()) {
482                                 string citation;
483                                 data = split(data, citation, ',');
484                                 lyxerr[Debug::LATEX] << "Citation: "
485                                                      << citation << endl;
486                                 aux_info.citations.insert(citation);
487                         }
488                 } else if (regex_match(token, sub, reg2)) {
489                         string data = sub.str(1);
490                         // data is now all the bib files separated by ','
491                         // get them one by one and pass them to the helper
492                         while (!data.empty()) {
493                                 string database;
494                                 data = split(data, database, ',');
495                                 database = changeExtension(database, "bib");
496                                 lyxerr[Debug::LATEX] << "BibTeX database: `"
497                                                      << database << '\'' << endl;
498                                 aux_info.databases.insert(database);
499                         }
500                 } else if (regex_match(token, sub, reg3)) {
501                         string style = sub.str(1);
502                         // token is now the style file
503                         // pass it to the helper
504                         style = changeExtension(style, "bst");
505                         lyxerr[Debug::LATEX] << "BibTeX style: `"
506                                              << style << '\'' << endl;
507                         aux_info.styles.insert(style);
508                 } else if (regex_match(token, sub, reg4)) {
509                         string const file2 = sub.str(1);
510                         scanAuxFile(FileName(makeAbsPath(file2)), aux_info);
511                 }
512         }
513 }
514
515
516 void LaTeX::updateBibtexDependencies(DepTable & dep,
517                                      vector<Aux_Info> const & bibtex_info)
518 {
519         // Since a run of Bibtex mandates more latex runs it is ok to
520         // remove all ".bib" and ".bst" files.
521         dep.remove_files_with_extension(".bib");
522         dep.remove_files_with_extension(".bst");
523         //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
524
525         for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
526              it != bibtex_info.end(); ++it) {
527                 for (set<string>::const_iterator it2 = it->databases.begin();
528                      it2 != it->databases.end(); ++it2) {
529                         FileName const file = findtexfile(*it2, "bib");
530                         if (!file.empty())
531                                 dep.insert(file, true);
532                 }
533
534                 for (set<string>::const_iterator it2 = it->styles.begin();
535                      it2 != it->styles.end(); ++it2) {
536                         FileName const file = findtexfile(*it2, "bst");
537                         if (!file.empty())
538                                 dep.insert(file, true);
539                 }
540         }
541 }
542
543
544 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
545 {
546         bool result = false;
547         for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
548              it != bibtex_info.end(); ++it) {
549                 if (it->databases.empty())
550                         continue;
551                 result = true;
552
553                 string tmp = lyxrc.bibtex_command + " ";
554                 tmp += quoteName(onlyFilename(removeExtension(it->aux_file.absFilename())));
555                 Systemcall one;
556                 one.startscript(Systemcall::Wait, tmp);
557         }
558         // Return whether bibtex was run
559         return result;
560 }
561
562
563 int LaTeX::scanLogFile(TeXErrors & terr)
564 {
565         int last_line = -1;
566         int line_count = 1;
567         int retval = NO_ERRORS;
568         string tmp = onlyFilename(changeExtension(file.absFilename(), ".log"));
569         lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
570         FileName const fn = FileName(makeAbsPath(tmp));
571         ifstream ifs(fn.toFilesystemEncoding().c_str());
572
573         string token;
574         while (getline(ifs, token)) {
575                 // MikTeX sometimes inserts \0 in the log file. They can't be
576                 // removed directly with the existing string utility
577                 // functions, so convert them first to \r, and remove all
578                 // \r's afterwards, since we need to remove them anyway.
579                 token = subst(token, '\0', '\r');
580                 token = subst(token, "\r", "");
581
582                 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
583
584                 if (token.empty())
585                         continue;
586
587                 if (prefixIs(token, "LaTeX Warning:") ||
588                     prefixIs(token, "! pdfTeX warning")) {
589                         // Here shall we handle different
590                         // types of warnings
591                         retval |= LATEX_WARNING;
592                         lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
593                         if (contains(token, "Rerun to get cross-references")) {
594                                 retval |= RERUN;
595                                 lyxerr[Debug::LATEX]
596                                         << "We should rerun." << endl;
597                         } else if (contains(token, "Citation")
598                                    && contains(token, "on page")
599                                    && contains(token, "undefined")) {
600                                 retval |= UNDEF_CIT;
601                         }
602                 } else if (prefixIs(token, "Package")) {
603                         // Package warnings
604                         retval |= PACKAGE_WARNING;
605                         if (contains(token, "natbib Warning:")) {
606                                 // Natbib warnings
607                                 if (contains(token, "Citation")
608                                     && contains(token, "on page")
609                                     && contains(token, "undefined")) {
610                                         retval |= UNDEF_CIT;
611                                 }
612                         } else if (contains(token, "run BibTeX")) {
613                                 retval |= UNDEF_CIT;
614                         } else if (contains(token, "Rerun LaTeX") ||
615                                    contains(token, "Rerun to get")) {
616                                 // at least longtable.sty and bibtopic.sty
617                                 // might use this.
618                                 lyxerr[Debug::LATEX]
619                                         << "We should rerun." << endl;
620                                 retval |= RERUN;
621                         }
622                 } else if (token[0] == '(') {
623                         if (contains(token, "Rerun LaTeX") ||
624                             contains(token, "Rerun to get")) {
625                                 // Used by natbib
626                                 lyxerr[Debug::LATEX]
627                                         << "We should rerun." << endl;
628                                 retval |= RERUN;
629                         }
630                 } else if (prefixIs(token, "! ")) {
631                         // Ok, we have something that looks like a TeX Error
632                         // but what do we really have.
633
634                         // Just get the error description:
635                         string desc(token, 2);
636                         if (contains(token, "LaTeX Error:"))
637                                 retval |= LATEX_ERROR;
638                         // get the next line
639                         string tmp;
640                         int count = 0;
641                         do {
642                                 if (!getline(ifs, tmp))
643                                         break;
644                                 if (++count > 10)
645                                         break;
646                         } while (!prefixIs(tmp, "l."));
647                         if (prefixIs(tmp, "l.")) {
648                                 // we have a latex error
649                                 retval |=  TEX_ERROR;
650                                 if (contains(desc, "Package babel Error: You haven't defined the language"))
651                                         retval |= ERROR_RERUN;
652                                 // get the line number:
653                                 int line = 0;
654                                 sscanf(tmp.c_str(), "l.%d", &line);
655                                 // get the rest of the message:
656                                 string errstr(tmp, tmp.find(' '));
657                                 errstr += '\n';
658                                 getline(ifs, tmp);
659                                 while (!contains(errstr, "l.")
660                                        && !tmp.empty()
661                                        && !prefixIs(tmp, "! ")
662                                        && !contains(tmp, "(job aborted")) {
663                                         errstr += tmp;
664                                         errstr += "\n";
665                                         getline(ifs, tmp);
666                                 }
667                                 lyxerr[Debug::LATEX]
668                                         << "line: " << line << '\n'
669                                         << "Desc: " << desc << '\n'
670                                         << "Text: " << errstr << endl;
671                                 if (line == last_line)
672                                         ++line_count;
673                                 else {
674                                         line_count = 1;
675                                         last_line = line;
676                                 }
677                                 if (line_count <= 5) {
678                                         // FIXME UNICODE
679                                         // We have no idea what the encoding of the log file is
680                                         // (probably pure ascii, but maybe some localized
681                                         // latex compilers or packages exist)
682                                         terr.insertError(line, from_utf8(desc), from_utf8(errstr));
683                                         ++num_errors;
684                                 }
685                         }
686                 } else {
687                         // information messages, TeX warnings and other
688                         // warnings we have not caught earlier.
689                         if (prefixIs(token, "Overfull ")) {
690                                 retval |= TEX_WARNING;
691                         } else if (prefixIs(token, "Underfull ")) {
692                                 retval |= TEX_WARNING;
693                         } else if (contains(token, "Rerun to get citations")) {
694                                 // Natbib seems to use this.
695                                 retval |= UNDEF_CIT;
696                         } else if (contains(token, "No pages of output")) {
697                                 // A dvi file was not created
698                                 retval |= NO_OUTPUT;
699                         } else if (contains(token, "That makes 100 errors")) {
700                                 // More than 100 errors were reprted
701                                 retval |= TOO_MANY_ERRORS;
702                         }
703                 }
704         }
705         lyxerr[Debug::LATEX] << "Log line: " << token << endl;
706         return retval;
707 }
708
709
710 namespace {
711
712 void handleFoundFile(string const & ff, DepTable & head)
713 {
714         // convert from native os path to unix path
715         string const foundfile = os::internal_path(trim(ff));
716
717         lyxerr[Debug::DEPEND] << "Found file: " << foundfile << endl;
718
719         // Ok now we found a file.
720         // Now we should make sure that this is a file that we can
721         // access through the normal paths.
722         // We will not try any fancy search methods to
723         // find the file.
724
725         // (1) foundfile is an
726         //     absolute path and should
727         //     be inserted.
728         if (absolutePath(foundfile)) {
729                 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
730                                       << foundfile << endl;
731                 // On initial insert we want to do the update at once
732                 // since this file cannot be a file generated by
733                 // the latex run.
734                 FileName const absname(foundfile);
735                 if (fs::exists(absname.toFilesystemEncoding()) &&
736                     !fs::is_directory(absname.toFilesystemEncoding()))
737                         head.insert(absname, true);
738
739                 return;
740         }
741
742         string const onlyfile = onlyFilename(foundfile);
743         FileName const absname(makeAbsPath(onlyfile));
744
745         // (2) foundfile is in the tmpdir
746         //     insert it into head
747         if (fs::exists(absname.toFilesystemEncoding())) {
748                 static regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
749                 if (regex_match(onlyfile, unwanted)) {
750                         lyxerr[Debug::DEPEND]
751                                 << "We don't want "
752                                 << onlyfile
753                                 << " in the dep file"
754                                 << endl;
755                 } else if (suffixIs(onlyfile, ".tex")) {
756                         // This is a tex file generated by LyX
757                         // and latex is not likely to change this
758                         // during its runs.
759                         lyxerr[Debug::DEPEND]
760                                 << "Tmpdir TeX file: "
761                                 << onlyfile
762                                 << endl;
763                         head.insert(absname, true);
764                 } else {
765                         lyxerr[Debug::DEPEND]
766                                 << "In tmpdir file:"
767                                 << onlyfile
768                                 << endl;
769                         head.insert(absname);
770                 }
771         } else
772                 lyxerr[Debug::DEPEND]
773                         << "Not a file or we are unable to find it."
774                         << endl;
775 }
776
777 } // anon namespace
778
779
780 void LaTeX::deplog(DepTable & head)
781 {
782         // This function reads the LaTeX log file end extracts all the external
783         // files used by the LaTeX run. The files are then entered into the
784         // dependency file.
785
786         string const logfile = onlyFilename(changeExtension(file.absFilename(), ".log"));
787
788         static regex reg1(".*\\([^)]+.*");
789         static regex reg2("File: ([^ ]+).*");
790         static regex reg3("No file ([^ ]+)\\..*");
791         static regex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
792         // If an index should be created, MikTex does not write a line like
793         //    \openout# = 'sample.idx'.
794         // but instead only a line like this into the log:
795         //   Writing index file sample.idx
796         static regex reg5("Writing index file ([^ ]+).*");
797         static regex regnomencl("Writing nomenclature file ([^ ]+).*");
798         // If a toc should be created, MikTex does not write a line like
799         //    \openout# = `sample.toc'.
800         // but only a line like this into the log:
801         //    \tf@toc=\write#
802         // This line is also written by tetex.
803         // This line is not present if no toc should be created.
804         static regex miktexTocReg("\\\\tf@toc=\\\\write.*");
805
806         FileName const fn = FileName(makeAbsPath(logfile));
807         ifstream ifs(fn.toFilesystemEncoding().c_str());
808         while (ifs) {
809                 // Ok, the scanning of files here is not sufficient.
810                 // Sometimes files are named by "File: xxx" only
811                 // So I think we should use some regexps to find files instead.
812                 // "(\([^ ]+\)"   should match the "(file " variant, note
813                 // that we can have several of these on one line.
814                 // "File: \([^ ]+\)" should match the "File: file" variant
815
816                 string token;
817                 getline(ifs, token);
818                 // MikTeX sometimes inserts \0 in the log file. They can't be
819                 // removed directly with the existing string utility
820                 // functions, so convert them first to \r, and remove all
821                 // \r's afterwards, since we need to remove them anyway.
822                 token = subst(token, '\0', '\r');
823                 token = subst(token, "\r", "");
824                 if (token.empty())
825                         continue;
826
827                 smatch sub;
828
829                 if (regex_match(token, sub, reg1)) {
830                         static regex reg1_1("\\(([^()]+)");
831                         smatch what;
832                         string::const_iterator first = token.begin();
833                         string::const_iterator end = token.end();
834
835                         while (regex_search(first, end, what, reg1_1)) {
836                                 first = what[0].second;
837                                 handleFoundFile(what.str(1), head);
838                         }
839                 } else if (regex_match(token, sub, reg2))
840                         handleFoundFile(sub.str(1), head);
841                 else if (regex_match(token, sub, reg3))
842                         handleFoundFile(sub.str(1), head);
843                 else if (regex_match(token, sub, reg4))
844                         handleFoundFile(sub.str(1), head);
845                 else if (regex_match(token, sub, reg5))
846                         handleFoundFile(sub.str(1), head);
847                 else if (regex_match(token, sub, regnomencl))
848                         handleFoundFile(sub.str(1), head);
849                 else if (regex_match(token, sub, miktexTocReg))
850                         handleFoundFile(onlyFilename(changeExtension(file.absFilename(), ".toc")), head);
851         }
852
853         // Make sure that the main .tex file is in the dependancy file.
854         head.insert(file, true);
855 }
856
857
858 } // namespace lyx