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