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