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