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