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