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