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