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