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