]> git.lyx.org Git - lyx.git/blob - src/LaTeX.cpp
Remove all messages to user related to assertions. We'll just use
[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, string const & p)
97         : cmd(latex), file(f), path(p), runparams(rp), biber(false)
98 {
99         num_errors = 0;
100         if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
101                 depfile = FileName(file.absFileName() + ".dep-pdf");
102                 output_file =
103                         FileName(changeExtension(file.absFileName(), ".pdf"));
104         } else {
105                 depfile = FileName(file.absFileName() + ".dep");
106                 output_file =
107                         FileName(changeExtension(file.absFileName(), ".dvi"));
108         }
109 }
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         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);
294                 rerun |= runBibTeX(bibtex_info, runparams);
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);
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);
354                 rerun |= runBibTeX(bibtex_info, runparams);
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, path);
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, path);
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, path);
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 {
555         // Since a run of Bibtex mandates more latex runs it is ok to
556         // remove all ".bib" and ".bst" files.
557         dep.remove_files_with_extension(".bib");
558         dep.remove_files_with_extension(".bst");
559         //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
560
561         for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
562              it != bibtex_info.end(); ++it) {
563                 for (set<string>::const_iterator it2 = it->databases.begin();
564                      it2 != it->databases.end(); ++it2) {
565                         FileName const file = findtexfile(*it2, "bib");
566                         if (!file.empty())
567                                 dep.insert(file, true);
568                 }
569
570                 for (set<string>::const_iterator it2 = it->styles.begin();
571                      it2 != it->styles.end(); ++it2) {
572                         FileName const file = findtexfile(*it2, "bst");
573                         if (!file.empty())
574                                 dep.insert(file, true);
575                 }
576         }
577
578         // biber writes nothing into the aux file.
579         // Instead, we have to scan the blg file
580         if (biber) {
581                 scanBlgFile(dep);
582         }
583 }
584
585
586 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
587                       OutputParams const & runparams)
588 {
589         bool result = false;
590         for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
591              it != bibtex_info.end(); ++it) {
592                 if (!biber && it->databases.empty())
593                         continue;
594                 result = true;
595
596                 string tmp = runparams.use_japanese ?
597                         lyxrc.jbibtex_command : lyxrc.bibtex_command;
598
599                 if (!runparams.bibtex_command.empty())
600                         tmp = runparams.bibtex_command;
601                 tmp += " ";
602                 // onlyFileName() is needed for cygwin
603                 tmp += quoteName(onlyFileName(removeExtension(
604                                 it->aux_file.absFileName())));
605                 Systemcall one;
606                 one.startscript(Systemcall::Wait, tmp, path);
607         }
608         // Return whether bibtex was run
609         return result;
610 }
611
612
613 int LaTeX::scanLogFile(TeXErrors & terr)
614 {
615         int last_line = -1;
616         int line_count = 1;
617         int retval = NO_ERRORS;
618         string tmp =
619                 onlyFileName(changeExtension(file.absFileName(), ".log"));
620         LYXERR(Debug::LATEX, "Log file: " << tmp);
621         FileName const fn = FileName(makeAbsPath(tmp));
622         ifstream ifs(fn.toFilesystemEncoding().c_str());
623         bool fle_style = false;
624         static regex file_line_error(".+\\.\\D+:[0-9]+: (.+)");
625         static regex child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
626         // Flag for 'File ended while scanning' message.
627         // We need to wait for subsequent processing.
628         string wait_for_error;
629         string child_name;
630         int pnest = 0;
631         stack <pair<string, int> > child;
632
633         string token;
634         while (getline(ifs, token)) {
635                 // MikTeX sometimes inserts \0 in the log file. They can't be
636                 // removed directly with the existing string utility
637                 // functions, so convert them first to \r, and remove all
638                 // \r's afterwards, since we need to remove them anyway.
639                 token = subst(token, '\0', '\r');
640                 token = subst(token, "\r", "");
641                 smatch sub;
642
643                 LYXERR(Debug::LATEX, "Log line: " << token);
644
645                 if (token.empty())
646                         continue;
647
648                 // Track child documents
649                 for (size_t i = 0; i < token.length(); ++i) {
650                         if (token[i] == '(') {
651                                 ++pnest;
652                                 size_t j = token.find('(', i + 1);
653                                 size_t len = j == string::npos
654                                                 ? token.substr(i + 1).length()
655                                                 : j - i - 1;
656                                 if (regex_match(token.substr(i + 1, len),
657                                                         sub, child_file)) {
658                                         string const name = sub.str(1);
659                                         child.push(make_pair(name, pnest));
660                                         i += len;
661                                 }
662                         } else if (token[i] == ')') {
663                                 if (!child.empty()
664                                     && child.top().second == pnest)
665                                         child.pop();
666                                 --pnest;
667                         }
668                 }
669                 child_name = child.empty() ? empty_string() : child.top().first;
670
671                 if (contains(token, "file:line:error style messages enabled"))
672                         fle_style = true;
673
674                 if (prefixIs(token, "LaTeX Warning:") ||
675                     prefixIs(token, "! pdfTeX warning")) {
676                         // Here shall we handle different
677                         // types of warnings
678                         retval |= LATEX_WARNING;
679                         LYXERR(Debug::LATEX, "LaTeX Warning.");
680                         if (contains(token, "Rerun to get cross-references")) {
681                                 retval |= RERUN;
682                                 LYXERR(Debug::LATEX, "We should rerun.");
683                         // package clefval needs 2 latex runs before bibtex
684                         } else if (contains(token, "Value of")
685                                    && contains(token, "on page")
686                                    && contains(token, "undefined")) {
687                                 retval |= ERROR_RERUN;
688                                 LYXERR(Debug::LATEX, "Force rerun.");
689                         // package etaremune
690                         } else if (contains(token, "Etaremune labels have changed")) {
691                                 retval |= ERROR_RERUN;
692                                 LYXERR(Debug::LATEX, "Force rerun.");
693                         } else if (contains(token, "Citation")
694                                    && contains(token, "on page")
695                                    && contains(token, "undefined")) {
696                                 retval |= UNDEF_CIT;
697                         } else if (contains(token, "Citation")
698                                    && contains(token, "on input line")
699                                    && contains(token, "undefined")) {
700                                 retval |= UNDEF_CIT;
701                         }
702                 } else if (prefixIs(token, "Package")) {
703                         // Package warnings
704                         retval |= PACKAGE_WARNING;
705                         if (contains(token, "natbib Warning:")) {
706                                 // Natbib warnings
707                                 if (contains(token, "Citation")
708                                     && contains(token, "on page")
709                                     && contains(token, "undefined")) {
710                                         retval |= UNDEF_CIT;
711                                 }
712                         } else if (contains(token, "run BibTeX")) {
713                                 retval |= UNDEF_CIT;
714                         } else if (contains(token, "run Biber")) {
715                                 retval |= UNDEF_CIT;
716                                 biber = true;
717                         } else if (contains(token, "Rerun LaTeX") ||
718                                    contains(token, "Please rerun LaTeX") ||
719                                    contains(token, "Rerun to get")) {
720                                 // at least longtable.sty and bibtopic.sty
721                                 // might use this.
722                                 LYXERR(Debug::LATEX, "We should rerun.");
723                                 retval |= RERUN;
724                         }
725                 } else if (prefixIs(token, "LETTRE WARNING:")) {
726                         if (contains(token, "veuillez recompiler")) {
727                                 // lettre.cls
728                                 LYXERR(Debug::LATEX, "We should rerun.");
729                                 retval |= RERUN;
730                         }
731                 } else if (token[0] == '(') {
732                         if (contains(token, "Rerun LaTeX") ||
733                             contains(token, "Rerun to get")) {
734                                 // Used by natbib
735                                 LYXERR(Debug::LATEX, "We should rerun.");
736                                 retval |= RERUN;
737                         }
738                 } else if (prefixIs(token, "! ")
739                             || (fle_style
740                                 && regex_match(token, sub, file_line_error)
741                                 && !contains(token, "pdfTeX warning"))) {
742                            // Ok, we have something that looks like a TeX Error
743                            // but what do we really have.
744
745                         // Just get the error description:
746                         string desc;
747                         if (prefixIs(token, "! "))
748                                 desc = string(token, 2);
749                         else if (fle_style)
750                                 desc = sub.str();
751                         if (contains(token, "LaTeX Error:"))
752                                 retval |= LATEX_ERROR;
753
754                         if (prefixIs(token, "! File ended while scanning")){
755                                 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
756                                         // bug 7344. We must rerun LaTeX if hyperref has been toggled.
757                                         retval |= ERROR_RERUN;
758                                         LYXERR(Debug::LATEX, "Force rerun.");
759                                 } else {
760                                         // bug 6445. At this point its not clear we finish with error.
761                                         wait_for_error = desc;
762                                         continue;
763                                 }
764                         }
765
766                         if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
767                                         // bug 7344. We must rerun LaTeX if hyperref has been toggled.
768                                         retval |= ERROR_RERUN;
769                                         LYXERR(Debug::LATEX, "Force rerun.");
770                         }
771
772                         if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
773                                 retval |= LATEX_ERROR;
774                                 string errstr;
775                                 int count = 0;
776                                 errstr = wait_for_error;
777                                 do {
778                                         if (!getline(ifs, tmp))
779                                                 break;
780                                         tmp = rtrim(tmp, "\r");
781                                         errstr += "\n" + tmp;
782                                         if (++count > 5)
783                                                 break;
784                                 } while (!contains(tmp, "(job aborted"));
785
786                                 terr.insertError(0,
787                                                  from_local8bit("Emergency stop"),
788                                                  from_local8bit(errstr),
789                                                  child_name);
790                         }
791
792                         // get the next line
793                         string tmp;
794                         int count = 0;
795                         do {
796                                 if (!getline(ifs, tmp))
797                                         break;
798                                 tmp = rtrim(tmp, "\r");
799                                 if (++count > 10)
800                                         break;
801                         } while (!prefixIs(tmp, "l."));
802                         if (prefixIs(tmp, "l.")) {
803                                 // we have a latex error
804                                 retval |=  TEX_ERROR;
805                                 if (contains(desc,
806                                     "Package babel Error: You haven't defined the language") ||
807                                     contains(desc,
808                                     "Package babel Error: You haven't loaded the option"))
809                                         retval |= ERROR_RERUN;
810                                 // get the line number:
811                                 int line = 0;
812                                 sscanf(tmp.c_str(), "l.%d", &line);
813                                 // get the rest of the message:
814                                 string errstr(tmp, tmp.find(' '));
815                                 errstr += '\n';
816                                 getline(ifs, tmp);
817                                 tmp = rtrim(tmp, "\r");
818                                 while (!contains(errstr, "l.")
819                                        && !tmp.empty()
820                                        && !prefixIs(tmp, "! ")
821                                        && !contains(tmp, "(job aborted")) {
822                                         errstr += tmp;
823                                         errstr += "\n";
824                                         getline(ifs, tmp);
825                                         tmp = rtrim(tmp, "\r");
826                                 }
827                                 LYXERR(Debug::LATEX, "line: " << line << '\n'
828                                         << "Desc: " << desc << '\n' << "Text: " << errstr);
829                                 if (line == last_line)
830                                         ++line_count;
831                                 else {
832                                         line_count = 1;
833                                         last_line = line;
834                                 }
835                                 if (line_count <= 5) {
836                                         // FIXME UNICODE
837                                         // We have no idea what the encoding of
838                                         // the log file is.
839                                         // It seems that the output from the
840                                         // latex compiler itself is pure ASCII,
841                                         // but it can include bits from the
842                                         // document, so whatever encoding we
843                                         // assume here it can be wrong.
844                                         terr.insertError(line,
845                                                          from_local8bit(desc),
846                                                          from_local8bit(errstr),
847                                                          child_name);
848                                         ++num_errors;
849                                 }
850                         }
851                 } else {
852                         // information messages, TeX warnings and other
853                         // warnings we have not caught earlier.
854                         if (prefixIs(token, "Overfull ")) {
855                                 retval |= TEX_WARNING;
856                         } else if (prefixIs(token, "Underfull ")) {
857                                 retval |= TEX_WARNING;
858                         } else if (contains(token, "Rerun to get citations")) {
859                                 // Natbib seems to use this.
860                                 retval |= UNDEF_CIT;
861                         } else if (contains(token, "No pages of output")) {
862                                 // A dvi file was not created
863                                 retval |= NO_OUTPUT;
864                         } else if (contains(token, "That makes 100 errors")) {
865                                 // More than 100 errors were reprted
866                                 retval |= TOO_MANY_ERRORS;
867                         } else if (prefixIs(token, "!pdfTeX error:")){
868                                 // otherwise we dont catch e.g.:
869                                 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
870                                 retval |= ERRORS;
871                                         terr.insertError(0,
872                                                          from_local8bit("pdfTeX Error"),
873                                                          from_local8bit(token),
874                                                          child_name);
875                         }
876                 }
877         }
878         LYXERR(Debug::LATEX, "Log line: " << token);
879         return retval;
880 }
881
882
883 namespace {
884
885 bool insertIfExists(FileName const & absname, DepTable & head)
886 {
887         if (absname.exists() && !absname.isDirectory()) {
888                 head.insert(absname, true);
889                 return true;
890         }
891         return false;
892 }
893
894
895 bool handleFoundFile(string const & ff, DepTable & head)
896 {
897         // convert from native os path to unix path
898         string foundfile = os::internal_path(trim(ff));
899
900         LYXERR(Debug::DEPEND, "Found file: " << foundfile);
901
902         // Ok now we found a file.
903         // Now we should make sure that this is a file that we can
904         // access through the normal paths.
905         // We will not try any fancy search methods to
906         // find the file.
907
908         // (1) foundfile is an
909         //     absolute path and should
910         //     be inserted.
911         FileName absname;
912         if (FileName::isAbsolute(foundfile)) {
913                 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
914                 // On initial insert we want to do the update at once
915                 // since this file cannot be a file generated by
916                 // the latex run.
917                 absname.set(foundfile);
918                 if (!insertIfExists(absname, head)) {
919                         // check for spaces
920                         string strippedfile = foundfile;
921                         while (contains(strippedfile, " ")) {
922                                 // files with spaces are often enclosed in quotation
923                                 // marks; those have to be removed
924                                 string unquoted = subst(strippedfile, "\"", "");
925                                 absname.set(unquoted);
926                                 if (insertIfExists(absname, head))
927                                         return true;
928                                 // strip off part after last space and try again
929                                 string tmp = strippedfile;
930                                 string const stripoff =
931                                         rsplit(tmp, strippedfile, ' ');
932                                 absname.set(strippedfile);
933                                 if (insertIfExists(absname, head))
934                                         return true;
935                         }
936                 }
937         }
938
939         string onlyfile = onlyFileName(foundfile);
940         absname = makeAbsPath(onlyfile);
941
942         // check for spaces
943         while (contains(foundfile, ' ')) {
944                 if (absname.exists())
945                         // everything o.k.
946                         break;
947                 else {
948                         // files with spaces are often enclosed in quotation
949                         // marks; those have to be removed
950                         string unquoted = subst(foundfile, "\"", "");
951                         absname = makeAbsPath(unquoted);
952                         if (absname.exists())
953                                 break;
954                         // strip off part after last space and try again
955                         string strippedfile;
956                         string const stripoff =
957                                 rsplit(foundfile, strippedfile, ' ');
958                         foundfile = strippedfile;
959                         onlyfile = onlyFileName(strippedfile);
960                         absname = makeAbsPath(onlyfile);
961                 }
962         }
963
964         // (2) foundfile is in the tmpdir
965         //     insert it into head
966         if (absname.exists() && !absname.isDirectory()) {
967                 // FIXME: This regex contained glo, but glo is used by the old
968                 // version of nomencl.sty. Do we need to put it back?
969                 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
970                 if (regex_match(onlyfile, unwanted)) {
971                         LYXERR(Debug::DEPEND, "We don't want " << onlyfile
972                                 << " in the dep file");
973                 } else if (suffixIs(onlyfile, ".tex")) {
974                         // This is a tex file generated by LyX
975                         // and latex is not likely to change this
976                         // during its runs.
977                         LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
978                         head.insert(absname, true);
979                 } else {
980                         LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
981                         head.insert(absname);
982                 }
983                 return true;
984         } else {
985                 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
986                 return false;
987         }
988 }
989
990
991 bool completeFilename(string const & ff, DepTable & head)
992 {
993         // If we do not find a dot, we suspect
994         // a fragmental file name
995         if (!contains(ff, '.'))
996                 return false;
997
998         // if we have a dot, we let handleFoundFile decide
999         return handleFoundFile(ff, head);
1000 }
1001
1002
1003 int iterateLine(string const token, regex const reg, string const & closing,
1004                 int fragment_pos, DepTable & head)
1005 {
1006         smatch what;
1007         string::const_iterator first = token.begin();
1008         string::const_iterator end = token.end();
1009         bool fragment = false;
1010         string last_match;
1011
1012         while (regex_search(first, end, what, reg)) {
1013                 // if we have a dot, try to handle as file
1014                 if (contains(what.str(1), '.')) {
1015                         first = what[0].second;
1016                         if (what.str(2) == closing) {
1017                                 handleFoundFile(what.str(1), head);
1018                                 // since we had a closing bracket,
1019                                 // do not investigate further
1020                                 fragment = false;
1021                         } else
1022                                 // if we have no closing bracket,
1023                                 // try to handle as file nevertheless
1024                                 fragment = !handleFoundFile(
1025                                         what.str(1) + what.str(2), head);
1026                 }
1027                 // if we do not have a dot, check if the line has
1028                 // a closing bracket (else, we suspect a line break)
1029                 else if (what.str(2) != closing) {
1030                         first = what[0].second;
1031                         fragment = true;
1032                 } else {
1033                         // we have a closing bracket, so the content
1034                         // is not a file name.
1035                         // no need to investigate further
1036                         first = what[0].second;
1037                         fragment = false;
1038                 }
1039                 last_match = what.str(1);
1040         }
1041
1042         // We need to consider the result from previous line iterations:
1043         // We might not find a fragment here, but another one might follow
1044         // E.g.: (filename.ext) <filenam
1045         // Vice versa, we consider the search completed if a real match
1046         // follows a potential fragment from a previous iteration.
1047         // E.g. <some text we considered a fragment (filename.ext)
1048         // result = -1 means we did not find a fragment!
1049         int result = -1;
1050         int last_match_pos = -1;
1051         if (!last_match.empty() && token.find(last_match) != string::npos)
1052                 last_match_pos = int(token.find(last_match));
1053         if (fragment) {
1054                 if (last_match_pos > fragment_pos)
1055                         result = last_match_pos;
1056                 else
1057                         result = fragment_pos;
1058         } else
1059                 if (last_match_pos < fragment_pos)
1060                         result = fragment_pos;
1061
1062         return result;
1063 }
1064
1065 } // anon namespace
1066
1067
1068 void LaTeX::deplog(DepTable & head)
1069 {
1070         // This function reads the LaTeX log file end extracts all the
1071         // external files used by the LaTeX run. The files are then
1072         // entered into the dependency file.
1073
1074         string const logfile =
1075                 onlyFileName(changeExtension(file.absFileName(), ".log"));
1076
1077         static regex const reg1("File: (.+).*");
1078         static regex const reg2("No file (.+)(.).*");
1079         static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1080         // If an index should be created, MikTex does not write a line like
1081         //    \openout# = 'sample.idx'.
1082         // but instead only a line like this into the log:
1083         //   Writing index file sample.idx
1084         static regex const reg4("Writing index file (.+).*");
1085         static regex const regoldnomencl("Writing glossary file (.+).*");
1086         static regex const regnomencl("Writing nomenclature file (.+).*");
1087         // If a toc should be created, MikTex does not write a line like
1088         //    \openout# = `sample.toc'.
1089         // but only a line like this into the log:
1090         //    \tf@toc=\write#
1091         // This line is also written by tetex.
1092         // This line is not present if no toc should be created.
1093         static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1094         // file names can be enclosed in <...> (anywhere on the line)
1095         static regex const reg5(".*<[^>]+.*");
1096         // and also (...) anywhere on the line
1097         static regex const reg6(".*\\([^)]+.*");
1098
1099         FileName const fn = makeAbsPath(logfile);
1100         ifstream ifs(fn.toFilesystemEncoding().c_str());
1101         string lastline;
1102         while (ifs) {
1103                 // Ok, the scanning of files here is not sufficient.
1104                 // Sometimes files are named by "File: xxx" only
1105                 // Therefore we use some regexps to find files instead.
1106                 // Note: all file names and paths might contains spaces.
1107                 // Also, file names might be broken across lines. Therefore
1108                 // we mark (potential) fragments and merge those lines.
1109                 bool fragment = false;
1110                 string token;
1111                 getline(ifs, token);
1112                 // MikTeX sometimes inserts \0 in the log file. They can't be
1113                 // removed directly with the existing string utility
1114                 // functions, so convert them first to \r, and remove all
1115                 // \r's afterwards, since we need to remove them anyway.
1116                 token = subst(token, '\0', '\r');
1117                 token = subst(token, "\r", "");
1118                 if (token.empty() || token == ")") {
1119                         lastline = string();
1120                         continue;
1121                 }
1122
1123                 // FIXME UNICODE: We assume that the file names in the log
1124                 // file are in the file system encoding.
1125                 token = to_utf8(from_filesystem8bit(token));
1126
1127                 // Sometimes, filenames are broken across lines.
1128                 // We care for that and save suspicious lines.
1129                 // Here we exclude some cases where we are sure
1130                 // that there is no continued filename
1131                 if (!lastline.empty()) {
1132                         static regex const package_info("Package \\w+ Info: .*");
1133                         static regex const package_warning("Package \\w+ Warning: .*");
1134                         if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1135                             || prefixIs(token, "Package:")
1136                             || prefixIs(token, "Language:")
1137                             || prefixIs(token, "LaTeX Info:")
1138                             || prefixIs(token, "LaTeX Font Info:")
1139                             || prefixIs(token, "\\openout[")
1140                             || prefixIs(token, "))")
1141                             || regex_match(token, package_info)
1142                             || regex_match(token, package_warning))
1143                                 lastline = string();
1144                 }
1145
1146                 if (!lastline.empty())
1147                         // probably a continued filename from last line
1148                         token = lastline + token;
1149                 if (token.length() > 255) {
1150                         // string too long. Cut off.
1151                         token.erase(0, token.length() - 251);
1152                 }
1153
1154                 smatch sub;
1155
1156                 // (1) "File: file.ext"
1157                 if (regex_match(token, sub, reg1)) {
1158                         // is this a fragmental file name?
1159                         fragment = !completeFilename(sub.str(1), head);
1160                         // However, ...
1161                         if (suffixIs(token, ")"))
1162                                 // no fragment for sure
1163                                 fragment = false;
1164                 // (2) "No file file.ext"
1165                 } else if (regex_match(token, sub, reg2)) {
1166                         // file names must contains a dot, line ends with dot
1167                         if (contains(sub.str(1), '.') && sub.str(2) == ".")
1168                                 fragment = !handleFoundFile(sub.str(1), head);
1169                         else
1170                                 // we suspect a line break
1171                                 fragment = true;
1172                 // (3) "\openout<nr> = `file.ext'."
1173                 } else if (regex_match(token, sub, reg3)) {
1174                         // search for closing '. at the end of the line
1175                         if (sub.str(2) == "\'.")
1176                                 fragment = !handleFoundFile(sub.str(1), head);
1177                         else
1178                                 // potential fragment
1179                                 fragment = true;
1180                 // (4) "Writing index file file.ext"
1181                 } else if (regex_match(token, sub, reg4))
1182                         // fragmential file name?
1183                         fragment = !completeFilename(sub.str(1), head);
1184                 // (5) "Writing nomenclature file file.ext"
1185                 else if (regex_match(token, sub, regnomencl) ||
1186                            regex_match(token, sub, regoldnomencl))
1187                         // fragmental file name?
1188                         fragment= !completeFilename(sub.str(1), head);
1189                 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1190                 else if (regex_match(token, sub, miktexTocReg))
1191                         fragment = !handleFoundFile(onlyFileName(changeExtension(
1192                                                 file.absFileName(), ".toc")), head);
1193                 else
1194                         // not found, but we won't check further
1195                         fragment = false;
1196
1197                 int fragment_pos = -1;
1198                 // (7) "<file.ext>"
1199                 // We can have several of these on one line
1200                 // (and in addition to those above)
1201                 if (regex_match(token, sub, reg5)) {
1202                         // search for strings in <...>
1203                         static regex reg5_1("<([^>]+)(.)");
1204                         fragment_pos = iterateLine(token, reg5_1, ">",
1205                                                    fragment_pos, head);
1206                         fragment = (fragment_pos != -1);
1207                 }
1208
1209                 // (8) "(file.ext)"
1210                 // We can have several of these on one line
1211                 // this must be queried separated, because of
1212                 // cases such as "File: file.ext (type eps)"
1213                 // where "File: file.ext" would be skipped
1214                 if (regex_match(token, sub, reg6)) {
1215                         // search for strings in (...)
1216                         static regex reg6_1("\\(([^()]+)(.)");
1217                         fragment_pos = iterateLine(token, reg6_1, ")",
1218                                                    fragment_pos, head);
1219                         fragment = (fragment_pos != -1);
1220                 }
1221
1222                 if (fragment)
1223                         // probable linebreak within file name:
1224                         // save this line
1225                         lastline = token;
1226                 else
1227                         // no linebreak: reset
1228                         lastline = string();
1229         }
1230
1231         // Make sure that the main .tex file is in the dependency file.
1232         head.insert(file, true);
1233 }
1234
1235
1236 void LaTeX::scanBlgFile(DepTable & dep)
1237 {
1238         FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1239         LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1240
1241         ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1242         string token;
1243         static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1244
1245         while (getline(ifs, token)) {
1246                 token = rtrim(token, "\r");
1247                 smatch sub;
1248                 // FIXME UNICODE: We assume that citation keys and filenames
1249                 // in the aux file are in the file system encoding.
1250                 token = to_utf8(from_filesystem8bit(token));
1251                 if (regex_match(token, sub, reg1)) {
1252                         string data = sub.str(3);
1253                         if (!data.empty()) {
1254                                 LYXERR(Debug::LATEX, "Found bib file: " << data);
1255                                 handleFoundFile(data, dep);
1256                         }
1257                 }
1258         } 
1259 }
1260
1261
1262 } // namespace lyx