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