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