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