]> git.lyx.org Git - lyx.git/blob - src/LaTeX.C
hopefully fix tex2lyx linking.
[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::findtexfile;
44 using support::getcwd;
45 using support::onlyFilename;
46 using support::prefixIs;
47 using support::quoteName;
48 using support::rtrim;
49 using support::split;
50 using support::subst;
51 using support::suffixIs;
52 using support::Systemcall;
53 using support::unlink;
54 using support::trim;
55
56 namespace os = support::os;
57 namespace fs = boost::filesystem;
58
59 using boost::regex;
60 using boost::smatch;
61
62
63 #ifndef CXX_GLOBAL_CSTD
64 using std::sscanf;
65 #endif
66
67 using std::endl;
68 using std::getline;
69 using std::string;
70 using std::ifstream;
71 using std::set;
72 using std::vector;
73
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
78 //   different way.
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
84
85 namespace {
86
87 docstring runMessage(unsigned int count)
88 {
89         return bformat(_("Waiting for LaTeX run number %1$d"), count);
90 }
91
92 } // anon namespace
93
94 /*
95  * CLASS TEXERRORS
96  */
97
98 void TeXErrors::insertError(int line, docstring const & error_desc,
99                             docstring const & error_text)
100 {
101         Error newerr(line, error_desc, error_text);
102         errors.push_back(newerr);
103 }
104
105
106 bool operator==(Aux_Info const & a, Aux_Info const & o)
107 {
108         return a.aux_file == o.aux_file &&
109                 a.citations == o.citations &&
110                 a.databases == o.databases &&
111                 a.styles == o.styles;
112 }
113
114
115 bool operator!=(Aux_Info const & a, Aux_Info const & o)
116 {
117         return !(a == o);
118 }
119
120
121 /*
122  * CLASS LaTeX
123  */
124
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)
128 {
129         num_errors = 0;
130         depfile = file + ".dep";
131         if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
132                 depfile += "-pdf";
133                 output_file = changeExtension(file,".pdf");
134         } else {
135                 output_file = changeExtension(file,".dvi");
136         }
137 }
138
139
140 void LaTeX::deleteFilesOnError() const
141 {
142         // currently just a dummy function.
143
144         // What files do we have to delete?
145
146         // This will at least make latex do all the runs
147         unlink(depfile);
148
149         // but the reason for the error might be in a generated file...
150
151         string const ofname = onlyFilename(file);
152
153         // bibtex file
154         string const bbl = changeExtension(ofname, ".bbl");
155         unlink(bbl);
156
157         // makeindex file
158         string const ind = changeExtension(ofname, ".ind");
159         unlink(ind);
160
161         // nomencl file
162         string const nls = changeExtension(ofname, ".nls");
163         unlink(nls);
164
165         // Also remove the aux file
166         string const aux = changeExtension(ofname, ".aux");
167         unlink(aux);
168 }
169
170
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.
177 {
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
184
185         // The class LaTeX does not know the temp path.
186         theBufferList().updateIncludedTeXfiles(getcwd(), runparams);
187
188         // Never write the depfile if an error was encountered.
189
190         // 0
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).
195         //                 -> if changed:
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
201         //             make it and
202         //             run latex once (we need to run latex once anyway) and
203         //             remake the dependency file.
204         //
205
206         bool had_depfile = fs::exists(depfile);
207         bool run_bibtex = false;
208         string aux_file = onlyFilename(changeExtension(file, "aux"));
209
210         if (had_depfile) {
211                 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
212                 // Read the dep file:
213                 had_depfile = head.read(depfile);
214         }
215
216         if (had_depfile) {
217                 // Update the checksums
218                 head.update();
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;
227                         return NO_CHANGE;
228                 } else {
229                         lyxerr[Debug::DEPEND]
230                                 << "Dependency file has changed" << endl;
231                 }
232
233                 if (head.extchanged(".bib") || head.extchanged(".bst"))
234                         run_bibtex = true;
235         } else
236                 lyxerr[Debug::DEPEND]
237                         << "Dependency file does not exist, or has wrong format" << endl;
238
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;
243         if (!run_bibtex)
244                 bibtex_info_old = scanAuxFiles(aux_file);
245
246         ++count;
247         lyxerr[Debug::LATEX] << "Run #" << count << endl;
248         message(runMessage(count));
249
250         startscript();
251         scanres = scanLogFile(terr);
252         if (scanres & ERROR_RERUN) {
253                 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
254                 startscript();
255                 scanres = scanLogFile(terr);
256         }
257
258         if (scanres & ERRORS) {
259                 deleteFilesOnError();
260                 return scanres; // return on error
261         }
262
263         vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
264         if (!run_bibtex && bibtex_info_old != bibtex_info)
265                 run_bibtex = true;
266
267         // update the dependencies.
268         deplog(head); // reads the latex log
269         head.update();
270
271         // 0.5
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
276         // if needed.
277
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"));
282
283         // run makeindex
284         if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
285                 // no checks for now
286                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
287                 message(_("Running MakeIndex."));
288                 rerun |= runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
289         }
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);
295         }
296
297         // run bibtex
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;
303                 // no checks for now
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);
313         }
314
315         // 1
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
326         //
327         if (rerun || head.sumchange()) {
328                 rerun = false;
329                 ++count;
330                 lyxerr[Debug::DEPEND]
331                         << "Dep. file has changed or rerun requested" << endl;
332                 lyxerr[Debug::LATEX]
333                         << "Run #" << count << endl;
334                 message(runMessage(count));
335                 startscript();
336                 scanres = scanLogFile(terr);
337                 if (scanres & ERRORS) {
338                         deleteFilesOnError();
339                         return scanres; // return on error
340                 }
341
342                 // update the depedencies
343                 deplog(head); // reads the latex log
344                 head.update();
345         } else {
346                 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
347         }
348
349         // 1.5
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
355         // more after this.
356
357         // run makeindex if the <file>.idx has changed or was generated.
358         if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
359                 // no checks for now
360                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
361                 message(_("Running MakeIndex."));
362                 rerun = runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
363         }
364
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);
371         }
372
373         // 2
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:
377         //             run latex and
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)
382         //
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.
387                 rerun = false;
388                 ++count;
389                 lyxerr[Debug::LATEX] << "Run #" << count << endl;
390                 message(runMessage(count));
391                 startscript();
392                 scanres = scanLogFile(terr);
393                 if (scanres & ERRORS) {
394                         deleteFilesOnError();
395                         return scanres; // return on error
396                 }
397
398                 // keep this updated
399                 head.update();
400         }
401
402         // Write the dependencies to file.
403         head.write(depfile);
404         lyxerr[Debug::LATEX] << "Done." << endl;
405         return scanres;
406 }
407
408
409 int LaTeX::startscript()
410 {
411         string tmp = cmd + ' ' + quoteName(file) + " > " + os::nulldev();
412         Systemcall one;
413         return one.startscript(Systemcall::Wait, tmp);
414 }
415
416
417 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
418                          string const & params)
419 {
420         lyxerr[Debug::LATEX]
421                 << "idx file has been made, running makeindex on file "
422                 << f << endl;
423         string tmp = lyxrc.index_command + ' ';
424         
425         tmp = subst(tmp, "$$lang", runparams.document_language);
426         tmp += quoteName(f);
427         tmp += params;
428         Systemcall one;
429         one.startscript(Systemcall::Wait, tmp);
430         return true;
431 }
432
433
434 vector<Aux_Info> const
435 LaTeX::scanAuxFiles(string const & file)
436 {
437         vector<Aux_Info> result;
438
439         result.push_back(scanAuxFile(file));
440
441         for (int i = 1; i < 1000; ++i) {
442                 string const file2 = changeExtension(file, "")
443                         + '.' + convert<string>(i)
444                         + ".aux";
445                 if (!fs::exists(file2))
446                         break;
447                 result.push_back(scanAuxFile(file2));
448         }
449         return result;
450 }
451
452
453 Aux_Info const LaTeX::scanAuxFile(string const & file)
454 {
455         Aux_Info result;
456         result.aux_file = file;
457         scanAuxFile(file, result);
458         return result;
459 }
460
461
462 void LaTeX::scanAuxFile(string const & file, Aux_Info & aux_info)
463 {
464         lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
465
466         ifstream ifs(file.c_str());
467         string token;
468         static regex const reg1("\\\\citation\\{([^}]+)\\}");
469         static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
470         static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
471         static regex const reg4("\\\\@input\\{([^}]+)\\}");
472
473         while (getline(ifs, token)) {
474                 token = rtrim(token, "\r");
475                 smatch sub;
476                 if (regex_match(token, sub, reg1)) {
477                         string data = sub.str(1);
478                         while (!data.empty()) {
479                                 string citation;
480                                 data = split(data, citation, ',');
481                                 lyxerr[Debug::LATEX] << "Citation: "
482                                                      << citation << endl;
483                                 aux_info.citations.insert(citation);
484                         }
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()) {
490                                 string database;
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);
496                         }
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);
508                 }
509         }
510 }
511
512
513 void LaTeX::updateBibtexDependencies(DepTable & dep,
514                                      vector<Aux_Info> const & bibtex_info)
515 {
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"));
521
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");
527                         if (!file.empty())
528                                 dep.insert(file, true);
529                 }
530
531                 for (set<string>::const_iterator it2 = it->styles.begin();
532                      it2 != it->styles.end(); ++it2) {
533                         string file = findtexfile(*it2, "bst");
534                         if (!file.empty())
535                                 dep.insert(file, true);
536                 }
537         }
538 }
539
540
541 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
542 {
543         bool result = false;
544         for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
545              it != bibtex_info.end(); ++it) {
546                 if (it->databases.empty())
547                         continue;
548                 result = true;
549
550                 string tmp = lyxrc.bibtex_command + " ";
551                 tmp += quoteName(onlyFilename(changeExtension(it->aux_file, string())));
552                 Systemcall one;
553                 one.startscript(Systemcall::Wait, tmp);
554         }
555         // Return whether bibtex was run
556         return result;
557 }
558
559
560 int LaTeX::scanLogFile(TeXErrors & terr)
561 {
562         int last_line = -1;
563         int line_count = 1;
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());
568
569         string token;
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", "");
577
578                 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
579
580                 if (token.empty())
581                         continue;
582
583                 if (prefixIs(token, "LaTeX Warning:") ||
584                     prefixIs(token, "! pdfTeX warning")) {
585                         // Here shall we handle different
586                         // types of warnings
587                         retval |= LATEX_WARNING;
588                         lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
589                         if (contains(token, "Rerun to get cross-references")) {
590                                 retval |= RERUN;
591                                 lyxerr[Debug::LATEX]
592                                         << "We should rerun." << endl;
593                         } else if (contains(token, "Citation")
594                                    && contains(token, "on page")
595                                    && contains(token, "undefined")) {
596                                 retval |= UNDEF_CIT;
597                         }
598                 } else if (prefixIs(token, "Package")) {
599                         // Package warnings
600                         retval |= PACKAGE_WARNING;
601                         if (contains(token, "natbib Warning:")) {
602                                 // Natbib warnings
603                                 if (contains(token, "Citation")
604                                     && contains(token, "on page")
605                                     && contains(token, "undefined")) {
606                                         retval |= UNDEF_CIT;
607                                 }
608                         } else if (contains(token, "run BibTeX")) {
609                                 retval |= UNDEF_CIT;
610                         } else if (contains(token, "Rerun LaTeX") ||
611                                    contains(token, "Rerun to get")) {
612                                 // at least longtable.sty and bibtopic.sty
613                                 // might use this.
614                                 lyxerr[Debug::LATEX]
615                                         << "We should rerun." << endl;
616                                 retval |= RERUN;
617                         }
618                 } else if (token[0] == '(') {
619                         if (contains(token, "Rerun LaTeX") ||
620                             contains(token, "Rerun to get")) {
621                                 // Used by natbib
622                                 lyxerr[Debug::LATEX]
623                                         << "We should rerun." << endl;
624                                 retval |= RERUN;
625                         }
626                 } else if (prefixIs(token, "! ")) {
627                         // Ok, we have something that looks like a TeX Error
628                         // but what do we really have.
629
630                         // Just get the error description:
631                         string desc(token, 2);
632                         if (contains(token, "LaTeX Error:"))
633                                 retval |= LATEX_ERROR;
634                         // get the next line
635                         string tmp;
636                         int count = 0;
637                         do {
638                                 if (!getline(ifs, tmp))
639                                         break;
640                                 if (++count > 10)
641                                         break;
642                         } while (!prefixIs(tmp, "l."));
643                         if (prefixIs(tmp, "l.")) {
644                                 // we have a latex error
645                                 retval |=  TEX_ERROR;
646                                 if (contains(desc, "Package babel Error: You haven't defined the language"))
647                                         retval |= ERROR_RERUN;
648                                 // get the line number:
649                                 int line = 0;
650                                 sscanf(tmp.c_str(), "l.%d", &line);
651                                 // get the rest of the message:
652                                 string errstr(tmp, tmp.find(' '));
653                                 errstr += '\n';
654                                 getline(ifs, tmp);
655                                 while (!contains(errstr, "l.")
656                                        && !tmp.empty()
657                                        && !prefixIs(tmp, "! ")
658                                        && !contains(tmp, "(job aborted")) {
659                                         errstr += tmp;
660                                         errstr += "\n";
661                                         getline(ifs, tmp);
662                                 }
663                                 lyxerr[Debug::LATEX]
664                                         << "line: " << line << '\n'
665                                         << "Desc: " << desc << '\n'
666                                         << "Text: " << errstr << endl;
667                                 if (line == last_line)
668                                         ++line_count;
669                                 else {
670                                         line_count = 1;
671                                         last_line = line;
672                                 }
673                                 if (line_count <= 5) {
674                                         // FIXME UNICODE
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));
679                                         ++num_errors;
680                                 }
681                         }
682                 } else {
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.
691                                 retval |= UNDEF_CIT;
692                         } else if (contains(token, "No pages of output")) {
693                                 // A dvi file was not created
694                                 retval |= NO_OUTPUT;
695                         } else if (contains(token, "That makes 100 errors")) {
696                                 // More than 100 errors were reprted
697                                 retval |= TOO_MANY_ERRORS;
698                         }
699                 }
700         }
701         lyxerr[Debug::LATEX] << "Log line: " << token << endl;
702         return retval;
703 }
704
705
706 namespace {
707
708 void handleFoundFile(string const & ff, DepTable & head)
709 {
710         // convert from native os path to unix path
711         string const foundfile = os::internal_path(trim(ff));
712
713         lyxerr[Debug::DEPEND] << "Found file: " << foundfile << endl;
714
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
719         // find the file.
720
721         // (1) foundfile is an
722         //     absolute path and should
723         //     be inserted.
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
729                 // the latex run.
730                 if (fs::exists(foundfile) && !fs::is_directory(foundfile))
731                         head.insert(foundfile, true);
732
733                 return;
734         }
735
736         string const onlyfile = onlyFilename(foundfile);
737
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]
744                                 << "We don't want "
745                                 << onlyfile
746                                 << " in the dep file"
747                                 << endl;
748                 } else if (suffixIs(onlyfile, ".tex")) {
749                         // This is a tex file generated by LyX
750                         // and latex is not likely to change this
751                         // during its runs.
752                         lyxerr[Debug::DEPEND]
753                                 << "Tmpdir TeX file: "
754                                 << onlyfile
755                                 << endl;
756                         head.insert(onlyfile, true);
757                 } else {
758                         lyxerr[Debug::DEPEND]
759                                 << "In tmpdir file:"
760                                 << onlyfile
761                                 << endl;
762                         head.insert(onlyfile);
763                 }
764         } else
765                 lyxerr[Debug::DEPEND]
766                         << "Not a file or we are unable to find it."
767                         << endl;
768 }
769
770 } // anon namespace
771
772
773 void LaTeX::deplog(DepTable & head)
774 {
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
777         // dependency file.
778
779         string const logfile = onlyFilename(changeExtension(file, ".log"));
780
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:
794         //    \tf@toc=\write#
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.*");
798
799         ifstream ifs(logfile.c_str());
800         while (ifs) {
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
807
808                 string token;
809                 getline(ifs, token);
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", "");
816                 if (token.empty())
817                         continue;
818
819                 smatch sub;
820
821                 if (regex_match(token, sub, reg1)) {
822                         static regex reg1_1("\\(([^()]+)");
823                         smatch what;
824                         string::const_iterator first = token.begin();
825                         string::const_iterator end = token.end();
826
827                         while (regex_search(first, end, what, reg1_1)) {
828                                 first = what[0].second;
829                                 handleFoundFile(what.str(1), head);
830                         }
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);
843         }
844
845         // Make sure that the main .tex file is in the dependancy file.
846         head.insert(onlyFilename(file), true);
847 }
848
849
850 } // namespace lyx