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