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