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