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