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