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