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