]> git.lyx.org Git - lyx.git/blob - src/LaTeX.C
934b233ffbb69ae4817754ddb870b557f2154940
[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::findtexfile;
44 using support::getcwd;
45 using support::onlyFilename;
46 using support::prefixIs;
47 using support::quoteName;
48 using support::rtrim;
49 using support::split;
50 using support::subst;
51 using support::suffixIs;
52 using support::Systemcall;
53 using support::unlink;
54 using support::trim;
55
56 namespace os = support::os;
57 namespace fs = boost::filesystem;
58
59 using boost::regex;
60 using boost::smatch;
61
62
63 #ifndef CXX_GLOBAL_CSTD
64 using std::sscanf;
65 #endif
66
67 using std::endl;
68 using std::getline;
69 using std::string;
70 using std::ifstream;
71 using std::set;
72 using std::vector;
73
74 // TODO: in no particular order
75 // - get rid of the call to
76 //   BufferList::updateIncludedTeXfiles, this should either
77 //   be done before calling LaTeX::funcs or in a completely
78 //   different way.
79 // - the makeindex style files should be taken care of with
80 //   the dependency mechanism.
81 // - makeindex commandline options should be supported
82 // - somewhere support viewing of bibtex and makeindex log files.
83 // - we should perhaps also scan the bibtex log file
84
85 namespace {
86
87 docstring runMessage(unsigned int count)
88 {
89         return bformat(_("Waiting for LaTeX run number %1$d"), count);
90 }
91
92 } // anon namespace
93
94 /*
95  * CLASS TEXERRORS
96  */
97
98 void TeXErrors::insertError(int line, string const & error_desc,
99                             string const & error_text)
100 {
101         Error newerr(line, error_desc, error_text);
102         errors.push_back(newerr);
103 }
104
105
106 bool operator==(Aux_Info const & a, Aux_Info const & o)
107 {
108         return a.aux_file == o.aux_file &&
109                 a.citations == o.citations &&
110                 a.databases == o.databases &&
111                 a.styles == o.styles;
112 }
113
114
115 bool operator!=(Aux_Info const & a, Aux_Info const & o)
116 {
117         return !(a == o);
118 }
119
120
121 /*
122  * CLASS LaTeX
123  */
124
125 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
126              string const & f, string const & p)
127         : cmd(latex), file(f), path(p), runparams(rp)
128 {
129         num_errors = 0;
130         depfile = file + ".dep";
131         if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
132                 depfile += "-pdf";
133                 output_file = changeExtension(file,".pdf");
134         } else {
135                 output_file = changeExtension(file,".dvi");
136         }
137 }
138
139
140 void LaTeX::deleteFilesOnError() const
141 {
142         // currently just a dummy function.
143
144         // What files do we have to delete?
145
146         // This will at least make latex do all the runs
147         unlink(depfile);
148
149         // but the reason for the error might be in a generated file...
150
151         string const ofname = onlyFilename(file);
152
153         // bibtex file
154         string const bbl = changeExtension(ofname, ".bbl");
155         unlink(bbl);
156
157         // makeindex file
158         string const ind = changeExtension(ofname, ".ind");
159         unlink(ind);
160
161         // Also remove the aux file
162         string const aux = changeExtension(ofname, ".aux");
163         unlink(aux);
164 }
165
166
167 int LaTeX::run(TeXErrors & terr)
168         // We know that this function will only be run if the lyx buffer
169         // has been changed. We also know that a newly written .tex file
170         // is always different from the previous one because of the date
171         // in it. However it seems safe to run latex (at least) on time each
172         // time the .tex file changes.
173 {
174         int scanres = NO_ERRORS;
175         unsigned int count = 0; // number of times run
176         num_errors = 0; // just to make sure.
177         unsigned int const MAX_RUN = 6;
178         DepTable head; // empty head
179         bool rerun = false; // rerun requested
180
181         // The class LaTeX does not know the temp path.
182         theBufferList().updateIncludedTeXfiles(getcwd(), runparams);
183
184         // Never write the depfile if an error was encountered.
185
186         // 0
187         // first check if the file dependencies exist:
188         //     ->If it does exist
189         //             check if any of the files mentioned in it have
190         //             changed (done using a checksum).
191         //                 -> if changed:
192         //                        run latex once and
193         //                        remake the dependency file
194         //                 -> if not changed:
195         //                        just return there is nothing to do for us.
196         //     ->if it doesn't exist
197         //             make it and
198         //             run latex once (we need to run latex once anyway) and
199         //             remake the dependency file.
200         //
201
202         bool had_depfile = fs::exists(depfile);
203         bool run_bibtex = false;
204         string aux_file = onlyFilename(changeExtension(file, "aux"));
205
206         if (had_depfile) {
207                 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
208                 // Read the dep file:
209                 had_depfile = head.read(depfile);
210         }
211
212         if (had_depfile) {
213                 // Update the checksums
214                 head.update();
215                 // Can't just check if anything has changed because it might have aborted
216                 // on error last time... in which cas we need to re-run latex
217                 // and collect the error messages (even if they are the same).
218                 if (!fs::exists(output_file)) {
219                         lyxerr[Debug::DEPEND]
220                                 << "re-running LaTeX because output file doesn't exist." << endl;
221                 } else if (!head.sumchange()) {
222                         lyxerr[Debug::DEPEND] << "return no_change" << endl;
223                         return NO_CHANGE;
224                 } else {
225                         lyxerr[Debug::DEPEND]
226                                 << "Dependency file has changed" << endl;
227                 }
228
229                 if (head.extchanged(".bib") || head.extchanged(".bst"))
230                         run_bibtex = true;
231         } else
232                 lyxerr[Debug::DEPEND]
233                         << "Dependency file does not exist, or has wrong format" << endl;
234
235         /// We scan the aux file even when had_depfile = false,
236         /// because we can run pdflatex on the file after running latex on it,
237         /// in which case we will not need to run bibtex again.
238         vector<Aux_Info> bibtex_info_old;
239         if (!run_bibtex)
240                 bibtex_info_old = scanAuxFiles(aux_file);
241
242         ++count;
243         lyxerr[Debug::LATEX] << "Run #" << count << endl;
244         message(runMessage(count));
245
246         startscript();
247         scanres = scanLogFile(terr);
248         if (scanres & ERROR_RERUN) {
249                 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
250                 startscript();
251                 scanres = scanLogFile(terr);
252         }
253
254         if (scanres & ERRORS) {
255                 deleteFilesOnError();
256                 return scanres; // return on error
257         }
258
259         vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
260         if (!run_bibtex && bibtex_info_old != bibtex_info)
261                 run_bibtex = true;
262
263         // update the dependencies.
264         deplog(head); // reads the latex log
265         head.update();
266
267         // 0.5
268         // At this point we must run external programs if needed.
269         // makeindex will be run if a .idx file changed or was generated.
270         // And if there were undefined citations or changes in references
271         // the .aux file is checked for signs of bibtex. Bibtex is then run
272         // if needed.
273
274         // memoir (at least) writes an empty *idx file in the first place.
275         // A second latex run is needed.
276         rerun = fs::exists(changeExtension(file, ".idx"))
277                 && fs::is_empty(changeExtension(file, ".idx"));
278
279         // run makeindex
280         if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
281                 // no checks for now
282                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
283                 message(_("Running MakeIndex."));
284                 rerun |= runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
285         }
286
287         // run bibtex
288         // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
289         if (scanres & UNDEF_CIT || run_bibtex) {
290                 // Here we must scan the .aux file and look for
291                 // "\bibdata" and/or "\bibstyle". If one of those
292                 // tags is found -> run bibtex and set rerun = true;
293                 // no checks for now
294                 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
295                 message(_("Running BibTeX."));
296                 updateBibtexDependencies(head, bibtex_info);
297                 rerun |= runBibTeX(bibtex_info);
298         } else if (!had_depfile) {
299                 /// If we run pdflatex on the file after running latex on it,
300                 /// then we do not need to run bibtex, but we do need to
301                 /// insert the .bib and .bst files into the .dep-pdf file.
302                 updateBibtexDependencies(head, bibtex_info);
303         }
304
305         // 1
306         // we know on this point that latex has been run once (or we just
307         // returned) and the question now is to decide if we need to run
308         // it any more. This is done by asking if any of the files in the
309         // dependency file has changed. (remember that the checksum for
310         // a given file is reported to have changed if it just was created)
311         //     -> if changed or rerun == true:
312         //             run latex once more and
313         //             update the dependency structure
314         //     -> if not changed:
315         //             we does nothing at this point
316         //
317         if (rerun || head.sumchange()) {
318                 rerun = false;
319                 ++count;
320                 lyxerr[Debug::DEPEND]
321                         << "Dep. file has changed or rerun requested" << endl;
322                 lyxerr[Debug::LATEX]
323                         << "Run #" << count << endl;
324                 message(runMessage(count));
325                 startscript();
326                 scanres = scanLogFile(terr);
327                 if (scanres & ERRORS) {
328                         deleteFilesOnError();
329                         return scanres; // return on error
330                 }
331
332                 // update the depedencies
333                 deplog(head); // reads the latex log
334                 head.update();
335         } else {
336                 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
337         }
338
339         // 1.5
340         // The inclusion of files generated by external programs like
341         // makeindex or bibtex might have done changes to pagenumbering,
342         // etc. And because of this we must run the external programs
343         // again to make sure everything is redone correctly.
344         // Also there should be no need to run the external programs any
345         // more after this.
346
347         // run makeindex if the <file>.idx has changed or was generated.
348         if (head.haschanged(onlyFilename(changeExtension(file, ".idx")))) {
349                 // no checks for now
350                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
351                 message(_("Running MakeIndex."));
352                 rerun = runMakeIndex(onlyFilename(changeExtension(file, ".idx")), runparams);
353         }
354
355         // 2
356         // we will only run latex more if the log file asks for it.
357         // or if the sumchange() is true.
358         //     -> rerun asked for:
359         //             run latex and
360         //             remake the dependency file
361         //             goto 2 or return if max runs are reached.
362         //     -> rerun not asked for:
363         //             just return (fall out of bottom of func)
364         //
365         while ((head.sumchange() || rerun || (scanres & RERUN))
366                && count < MAX_RUN) {
367                 // Yes rerun until message goes away, or until
368                 // MAX_RUNS are reached.
369                 rerun = false;
370                 ++count;
371                 lyxerr[Debug::LATEX] << "Run #" << count << endl;
372                 message(runMessage(count));
373                 startscript();
374                 scanres = scanLogFile(terr);
375                 if (scanres & ERRORS) {
376                         deleteFilesOnError();
377                         return scanres; // return on error
378                 }
379
380                 // keep this updated
381                 head.update();
382         }
383
384         // Write the dependencies to file.
385         head.write(depfile);
386         lyxerr[Debug::LATEX] << "Done." << endl;
387         return scanres;
388 }
389
390
391 int LaTeX::startscript()
392 {
393         string tmp = cmd + ' ' + quoteName(file) + " > " + os::nulldev();
394         Systemcall one;
395         return one.startscript(Systemcall::Wait, tmp);
396 }
397
398
399 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams)
400 {
401         lyxerr[Debug::LATEX] << "idx file has been made,"
402                 " running makeindex on file " <<  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 }
819
820
821 } // namespace lyx