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