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