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