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