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