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