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