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