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