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