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