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