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