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