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