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