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