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