]> git.lyx.org Git - lyx.git/blob - src/LaTeX.cpp
More requires --> required, for C++2a.
[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) as well
518                 // as input markup (latex or xelatex)
519                 string xdyopts = rp.xindy_language;
520                 if (!xdyopts.empty())
521                         xdyopts = "-L " + xdyopts;
522                 if (rp.isFullUnicode() && rp.encoding->package() == Encoding::none) {
523                         if (!xdyopts.empty())
524                                 xdyopts += " ";
525                         // xelatex includes lualatex
526                         xdyopts += "-I xelatex";
527                 }
528                 else if (rp.encoding->iconvName() == "UTF-8") {
529                         if (!xdyopts.empty())
530                                 xdyopts += " ";
531                         // -I not really needed for texindy, but for xindy
532                         xdyopts += "-C utf8 -I latex";
533                 }
534                 else {
535                         if (!xdyopts.empty())
536                                 xdyopts += " ";
537                         // not really needed for texindy, but for xindy
538                         xdyopts += "-I latex";
539                 }
540                 tmp = subst(tmp, "$$x", xdyopts);
541         }
542
543         if (contains(tmp, "$$b")) {
544                 // advise xindy to write a log file
545                 tmp = subst(tmp, "$$b", removeExtension(f));
546         }
547
548         LYXERR(Debug::LATEX,
549                 "idx file has been made, running index processor ("
550                 << tmp << ") on file " << f);
551
552         tmp = subst(tmp, "$$lang", rp.document_language);
553         if (rp.use_indices) {
554                 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
555                 LYXERR(Debug::LATEX,
556                 "Multiple indices. Using splitindex command: " << tmp);
557         }
558         tmp += ' ';
559         tmp += quoteName(f);
560         tmp += params;
561         Systemcall one;
562         Systemcall::Starttype const starttype = 
563                 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
564         return one.startscript(starttype, tmp, path, lpath, true);
565 }
566
567
568 int LaTeX::runMakeIndexNomencl(FileName const & fname,
569                 string const & nlo, string const & nls)
570 {
571         LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
572         message(_("Running MakeIndex for nomencl."));
573         string tmp = lyxrc.nomencl_command + ' ';
574         // onlyFileName() is needed for cygwin
575         tmp += quoteName(onlyFileName(changeExtension(fname.absFileName(), nlo)));
576         tmp += " -o "
577                 + onlyFileName(changeExtension(fname.toFilesystemEncoding(), nls));
578         Systemcall one;
579         Systemcall::Starttype const starttype = 
580                 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
581         return one.startscript(starttype, tmp, path, lpath, true);
582 }
583
584
585 vector<AuxInfo> const
586 LaTeX::scanAuxFiles(FileName const & fname, bool const only_childbibs)
587 {
588         vector<AuxInfo> result;
589
590         // With chapterbib, we have to bibtex all children's aux files
591         // but _not_ the master's!
592         if (only_childbibs) {
593                 for (string const &s: children) {
594                         FileName fn =
595                                 makeAbsPath(s, fname.onlyPath().realPath());
596                         fn.changeExtension("aux");
597                         if (fn.exists())
598                                 result.push_back(scanAuxFile(fn));
599                 }
600                 return result;
601         }
602
603         result.push_back(scanAuxFile(fname));
604
605         // This is for bibtopic
606         string const basename = removeExtension(fname.absFileName());
607         for (int i = 1; i < 1000; ++i) {
608                 FileName const file2(basename
609                         + '.' + convert<string>(i)
610                         + ".aux");
611                 if (!file2.exists())
612                         break;
613                 result.push_back(scanAuxFile(file2));
614         }
615         return result;
616 }
617
618
619 AuxInfo const LaTeX::scanAuxFile(FileName const & fname)
620 {
621         AuxInfo result;
622         result.aux_file = fname;
623         scanAuxFile(fname, result);
624         return result;
625 }
626
627
628 void LaTeX::scanAuxFile(FileName const & fname, AuxInfo & aux_info)
629 {
630         LYXERR(Debug::LATEX, "Scanning aux file: " << fname);
631
632         ifstream ifs(fname.toFilesystemEncoding().c_str());
633         string token;
634         static regex const reg1("\\\\citation\\{([^}]+)\\}");
635         static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
636         static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
637         static regex const reg4("\\\\@input\\{([^}]+)\\}");
638
639         while (getline(ifs, token)) {
640                 token = rtrim(token, "\r");
641                 smatch sub;
642                 // FIXME UNICODE: We assume that citation keys and filenames
643                 // in the aux file are in the file system encoding.
644                 token = to_utf8(from_filesystem8bit(token));
645                 if (regex_match(token, sub, reg1)) {
646                         string data = sub.str(1);
647                         while (!data.empty()) {
648                                 string citation;
649                                 data = split(data, citation, ',');
650                                 LYXERR(Debug::LATEX, "Citation: " << citation);
651                                 aux_info.citations.insert(citation);
652                         }
653                 } else if (regex_match(token, sub, reg2)) {
654                         string data = sub.str(1);
655                         // data is now all the bib files separated by ','
656                         // get them one by one and pass them to the helper
657                         while (!data.empty()) {
658                                 string database;
659                                 data = split(data, database, ',');
660                                 database = changeExtension(database, "bib");
661                                 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
662                                 aux_info.databases.insert(database);
663                         }
664                 } else if (regex_match(token, sub, reg3)) {
665                         string style = sub.str(1);
666                         // token is now the style file
667                         // pass it to the helper
668                         style = changeExtension(style, "bst");
669                         LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
670                         aux_info.styles.insert(style);
671                 } else if (regex_match(token, sub, reg4)) {
672                         string const file2 = sub.str(1);
673                         scanAuxFile(makeAbsPath(file2), aux_info);
674                 }
675         }
676 }
677
678
679 void LaTeX::updateBibtexDependencies(DepTable & dep,
680                                      vector<AuxInfo> const & bibtex_info)
681 {
682         // Since a run of Bibtex mandates more latex runs it is ok to
683         // remove all ".bib" and ".bst" files.
684         dep.remove_files_with_extension(".bib");
685         dep.remove_files_with_extension(".bst");
686         //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
687
688         for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
689              it != bibtex_info.end(); ++it) {
690                 for (set<string>::const_iterator it2 = it->databases.begin();
691                      it2 != it->databases.end(); ++it2) {
692                         FileName const file = findtexfile(*it2, "bib");
693                         if (!file.empty())
694                                 dep.insert(file, true);
695                 }
696
697                 for (set<string>::const_iterator it2 = it->styles.begin();
698                      it2 != it->styles.end(); ++it2) {
699                         FileName const file = findtexfile(*it2, "bst");
700                         if (!file.empty())
701                                 dep.insert(file, true);
702                 }
703         }
704
705         // biber writes nothing into the aux file.
706         // Instead, we have to scan the blg file
707         if (biber) {
708                 TeXErrors terr;
709                 scanBlgFile(dep, terr);
710         }
711 }
712
713
714 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
715                       OutputParams const & rp, int & exit_code)
716 {
717         bool result = false;
718         exit_code = 0;
719         for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
720              it != bibtex_info.end(); ++it) {
721                 if (!biber && it->databases.empty())
722                         continue;
723                 result = true;
724
725                 string tmp = rp.bibtex_command;
726                 tmp += " ";
727                 // onlyFileName() is needed for cygwin
728                 tmp += quoteName(onlyFileName(removeExtension(
729                                 it->aux_file.absFileName())));
730                 Systemcall one;
731                 Systemcall::Starttype const starttype = 
732                 allow_cancel ? Systemcall::WaitLoop : Systemcall::Wait;
733                 exit_code = one.startscript(starttype, tmp, path, lpath, true);
734                 if (exit_code) {
735                         return result;
736                 }
737         }
738         // Return whether bibtex was run
739         return result;
740 }
741
742
743 //helper func for scanLogFile; gets line number X from strings "... on input line X ..."
744 //returns 0 if none is found
745 int getLineNumber(const string &token){
746         string l = support::token(token, ' ', tokenPos(token,' ',"line") + 1);
747         return l.empty() ? 0 : convert<int>(l);
748 }
749
750
751 int LaTeX::scanLogFile(TeXErrors & terr)
752 {
753         int last_line = -1;
754         int line_count = 1;
755         int retval = NO_ERRORS;
756         string tmp =
757                 onlyFileName(changeExtension(file.absFileName(), ".log"));
758         LYXERR(Debug::LATEX, "Log file: " << tmp);
759         FileName const fn = FileName(makeAbsPath(tmp));
760         // FIXME we should use an ifdocstream here and a docstring for token
761         // below. The encoding of the log file depends on the _output_ (font)
762         // encoding of the TeX file (T1, TU etc.). See #10728.
763         ifstream ifs(fn.toFilesystemEncoding().c_str());
764         bool fle_style = false;
765         static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
766         static regex const child_file("[^0-9]*([0-9]+[A-Za-z]*_.+\\.tex).*");
767         // Flag for 'File ended while scanning' message.
768         // We need to wait for subsequent processing.
769         string wait_for_error;
770         string child_name;
771         int pnest = 0;
772         stack <pair<string, int> > child;
773         children.clear();
774
775         terr.clearRefs();
776
777         string token;
778         while (getline(ifs, token)) {
779                 // MikTeX sometimes inserts \0 in the log file. They can't be
780                 // removed directly with the existing string utility
781                 // functions, so convert them first to \r, and remove all
782                 // \r's afterwards, since we need to remove them anyway.
783                 token = subst(token, '\0', '\r');
784                 token = subst(token, "\r", "");
785                 smatch sub;
786
787                 LYXERR(Debug::LATEX, "Log line: " << token);
788
789                 if (token.empty())
790                         continue;
791
792                 // Track child documents
793                 for (size_t i = 0; i < token.length(); ++i) {
794                         if (token[i] == '(') {
795                                 ++pnest;
796                                 size_t j = token.find('(', i + 1);
797                                 size_t len = j == string::npos
798                                                 ? token.substr(i + 1).length()
799                                                 : j - i - 1;
800                                 string const substr = token.substr(i + 1, len);
801                                 if (regex_match(substr, sub, child_file)) {
802                                         string const name = sub.str(1);
803                                         // Sometimes also masters have a name that matches
804                                         // (if their name starts with a number and _)
805                                         if (name != file.onlyFileName()) {
806                                                 child.push(make_pair(name, pnest));
807                                                 children.push_back(name);
808                                         }
809                                         i += len;
810                                 }
811                         } else if (token[i] == ')') {
812                                 if (!child.empty()
813                                     && child.top().second == pnest)
814                                         child.pop();
815                                 --pnest;
816                         }
817                 }
818                 child_name = child.empty() ? empty_string() : child.top().first;
819
820                 if (contains(token, "file:line:error style messages enabled"))
821                         fle_style = true;
822
823                 //Handles both "LaTeX Warning:" & "Package natbib Warning:"
824                 //Various handlers for missing citations below won't catch the problem if citation
825                 //key is long (>~25chars), because pdflatex splits output at line length 80.
826                 //TODO: TL 2020 engines will contain new commandline switch --cnf-line which we  
827                 //can use to set max_print_line variable for appropriate length and detect all
828                 //errors correctly.
829                 if (contains(token, "There were undefined citations.") ||
830                     prefixIs(token, "Package biblatex Warning: The following entry could not be found"))
831                         retval |= UNDEF_CIT;
832
833                 if (prefixIs(token, "LaTeX Warning:") ||
834                     prefixIs(token, "! pdfTeX warning")) {
835                         // Here shall we handle different
836                         // types of warnings
837                         retval |= LATEX_WARNING;
838                         LYXERR(Debug::LATEX, "LaTeX Warning.");
839                         if (contains(token, "Rerun to get cross-references")) {
840                                 retval |= RERUN;
841                                 LYXERR(Debug::LATEX, "We should rerun.");
842                         // package clefval needs 2 latex runs before bibtex
843                         } else if (contains(token, "Value of")
844                                    && contains(token, "on page")
845                                    && contains(token, "undefined")) {
846                                 retval |= ERROR_RERUN;
847                                 LYXERR(Debug::LATEX, "Force rerun.");
848                         // package etaremune
849                         } else if (contains(token, "Etaremune labels have changed")) {
850                                 retval |= ERROR_RERUN;
851                                 LYXERR(Debug::LATEX, "Force rerun.");
852                         // package enotez
853                         } else if (contains(token, "Endnotes may have changed. Rerun")) {
854                                 retval |= RERUN;
855                                 LYXERR(Debug::LATEX, "We should rerun.");
856                         //"Citation `cit' on page X undefined on input line X."
857                         } else if (contains(token, "Citation")
858                                    //&& contains(token, "on input line") //often split to newline
859                                    && contains(token, "undefined")) {
860                                 retval |= UNDEF_CIT;
861                                 terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
862                                         from_utf8(token), child_name);
863                         //"Reference `X' on page Y undefined on input line Z."
864                         } else if (contains(token, "Reference")
865                                    //&& contains(token, "on input line")) //often split to new line
866                                    && contains(token, "undefined")) {
867                                 retval |= UNDEF_REF;
868                                 terr.insertRef(getLineNumber(token), from_ascii("Reference undefined"),
869                                         from_utf8(token), child_name);
870
871                         //If label is too long pdlaftex log line splitting will make the above fail
872                         //so we catch at least this generic statement occuring for both CIT & REF.
873                         } else if (contains(token, "There were undefined references.")) {
874                                 if (!(retval & UNDEF_CIT)) //if not handled already
875                                          retval |= UNDEF_REF;
876                         }
877
878                 } else if (prefixIs(token, "Package")) {
879                         // Package warnings
880                         retval |= PACKAGE_WARNING;
881                         if (contains(token, "natbib Warning:")) {
882                                 // Natbib warnings
883                                 if (contains(token, "Citation")
884                                     && contains(token, "on page")
885                                     && contains(token, "undefined")) {
886                                         retval |= UNDEF_CIT;
887                                         //Unf only keys up to ~6 chars will make it due to line splits
888                                         terr.insertRef(getLineNumber(token), from_ascii("Citation undefined"),
889                                                 from_utf8(token), child_name);
890                                 }
891                         } else if (contains(token, "run BibTeX")) {
892                                 retval |= UNDEF_CIT;
893                         } else if (contains(token, "run Biber")) {
894                                 retval |= UNDEF_CIT;
895                                 biber = true;
896                         } else if (contains(token, "Rerun LaTeX") ||
897                                    contains(token, "Please rerun LaTeX") ||
898                                    contains(token, "Rerun to get")) {
899                                 // at least longtable.sty and bibtopic.sty
900                                 // might use this.
901                                 LYXERR(Debug::LATEX, "We should rerun.");
902                                 retval |= RERUN;
903                         }
904                 } else if (prefixIs(token, "LETTRE WARNING:")) {
905                         if (contains(token, "veuillez recompiler")) {
906                                 // lettre.cls
907                                 LYXERR(Debug::LATEX, "We should rerun.");
908                                 retval |= RERUN;
909                         }
910                 } else if (token[0] == '(') {
911                         if (contains(token, "Rerun LaTeX") ||
912                             contains(token, "Rerun to get")) {
913                                 // Used by natbib
914                                 LYXERR(Debug::LATEX, "We should rerun.");
915                                 retval |= RERUN;
916                         }
917                 } else if (prefixIs(token, "! ")
918                             || (fle_style
919                                 && regex_match(token, sub, file_line_error)
920                                 && !contains(token, "pdfTeX warning"))) {
921                            // Ok, we have something that looks like a TeX Error
922                            // but what do we really have.
923
924                         // Just get the error description:
925                         string desc;
926                         if (prefixIs(token, "! "))
927                                 desc = string(token, 2);
928                         else if (fle_style)
929                                 desc = sub.str();
930                         if (contains(token, "LaTeX Error:"))
931                                 retval |= LATEX_ERROR;
932
933                         if (prefixIs(token, "! File ended while scanning")) {
934                                 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
935                                         // bug 7344. We must rerun LaTeX if hyperref has been toggled.
936                                         retval |= ERROR_RERUN;
937                                         LYXERR(Debug::LATEX, "Force rerun.");
938                                 } else {
939                                         // bug 6445. At this point its not clear we finish with error.
940                                         wait_for_error = desc;
941                                         continue;
942                                 }
943                         }
944
945                         if (prefixIs(token, "! Incomplete \\if")) {
946                                 // bug 10666. At this point its not clear we finish with error.
947                                 wait_for_error = desc;
948                                 continue;
949                         }
950
951                         if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
952                                         // bug 7344. We must rerun LaTeX if hyperref has been toggled.
953                                         retval |= ERROR_RERUN;
954                                         LYXERR(Debug::LATEX, "Force rerun.");
955                         }
956
957                         if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
958                                 retval |= LATEX_ERROR;
959                                 string errstr;
960                                 int count = 0;
961                                 errstr = wait_for_error;
962                                 wait_for_error.clear();
963                                 do {
964                                         if (!getline(ifs, tmp))
965                                                 break;
966                                         tmp = rtrim(tmp, "\r");
967                                         errstr += "\n" + tmp;
968                                         if (++count > 5)
969                                                 break;
970                                 } while (!contains(tmp, "(job aborted"));
971
972                                 terr.insertError(0,
973                                                  from_ascii("Emergency stop"),
974                                                  from_local8bit(errstr),
975                                                  child_name);
976                         }
977
978                         // get the next line
979                         int count = 0;
980                         do {
981                                 if (!getline(ifs, tmp))
982                                         break;
983                                 tmp = rtrim(tmp, "\r");
984                                 // 15 is somewhat arbitrarily chosen, based on practice.
985                                 // We used 10 for 14 years and increased it to 15 when we
986                                 // saw one case.
987                                 if (++count > 15)
988                                         break;
989                         } while (!prefixIs(tmp, "l."));
990                         if (prefixIs(tmp, "l.")) {
991                                 // we have a latex error
992                                 retval |=  TEX_ERROR;
993                                 if (contains(desc,
994                                         "Package babel Error: You haven't defined the language")
995                                     || contains(desc,
996                                         "Package babel Error: You haven't loaded the option")
997                                     || contains(desc,
998                                         "Package babel Error: Unknown language"))
999                                         retval |= ERROR_RERUN;
1000                                 // get the line number:
1001                                 int line = 0;
1002                                 sscanf(tmp.c_str(), "l.%d", &line);
1003                                 // get the rest of the message:
1004                                 string errstr(tmp, tmp.find(' '));
1005                                 errstr += '\n';
1006                                 getline(ifs, tmp);
1007                                 tmp = rtrim(tmp, "\r");
1008                                 while (!contains(errstr, "l.")
1009                                        && !tmp.empty()
1010                                        && !prefixIs(tmp, "! ")
1011                                        && !contains(tmp, "(job aborted")) {
1012                                         errstr += tmp;
1013                                         errstr += "\n";
1014                                         getline(ifs, tmp);
1015                                         tmp = rtrim(tmp, "\r");
1016                                 }
1017                                 LYXERR(Debug::LATEX, "line: " << line << '\n'
1018                                         << "Desc: " << desc << '\n' << "Text: " << errstr);
1019                                 if (line == last_line)
1020                                         ++line_count;
1021                                 else {
1022                                         line_count = 1;
1023                                         last_line = line;
1024                                 }
1025                                 if (line_count <= 5) {
1026                                         // FIXME UNICODE
1027                                         // We have no idea what the encoding of
1028                                         // the log file is.
1029                                         // It seems that the output from the
1030                                         // latex compiler itself is pure ASCII,
1031                                         // but it can include bits from the
1032                                         // document, so whatever encoding we
1033                                         // assume here it can be wrong.
1034                                         terr.insertError(line,
1035                                                          from_local8bit(desc),
1036                                                          from_local8bit(errstr),
1037                                                          child_name);
1038                                         ++num_errors;
1039                                 }
1040                         }
1041                 } else {
1042                         // information messages, TeX warnings and other
1043                         // warnings we have not caught earlier.
1044                         if (prefixIs(token, "Overfull ")) {
1045                                 retval |= TEX_WARNING;
1046                         } else if (prefixIs(token, "Underfull ")) {
1047                                 retval |= TEX_WARNING;
1048                         } else if (contains(token, "Rerun to get citations")) {
1049                                 // Natbib seems to use this.
1050                                 retval |= UNDEF_CIT;
1051                         } else if (contains(token, "No pages of output")
1052                                 || contains(token, "no pages of output")) {
1053                                 // No output file (e.g. the DVI or PDF) was created
1054                                 retval |= NO_OUTPUT;
1055                         } else if (contains(token, "Error 256 (driver return code)")) {
1056                                 // This is a xdvipdfmx driver error reported by XeTeX.
1057                                 // We have to check whether an output PDF file was created.
1058                                 FileName pdffile = file;
1059                                 pdffile.changeExtension("pdf");
1060                                 if (!pdffile.exists())
1061                                         // No output PDF file was created (see #10076)
1062                                         retval |= NO_OUTPUT;
1063                         } else if (contains(token, "That makes 100 errors")) {
1064                                 // More than 100 errors were reported
1065                                 retval |= TOO_MANY_ERRORS;
1066                         } else if (prefixIs(token, "!pdfTeX error:")) {
1067                                 // otherwise we dont catch e.g.:
1068                                 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
1069                                 retval |= ERRORS;
1070                                 terr.insertError(0,
1071                                                  from_ascii("pdfTeX Error"),
1072                                                  from_local8bit(token),
1073                                                  child_name);
1074                         } else if (!ignore_missing_glyphs
1075                                    && prefixIs(token, "Missing character: There is no ")
1076                                    && !contains(token, "nullfont")) {
1077                                 // Warning about missing glyph in selected font
1078                                 // may be dataloss (bug 9610)
1079                                 // but can be ignored for 'nullfont' (bug 10394).
1080                                 // as well as for ZERO WIDTH NON-JOINER (0x200C) which is
1081                                 // missing in many fonts and output for ligature break (bug 10727).
1082                                 // Since this error only occurs with utf8 output, we can safely assume
1083                                 // that the log file is utf8-encoded
1084                                 docstring const utoken = from_utf8(token);
1085                                 if (!contains(utoken, 0x200C)) {
1086                                         retval |= LATEX_ERROR;
1087                                         terr.insertError(0,
1088                                                          from_ascii("Missing glyphs!"),
1089                                                          utoken,
1090                                                          child_name);
1091                                 }
1092                         } else if (!wait_for_error.empty()) {
1093                                 // We collect information until we know we have an error.
1094                                 wait_for_error += token + '\n';
1095                         }
1096                 }
1097         }
1098         LYXERR(Debug::LATEX, "Log line: " << token);
1099         return retval;
1100 }
1101
1102
1103 namespace {
1104
1105 bool insertIfExists(FileName const & absname, DepTable & head)
1106 {
1107         if (absname.exists() && !absname.isDirectory()) {
1108                 head.insert(absname, true);
1109                 return true;
1110         }
1111         return false;
1112 }
1113
1114
1115 bool handleFoundFile(string const & ff, DepTable & head)
1116 {
1117         // convert from native os path to unix path
1118         string foundfile = os::internal_path(trim(ff));
1119
1120         LYXERR(Debug::DEPEND, "Found file: " << foundfile);
1121
1122         // Ok now we found a file.
1123         // Now we should make sure that this is a file that we can
1124         // access through the normal paths.
1125         // We will not try any fancy search methods to
1126         // find the file.
1127
1128         // (1) foundfile is an
1129         //     absolute path and should
1130         //     be inserted.
1131         FileName absname;
1132         if (FileName::isAbsolute(foundfile)) {
1133                 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
1134                 // On initial insert we want to do the update at once
1135                 // since this file cannot be a file generated by
1136                 // the latex run.
1137                 absname.set(foundfile);
1138                 if (!insertIfExists(absname, head)) {
1139                         // check for spaces
1140                         string strippedfile = foundfile;
1141                         while (contains(strippedfile, " ")) {
1142                                 // files with spaces are often enclosed in quotation
1143                                 // marks; those have to be removed
1144                                 string unquoted = subst(strippedfile, "\"", "");
1145                                 absname.set(unquoted);
1146                                 if (insertIfExists(absname, head))
1147                                         return true;
1148                                 // strip off part after last space and try again
1149                                 string tmp = strippedfile;
1150                                 rsplit(tmp, strippedfile, ' ');
1151                                 absname.set(strippedfile);
1152                                 if (insertIfExists(absname, head))
1153                                         return true;
1154                         }
1155                 }
1156         }
1157
1158         string onlyfile = onlyFileName(foundfile);
1159         absname = makeAbsPath(onlyfile);
1160
1161         // check for spaces
1162         while (contains(foundfile, ' ')) {
1163                 if (absname.exists())
1164                         // everything o.k.
1165                         break;
1166                 else {
1167                         // files with spaces are often enclosed in quotation
1168                         // marks; those have to be removed
1169                         string unquoted = subst(foundfile, "\"", "");
1170                         absname = makeAbsPath(unquoted);
1171                         if (absname.exists())
1172                                 break;
1173                         // strip off part after last space and try again
1174                         string strippedfile;
1175                         rsplit(foundfile, strippedfile, ' ');
1176                         foundfile = strippedfile;
1177                         onlyfile = onlyFileName(strippedfile);
1178                         absname = makeAbsPath(onlyfile);
1179                 }
1180         }
1181
1182         // (2) foundfile is in the tmpdir
1183         //     insert it into head
1184         if (absname.exists() && !absname.isDirectory()) {
1185                 // FIXME: This regex contained glo, but glo is used by the old
1186                 // version of nomencl.sty. Do we need to put it back?
1187                 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
1188                 if (regex_match(onlyfile, unwanted)) {
1189                         LYXERR(Debug::DEPEND, "We don't want " << onlyfile
1190                                 << " in the dep file");
1191                 } else if (suffixIs(onlyfile, ".tex")) {
1192                         // This is a tex file generated by LyX
1193                         // and latex is not likely to change this
1194                         // during its runs.
1195                         LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
1196                         head.insert(absname, true);
1197                 } else {
1198                         LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
1199                         head.insert(absname);
1200                 }
1201                 return true;
1202         } else {
1203                 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
1204                 return false;
1205         }
1206 }
1207
1208
1209 bool completeFilename(string const & ff, DepTable & head)
1210 {
1211         // If we do not find a dot, we suspect
1212         // a fragmental file name
1213         if (!contains(ff, '.'))
1214                 return false;
1215
1216         // if we have a dot, we let handleFoundFile decide
1217         return handleFoundFile(ff, head);
1218 }
1219
1220
1221 int iterateLine(string const & token, regex const & reg, string const & opening,
1222                 string const & closing, int fragment_pos, DepTable & head)
1223 {
1224         smatch what;
1225         string::const_iterator first = token.begin();
1226         string::const_iterator end = token.end();
1227         bool fragment = false;
1228         string last_match;
1229
1230         while (regex_search(first, end, what, reg)) {
1231                 // if we have a dot, try to handle as file
1232                 if (contains(what.str(1), '.')) {
1233                         first = what[0].second;
1234                         if (what.str(2) == closing) {
1235                                 handleFoundFile(what.str(1), head);
1236                                 // since we had a closing bracket,
1237                                 // do not investigate further
1238                                 fragment = false;
1239                         } else if (what.str(2) == opening) {
1240                                 // if we have another opening bracket,
1241                                 // we might have a nested file chain
1242                                 // as is (file.ext (subfile.ext))
1243                                 fragment = !handleFoundFile(rtrim(what.str(1)), head);
1244                                 // decrease first position by one in order to
1245                                 // consider the opening delimiter on next iteration
1246                                 if (first > token.begin())
1247                                         --first;
1248                         } else
1249                                 // if we have no closing bracket,
1250                                 // try to handle as file nevertheless
1251                                 fragment = !handleFoundFile(
1252                                         what.str(1) + what.str(2), head);
1253                 }
1254                 // if we do not have a dot, check if the line has
1255                 // a closing bracket (else, we suspect a line break)
1256                 else if (what.str(2) != closing) {
1257                         first = what[0].second;
1258                         fragment = true;
1259                 } else {
1260                         // we have a closing bracket, so the content
1261                         // is not a file name.
1262                         // no need to investigate further
1263                         first = what[0].second;
1264                         fragment = false;
1265                 }
1266                 last_match = what.str(1);
1267         }
1268
1269         // We need to consider the result from previous line iterations:
1270         // We might not find a fragment here, but another one might follow
1271         // E.g.: (filename.ext) <filenam
1272         // Vice versa, we consider the search completed if a real match
1273         // follows a potential fragment from a previous iteration.
1274         // E.g. <some text we considered a fragment (filename.ext)
1275         // result = -1 means we did not find a fragment!
1276         int result = -1;
1277         int last_match_pos = -1;
1278         if (!last_match.empty() && token.find(last_match) != string::npos)
1279                 last_match_pos = int(token.find(last_match));
1280         if (fragment) {
1281                 if (last_match_pos > fragment_pos)
1282                         result = last_match_pos;
1283                 else
1284                         result = fragment_pos;
1285         } else
1286                 if (last_match_pos < fragment_pos)
1287                         result = fragment_pos;
1288
1289         return result;
1290 }
1291
1292 } // namespace
1293
1294
1295 void LaTeX::deplog(DepTable & head)
1296 {
1297         // This function reads the LaTeX log file end extracts all the
1298         // external files used by the LaTeX run. The files are then
1299         // entered into the dependency file.
1300
1301         string const logfile =
1302                 onlyFileName(changeExtension(file.absFileName(), ".log"));
1303
1304         static regex const reg1("File: (.+).*");
1305         static regex const reg2("No file (.+)(.).*");
1306         static regex const reg3a("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1307         // LuaTeX has a slightly different output
1308         static regex const reg3b("\\\\openout[0-9]+.*=\\s*(.+)");
1309         // If an index should be created, MikTex does not write a line like
1310         //    \openout# = 'sample.idx'.
1311         // but instead only a line like this into the log:
1312         //   Writing index file sample.idx
1313         static regex const reg4("Writing index file (.+).*");
1314         static regex const regoldnomencl("Writing glossary file (.+).*");
1315         static regex const regnomencl(".*Writing nomenclature file (.+).*");
1316         // If a toc should be created, MikTex does not write a line like
1317         //    \openout# = `sample.toc'.
1318         // but only a line like this into the log:
1319         //    \tf@toc=\write#
1320         // This line is also written by tetex.
1321         // This line is not present if no toc should be created.
1322         static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1323         // file names can be enclosed in <...> (anywhere on the line)
1324         static regex const reg5(".*<[^>]+.*");
1325         // and also (...) anywhere on the line
1326         static regex const reg6(".*\\([^)]+.*");
1327
1328         FileName const fn = makeAbsPath(logfile);
1329         ifstream ifs(fn.toFilesystemEncoding().c_str());
1330         string lastline;
1331         while (ifs) {
1332                 // Ok, the scanning of files here is not sufficient.
1333                 // Sometimes files are named by "File: xxx" only
1334                 // Therefore we use some regexps to find files instead.
1335                 // Note: all file names and paths might contains spaces.
1336                 // Also, file names might be broken across lines. Therefore
1337                 // we mark (potential) fragments and merge those lines.
1338                 bool fragment = false;
1339                 string token;
1340                 getline(ifs, token);
1341                 // MikTeX sometimes inserts \0 in the log file. They can't be
1342                 // removed directly with the existing string utility
1343                 // functions, so convert them first to \r, and remove all
1344                 // \r's afterwards, since we need to remove them anyway.
1345                 token = subst(token, '\0', '\r');
1346                 token = subst(token, "\r", "");
1347                 if (token.empty() || token == ")") {
1348                         lastline = string();
1349                         continue;
1350                 }
1351
1352                 // FIXME UNICODE: We assume that the file names in the log
1353                 // file are in the file system encoding.
1354                 token = to_utf8(from_filesystem8bit(token));
1355
1356                 // Sometimes, filenames are broken across lines.
1357                 // We care for that and save suspicious lines.
1358                 // Here we exclude some cases where we are sure
1359                 // that there is no continued filename
1360                 if (!lastline.empty()) {
1361                         static regex const package_info("Package \\w+ Info: .*");
1362                         static regex const package_warning("Package \\w+ Warning: .*");
1363                         if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1364                             || prefixIs(token, "Package:")
1365                             || prefixIs(token, "Language:")
1366                             || prefixIs(token, "LaTeX Info:")
1367                             || prefixIs(token, "LaTeX Font Info:")
1368                             || prefixIs(token, "\\openout[")
1369                             || prefixIs(token, "))")
1370                             || regex_match(token, package_info)
1371                             || regex_match(token, package_warning))
1372                                 lastline = string();
1373                 }
1374
1375                 if (!lastline.empty())
1376                         // probably a continued filename from last line
1377                         token = lastline + token;
1378                 if (token.length() > 255) {
1379                         // string too long. Cut off.
1380                         token.erase(0, token.length() - 251);
1381                 }
1382
1383                 smatch sub;
1384
1385                 // (1) "File: file.ext"
1386                 if (regex_match(token, sub, reg1)) {
1387                         // is this a fragmental file name?
1388                         fragment = !completeFilename(sub.str(1), head);
1389                         // However, ...
1390                         if (suffixIs(token, ")"))
1391                                 // no fragment for sure
1392                                 fragment = false;
1393                 // (2) "No file file.ext"
1394                 } else if (regex_match(token, sub, reg2)) {
1395                         // file names must contains a dot, line ends with dot
1396                         if (contains(sub.str(1), '.') && sub.str(2) == ".")
1397                                 fragment = !handleFoundFile(sub.str(1), head);
1398                         else
1399                                 // we suspect a line break
1400                                 fragment = true;
1401                 // (3)(a) "\openout<nr> = `file.ext'."
1402                 } else if (regex_match(token, sub, reg3a)) {
1403                         // search for closing '. at the end of the line
1404                         if (sub.str(2) == "\'.")
1405                                 fragment = !handleFoundFile(sub.str(1), head);
1406                         else
1407                                 // potential fragment
1408                                 fragment = true;
1409                 // (3)(b) "\openout<nr> = file.ext" (LuaTeX)
1410                 } else if (regex_match(token, sub, reg3b)) {
1411                         // file names must contains a dot
1412                         if (contains(sub.str(1), '.'))
1413                                 fragment = !handleFoundFile(sub.str(1), head);
1414                         else
1415                                 // potential fragment
1416                                 fragment = true;
1417                 // (4) "Writing index file file.ext"
1418                 } else if (regex_match(token, sub, reg4))
1419                         // fragmential file name?
1420                         fragment = !completeFilename(sub.str(1), head);
1421                 // (5) "Writing nomenclature file file.ext"
1422                 else if (regex_match(token, sub, regnomencl) ||
1423                            regex_match(token, sub, regoldnomencl))
1424                         // fragmental file name?
1425                         fragment= !completeFilename(sub.str(1), head);
1426                 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1427                 else if (regex_match(token, sub, miktexTocReg))
1428                         fragment = !handleFoundFile(onlyFileName(changeExtension(
1429                                                 file.absFileName(), ".toc")), head);
1430                 else
1431                         // not found, but we won't check further
1432                         fragment = false;
1433
1434                 int fragment_pos = -1;
1435                 // (7) "<file.ext>"
1436                 // We can have several of these on one line
1437                 // (and in addition to those above)
1438                 if (regex_match(token, sub, reg5)) {
1439                         // search for strings in <...>
1440                         static regex const reg5_1("<([^>]+)(.)");
1441                         fragment_pos = iterateLine(token, reg5_1, "<", ">",
1442                                                    fragment_pos, head);
1443                         fragment = (fragment_pos != -1);
1444                 }
1445
1446                 // (8) "(file.ext)"
1447                 // We can have several of these on one line
1448                 // this must be queried separated, because of
1449                 // cases such as "File: file.ext (type eps)"
1450                 // where "File: file.ext" would be skipped
1451                 if (regex_match(token, sub, reg6)) {
1452                         // search for strings in (...)
1453                         static regex const reg6_1("\\(([^()]+)(.)");
1454                         fragment_pos = iterateLine(token, reg6_1, "(", ")",
1455                                                    fragment_pos, head);
1456                         fragment = (fragment_pos != -1);
1457                 }
1458
1459                 if (fragment)
1460                         // probable linebreak within file name:
1461                         // save this line
1462                         lastline = token;
1463                 else
1464                         // no linebreak: reset
1465                         lastline = string();
1466         }
1467
1468         // Make sure that the main .tex file is in the dependency file.
1469         head.insert(file, true);
1470 }
1471
1472
1473 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1474 {
1475         FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1476         LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1477
1478         ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1479         string token;
1480         static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1481         static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1482         static regex const bibtexError2("^(.*---while reading file).*$");
1483         static regex const bibtexError3("(A bad cross reference---).*");
1484         static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1485         static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1486         static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1487         int retval = NO_ERRORS;
1488
1489         string prevtoken;
1490         while (getline(ifs, token)) {
1491                 token = rtrim(token, "\r");
1492                 smatch sub;
1493                 // FIXME UNICODE: We assume that citation keys and filenames
1494                 // in the aux file are in the file system encoding.
1495                 token = to_utf8(from_filesystem8bit(token));
1496                 if (regex_match(token, sub, reg1)) {
1497                         string data = sub.str(3);
1498                         if (!data.empty()) {
1499                                 LYXERR(Debug::LATEX, "Found bib file: " << data);
1500                                 handleFoundFile(data, dep);
1501                         }
1502                 }
1503                 else if (regex_match(token, sub, bibtexError)
1504                          || regex_match(token, sub, bibtexError2)
1505                          || regex_match(token, sub, bibtexError4)
1506                          || regex_match(token, sub, bibtexError5)) {
1507                         retval |= BIBTEX_ERROR;
1508                         string errstr = N_("BibTeX error: ") + token;
1509                         string msg;
1510                         if ((prefixIs(token, "while executing---line")
1511                              || prefixIs(token, "---line ")
1512                              || prefixIs(token, "*Please notify the BibTeX"))
1513                             && !prevtoken.empty()) {
1514                                 errstr = N_("BibTeX error: ") + prevtoken;
1515                                 msg = prevtoken + '\n';
1516                         }
1517                         msg += token;
1518                         terr.insertError(0,
1519                                          from_local8bit(errstr),
1520                                          from_local8bit(msg));
1521                 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1522                         retval |= BIBTEX_ERROR;
1523                         string errstr = N_("BibTeX error: ") + prevtoken;
1524                         string msg = prevtoken + '\n' + token;
1525                         terr.insertError(0,
1526                                          from_local8bit(errstr),
1527                                          from_local8bit(msg));
1528                 } else if (regex_match(token, sub, biberError)) {
1529                         retval |= BIBTEX_ERROR;
1530                         string errstr = N_("Biber error: ") + sub.str(2);
1531                         string msg = token;
1532                         terr.insertError(0,
1533                                          from_local8bit(errstr),
1534                                          from_local8bit(msg));
1535                 }
1536                 prevtoken = token;
1537         }
1538         return retval;
1539 }
1540
1541
1542 int LaTeX::scanIlgFile(TeXErrors & terr)
1543 {
1544         FileName const ilg_file(changeExtension(file.absFileName(), "ilg"));
1545         LYXERR(Debug::LATEX, "Scanning ilg file: " << ilg_file);
1546
1547         ifstream ifs(ilg_file.toFilesystemEncoding().c_str());
1548         string token;
1549         int retval = NO_ERRORS;
1550
1551         string prevtoken;
1552         while (getline(ifs, token)) {
1553                 token = rtrim(token, "\r");
1554                 smatch sub;
1555                 if (prefixIs(token, "!! "))
1556                         prevtoken = token;
1557                 else if (!prevtoken.empty()) {
1558                         retval |= INDEX_ERROR;
1559                         string errstr = N_("Makeindex error: ") + prevtoken;
1560                         string msg = prevtoken + '\n';
1561                         msg += token;
1562                         terr.insertError(0,
1563                                          from_local8bit(errstr),
1564                                          from_local8bit(msg));
1565                         prevtoken.clear();
1566                 } else if (prefixIs(token, "ERROR: ")) {
1567                         retval |= BIBTEX_ERROR;
1568                         string errstr = N_("Xindy error: ") + token.substr(6);
1569                         string msg = token;
1570                         terr.insertError(0,
1571                                          from_local8bit(errstr),
1572                                          from_local8bit(msg));
1573                 }
1574         }
1575         return retval;
1576 }
1577
1578
1579
1580 } // namespace lyx