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