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