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