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