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