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