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