]> git.lyx.org Git - lyx.git/blob - src/LaTeX.C
Angus insetindex patch + protect patch from Dekel
[lyx.git] / src / LaTeX.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor         
5  *           Copyright 1995 Matthias Ettrich
6  *           Copyright 1995-2000 The LyX Team.
7  *
8  *           This file is Copyright 1996-2000
9  *           Lars Gullik Bjønnes
10  *
11  * ====================================================== 
12  */
13
14 #include <config.h>
15
16 #ifdef __GNUG__
17 #pragma implementation
18 #endif
19 #include <fstream>
20
21 #include "support/filetools.h"
22 #include "LaTeX.h"
23 #include "support/FileInfo.h"
24 #include "debug.h"
25 #include "support/lyxlib.h"
26 #include "support/syscall.h"
27 #include "support/syscontr.h"
28 #include "support/path.h"
29 #include "support/LRegex.h"
30 #include "support/LSubstring.h"
31 #include "bufferlist.h"
32 #include "minibuffer.h"
33 #include "gettext.h"
34
35 using std::ifstream;
36 using std::getline;
37 using std::endl;
38
39 // TODO: in no particular order
40 // - get rid of the extern BufferList and the call to
41 //   BufferList::updateIncludedTeXfiles, this should either
42 //   be done before calling LaTeX::funcs or in a completely
43 //   different way.
44 // - the bibtex command options should be supported.
45 // - the makeindex style files should be taken care of with
46 //   the dependency mechanism.
47 // - makeindex commandline options should be supported
48 // - somewhere support viewing of bibtex and makeindex log files.
49 // - we should perhaps also scan the bibtex log file
50 // - we should perhaps also scan the bibtex log file
51
52 extern BufferList bufferlist;
53
54 /*
55  * CLASS TEXERRORS
56  */
57
58 void TeXErrors::insertError(int line, string const & error_desc,
59                             string const & error_text)
60 {
61         Error newerr(line, error_desc, error_text);
62         errors.push_back(newerr);
63 }
64
65 /*
66  * CLASS LaTeX
67  */
68
69 LaTeX::LaTeX(string const & latex, string const & f, string const & p)
70                 : cmd(latex), file(f), path(p)
71 {
72         num_errors = 0;
73         depfile = file + ".dep";
74 }
75
76
77 void LaTeX::deleteFilesOnError() const
78 {
79         // currently just a dummy function.
80
81         // What files do we have to delete?
82
83         // This will at least make latex do all the runs
84         ::unlink(depfile.c_str());
85
86         // but the reason for the error might be in a generated file...
87
88         string ofname = OnlyFilename(file);
89
90         // bibtex file
91         string bbl = ChangeExtension(ofname, ".bbl");
92         ::unlink(bbl.c_str());
93
94         // makeindex file
95         string ind = ChangeExtension(ofname, ".ind");
96         ::unlink(ind.c_str());
97         
98         // Also remove the aux file
99         string aux = ChangeExtension(ofname, ".aux");
100         ::unlink(aux.c_str());
101 }
102
103
104 int LaTeX::run(TeXErrors & terr, MiniBuffer * minib)
105         // We know that this function will only be run if the lyx buffer
106         // has been changed. We also know that a newly written .tex file
107         // is always different from the previous one because of the date
108         // in it. However it seems safe to run latex (at least) on time each
109         // time the .tex file changes.
110 {
111         int scanres = LaTeX::NO_ERRORS;
112         unsigned int count = 0; // number of times run
113         num_errors = 0; // just to make sure.
114         const unsigned int MAX_RUN = 6;
115         DepTable head; // empty head
116         bool rerun = false; // rerun requested
117         
118         // The class LaTeX does not know the temp path.
119         bufferlist.updateIncludedTeXfiles(GetCWD());
120         
121         // Never write the depfile if an error was encountered.
122         
123         // 0
124         // first check if the file dependencies exist:
125         //     ->If it does exist
126         //             check if any of the files mentioned in it have
127         //             changed (done using a checksum).
128         //                 -> if changed:
129         //                        run latex once and
130         //                        remake the dependency file
131         //                 -> if not changed:
132         //                        just return there is nothing to do for us.
133         //     ->if it doesn't exist
134         //             make it and
135         //             run latex once (we need to run latex once anyway) and
136         //             remake the dependency file.
137         //
138         FileInfo fi(depfile);
139         bool run_bibtex = false;
140         if (fi.exist()) {
141                 // Read the dep file:
142                 head.read(depfile);
143                 // Update the checksums
144                 head.update();
145                 
146                 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
147                 if (head.sumchange()) {
148                         ++count;
149                         lyxerr[Debug::DEPEND]
150                                 << "Dependency file has changed" << endl;
151                         lyxerr[Debug::LATEX]
152                                 << "Run #" << count << endl; 
153                         minib->Set(string(_("LaTeX run number ")) + tostr(count));
154                         minib->Store();
155                         this->operator()();
156                         scanres = scanLogFile(terr);
157                         if (scanres & LaTeX::ERRORS) {
158                                 deleteFilesOnError();
159                                 return scanres; // return on error
160                         }
161                         
162                         run_bibtex = scanAux(head);
163                         if (run_bibtex)
164                                 lyxerr[Debug::DEPEND]
165                                         << "Bibtex demands rerun" << endl;
166                 } else {
167                         lyxerr[Debug::DEPEND] << "return no_change" << endl;
168                         return LaTeX::NO_CHANGE;
169                 }
170         } else {
171                 ++count;
172                 lyxerr[Debug::DEPEND]
173                         << "Dependency file does not exist" << endl;
174                 
175                 lyxerr[Debug::LATEX]
176                         << "Run #" << count << endl;
177                 head.insert(file, true);
178                 minib->Set(string(_("LaTeX run number ")) + tostr(count));
179                 minib->Store();
180                 this->operator()();
181                 scanres = scanLogFile(terr);
182                 if (scanres & LaTeX::ERRORS) {
183                         deleteFilesOnError();
184                         return scanres; // return on error
185                 }
186                 
187         }
188
189         // update the dependencies.
190         deplog(head); // reads the latex log
191         head.update();
192
193         // 0.5
194         // At this point we must run external programs if needed.
195         // makeindex will be run if a .idx file changed or was generated.
196         // And if there were undefined citations or changes in references
197         // the .aux file is checked for signs of bibtex. Bibtex is then run
198         // if needed.
199         
200         // run makeindex
201         if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
202                 // no checks for now
203                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
204                 minib->Set(_("Running MakeIndex."));
205                 minib->Store();
206                 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
207         }
208
209         // run bibtex
210         if (scanres & LaTeX::UNDEF_CIT
211             || scanres & LaTeX::RERUN
212             || run_bibtex) {
213                 // Here we must scan the .aux file and look for
214                 // "\bibdata" and/or "\bibstyle". If one of those
215                 // tags is found -> run bibtex and set rerun = true;
216                 // no checks for now
217                 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
218                 minib->Set(_("Running BibTeX."));
219                 minib->Store();
220                 rerun = runBibTeX(OnlyFilename(ChangeExtension(file, ".aux")), 
221                                   head);
222         }
223         
224         // 1
225         // we know on this point that latex has been run once (or we just
226         // returned) and the question now is to decide if we need to run
227         // it any more. This is done by asking if any of the files in the
228         // dependency file has changed. (remember that the checksum for
229         // a given file is reported to have changed if it just was created)
230         //     -> if changed or rerun == true:
231         //             run latex once more and
232         //             update the dependency structure
233         //     -> if not changed:
234         //             we does nothing at this point
235         //
236         if (rerun || head.sumchange()) {
237                 rerun = false;
238                 ++count;
239                 lyxerr[Debug::DEPEND]
240                         << "Dep. file has changed or rerun requested" << endl;
241                 lyxerr[Debug::LATEX]
242                         << "Run #" << count << endl;
243                 minib->Set(string(_("LaTeX run number ")) + tostr(count));
244                 minib->Store();
245                 this->operator()();
246                 scanres = scanLogFile(terr);
247                 if (scanres & LaTeX::ERRORS) {
248                         deleteFilesOnError();
249                         return scanres; // return on error
250                 }
251                 
252                 // update the depedencies
253                 deplog(head); // reads the latex log
254                 head.update();
255         } else {
256                 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
257         }
258
259         // 1.5
260         // The inclusion of files generated by external programs like
261         // makeindex or bibtex might have done changes to pagenumbereing,
262         // etc. And because of this we must run the external programs
263         // again to make sure everything is redone correctly.
264         // Also there should be no need to run the external programs any
265         // more after this.
266         
267         // run makeindex if the <file>.idx has changed or was generated.
268         if (head.haschanged(OnlyFilename(ChangeExtension(file, ".idx")))) {
269                 // no checks for now
270                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
271                 minib->Set(_("Running MakeIndex."));
272                 minib->Store();
273                 rerun = runMakeIndex(OnlyFilename(ChangeExtension(file, ".idx")));
274         }
275         
276         // 2
277         // we will only run latex more if the log file asks for it.
278         // or if the sumchange() is true.
279         //     -> rerun asked for:
280         //             run latex and
281         //             remake the dependency file
282         //             goto 2 or return if max runs are reached.
283         //     -> rerun not asked for:
284         //             just return (fall out of bottom of func)
285         //
286         while ((head.sumchange() || rerun || (scanres & LaTeX::RERUN)) 
287                && count < MAX_RUN) {
288                 // Yes rerun until message goes away, or until
289                 // MAX_RUNS are reached.
290                 rerun = false;
291                 ++count;
292                 lyxerr[Debug::LATEX] << "Run #" << count << endl;
293                 minib->Set(string(_("LaTeX run number ")) + tostr(count));
294                 minib->Store();
295                 this->operator()();
296                 scanres = scanLogFile(terr);
297                 if (scanres & LaTeX::ERRORS) {
298                         deleteFilesOnError();
299                         return scanres; // return on error
300                 }
301                 
302                 // keep this updated
303                 head.update();
304         }
305
306         // Write the dependencies to file.
307         head.write(depfile);
308         lyxerr[Debug::LATEX] << "Done." << endl;
309         return scanres;
310 }
311
312
313 int LaTeX::operator()()
314 {
315 #ifndef __EMX__
316         string tmp = cmd + ' ' + QuoteName(file) + " > /dev/null";
317 #else // cmd.exe (OS/2) causes SYS0003 error at "/dev/null"
318         string tmp = cmd + ' ' + file + " > nul";
319 #endif
320         Systemcalls one;
321         return one.startscript(Systemcalls::System, tmp);
322 }
323
324
325 bool LaTeX::runMakeIndex(string const & f)
326 {
327         lyxerr[Debug::LATEX] << "idx file has been made,"
328                 " running makeindex on file "
329                              <<  f << endl;
330
331         // It should be possible to set the switches for makeindex
332         // sorting style and such. It would also be very convenient
333         // to be able to make style files from within LyX. This has
334         // to come for a later time. (0.13 perhaps?)
335         string tmp = "makeindex -c -q ";
336         tmp += f;
337         Systemcalls one;
338         one.startscript(Systemcalls::System, tmp);
339         return true;
340 }
341
342
343 bool LaTeX::scanAux(DepTable & dep)
344 {
345         // if any of the bib file has changed we don't have to
346         // check the .aux file.
347         if (dep.extchanged(".bib")
348             || dep.extchanged(".bst")) return true;
349         
350         string aux = OnlyFilename(ChangeExtension(file, ".aux"));
351         ifstream ifs(aux.c_str());
352         string token;
353         LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
354         LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
355         while (getline(ifs, token)) {
356                 if (reg1.exact_match(token)) {
357                         LRegex::SubMatches sub = reg1.exec(token);
358                         string data = LSubstring(token, sub[1].first,
359                                                  sub[1].second);
360                         string::size_type b;
361                         do {
362                                 b = data.find_first_of(',', 0);
363                                 string l;
364                                 if (b == string::npos)
365                                         l = data;
366                                 else {
367                                         l = data.substr( 0, b - 0);
368                                         data.erase(0, b + 1);
369                                 }
370                                 string full_l =
371                                         findtexfile(
372                                                 ChangeExtension(l, "bib"), "bib");
373                                 if (!full_l.empty()) {
374                                         if (!dep.exist(full_l))
375                                                 return true;
376                                 }
377                         } while (b != string::npos);
378                 } else if (reg2.exact_match(token)) {
379                         LRegex::SubMatches sub = reg2.exec(token);
380                         string style = LSubstring(token, sub[1].first,
381                                                   sub[1].second);
382                         // token is now the style file
383                         // pass it to the helper
384                         string full_l =
385                                 findtexfile(
386                                         ChangeExtension(style, "bst"),
387                                         "bst");
388                         if (!full_l.empty()) {
389                                 if (!dep.exist(full_l))
390                                         return true;
391                         }
392                 }
393         }
394         return false;
395 }
396
397
398 bool LaTeX::runBibTeX(string const & f, DepTable & dep)
399 {
400         // Since a run of Bibtex mandates more latex runs it is ok to
401         // remove all ".bib" and ".bst" files, it is also required to
402         // discover style and database changes.
403         dep.remove_files_with_extension(".bib");
404         dep.remove_files_with_extension(".bst");
405         ifstream ifs(f.c_str());
406         string token;
407         bool using_bibtex = false;
408         LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
409         LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
410         while (getline(ifs, token)) {
411                 if (reg1.exact_match(token)) {
412                         using_bibtex = true;
413                         LRegex::SubMatches const & sub = reg1.exec(token);
414                         string data = LSubstring(token, sub[1].first,
415                                                  sub[1].second);
416                         // data is now all the bib files separated by ','
417                         // get them one by one and pass them to the helper
418                         string::size_type b;
419                         do {
420                                 b = data.find_first_of(',', 0);
421                                 string l;
422                                 if (b == string::npos)
423                                         l = data;
424                                 else {
425                                         l = data.substr(0, b - 0);
426                                         data.erase(0, b + 1);
427                                 }
428                                 string full_l = 
429                                         findtexfile(
430                                                 ChangeExtension(l, "bib"),
431                                                 "bib");
432                                 lyxerr[Debug::LATEX] << "Bibtex database: `"
433                                                      << full_l << "'" << endl;
434                                 if (!full_l.empty()) {
435                                         // add full_l to the dep file.
436                                         dep.insert(full_l, true);
437                                 }
438                         } while (b != string::npos);
439                 } else if (reg2.exact_match(token)) {
440                         using_bibtex = true;
441                         LRegex::SubMatches const & sub = reg2.exec(token);
442                         string style = LSubstring(token, sub[1].first,
443                                                   sub[1].second);
444                         // token is now the style file
445                         // pass it to the helper
446                         string full_l = 
447                                 findtexfile(
448                                         ChangeExtension(style, "bst"),
449                                         "bst");
450                         lyxerr[Debug::LATEX] << "Bibtex style: `"
451                                              << full_l << "'" << endl;
452                         if (!full_l.empty()) {
453                                 // add full_l to the dep file.
454                                 dep.insert(full_l, true);
455                         }
456                 }
457         }
458         if (using_bibtex) {
459                 // run bibtex and
460                 string tmp = "bibtex ";
461                 tmp += OnlyFilename(ChangeExtension(file, string()));
462                 Systemcalls one;
463                 one.startscript(Systemcalls::System, tmp);
464                 return true;
465         }
466         // bibtex was not run.
467         return false;
468 }
469
470
471 int LaTeX::scanLogFile(TeXErrors & terr)
472 {
473         int last_line = -1;
474         int line_count = 1;
475         int retval = NO_ERRORS;
476         string tmp = OnlyFilename(ChangeExtension(file, ".log"));
477         lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
478         ifstream ifs(tmp.c_str());
479
480         string token;
481         while (getline(ifs, token)) {
482                 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
483                 
484                 if (token.empty())
485                         continue;
486
487                 if (prefixIs(token, "LaTeX Warning:")) {
488                         // Here shall we handle different
489                         // types of warnings
490                         retval |= LATEX_WARNING;
491                         lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
492                         if (contains(token, "Rerun to get cross-references")) {
493                                 retval |= RERUN;
494                                 lyxerr[Debug::LATEX]
495                                         << "We should rerun." << endl;
496                         } else if (contains(token, "Citation")
497                                    && contains(token, "on page")
498                                    && contains(token, "undefined")) {
499                                 retval |= UNDEF_CIT;
500                         }
501                 } else if (prefixIs(token, "Package")) {
502                         // Package warnings
503                         retval |= PACKAGE_WARNING;
504                         if (contains(token, "natbib Warning:")) {
505                                 // Natbib warnings
506                                 if (contains(token, "Citation")
507                                     && contains(token, "on page")
508                                     && contains(token, "undefined")) {
509                                         retval |= UNDEF_CIT;
510                                 }
511                         } else if (contains(token, "Rerun LaTeX.")) {
512                                 // at least longtable.sty might use this.
513                                 retval |= RERUN;
514                         }
515                 } else if (prefixIs(token, "! ")) {
516                         // Ok, we have something that looks like a TeX Error
517                         // but what do we really have.
518
519                         // Just get the error description:
520                         string desc(token, 2);
521                         if (contains(token, "LaTeX Error:"))
522                                 retval |= LATEX_ERROR;
523                         // get the next line
524                         string tmp;
525                         int count = 0;
526                         do {
527                                 if (!getline(ifs, tmp))
528                                         break;
529                                 if (++count > 10)
530                                         break;
531                         } while (!prefixIs(tmp, "l."));
532                         if (prefixIs(tmp, "l.")) {
533                                 // we have a latex error
534                                 retval |=  TEX_ERROR;
535                                 // get the line number:
536                                 int line = 0;
537                                 sscanf(tmp.c_str(), "l.%d", &line);
538                                 // get the rest of the message:
539                                 string errstr(tmp, tmp.find(' '));
540                                 errstr += '\n';
541                                 getline(ifs, tmp);
542                                 while (!contains(errstr, "l.")
543                                        && !tmp.empty()
544                                        && !prefixIs(tmp, "! ")
545                                        && !contains(tmp, "(job aborted")) {
546                                         errstr += tmp;
547                                         errstr += "\n";
548                                         getline(ifs, tmp);
549                                 }
550                                 lyxerr[Debug::LATEX]
551                                         << "line: " << line << '\n'
552                                         << "Desc: " << desc << '\n'
553                                         << "Text: " << errstr << endl;
554                                 if (line == last_line)
555                                         ++line_count;
556                                 else {
557                                         line_count = 1;
558                                         last_line = line;
559                                 }
560                                 if (line_count <= 5) {
561                                         terr.insertError(line, desc, errstr);
562                                         ++num_errors;
563                                 }
564                         }
565                 } else {
566                         // information messages, TeX warnings and other
567                         // warnings we have not caught earlier.
568                         if (prefixIs(token, "Overfull ")) {
569                                 retval |= TEX_WARNING;
570                         } else if (prefixIs(token, "Underfull ")) {
571                                 retval |= TEX_WARNING;
572                         } else if (contains(token, "Rerun to get citations")) {
573                                 // Natbib seems to use this.
574                                 retval |= RERUN;
575                         } else if (contains(token, "No pages of output")) {
576                                 // A dvi file was not created
577                                 retval |= NO_OUTPUT;
578                         } else if (contains(token, "That makes 100 errors")) {
579                                 // More than 100 errors were reprted
580                                 retval |= TOO_MANY_ERRORS;
581                         }
582                 }
583         }
584         lyxerr[Debug::LATEX] << "Log line: " << token << endl;
585         return retval;
586 }
587
588
589 void LaTeX::deplog(DepTable & head)
590 {
591         // This function reads the LaTeX log file end extracts all the external
592         // files used by the LaTeX run. The files are then entered into the
593         // dependency file.
594
595         string logfile = OnlyFilename(ChangeExtension(file, ".log"));
596
597         LRegex reg1(")* *\\(([^ ]+).*");
598         LRegex reg2("File: ([^ ]+).*");
599         LRegex reg3("No file ([^ ]+)\\..*");
600         LRegex reg4("\\\\openout[0-9]+.*=.*`([^ ]+)'\\..*");
601         LRegex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
602         
603         ifstream ifs(logfile.c_str());
604         while (ifs) {
605                 // Ok, the scanning of files here is not sufficient.
606                 // Sometimes files are named by "File: xxx" only
607                 // So I think we should use some regexps to find files instead.
608                 // "(\([^ ]+\)"   should match the "(file " variant
609                 // "File: \([^ ]+\)" should match the "File: file" variant
610                 string foundfile;
611                 string token;
612                 getline(ifs, token);
613                 if (token.empty()) continue;
614                 
615                 if (reg1.exact_match(token)) {
616                         LRegex::SubMatches const & sub = reg1.exec(token);
617                         foundfile = LSubstring(token, sub[1].first,
618                                                sub[1].second);
619                 } else if (reg2.exact_match(token)) {
620                         LRegex::SubMatches const & sub = reg2.exec(token);
621                         foundfile = LSubstring(token, sub[1].first,
622                                                sub[1].second);
623                 } else if (reg3.exact_match(token)) {
624                         LRegex::SubMatches const & sub = reg3.exec(token);
625                         foundfile = LSubstring(token, sub[1].first,
626                                                sub[1].second);
627                 } else if (reg4.exact_match(token)) {
628                         LRegex::SubMatches const & sub = reg4.exec(token);
629                         foundfile = LSubstring(token, sub[1].first,
630                                                sub[1].second);
631                 } else {
632                         continue;
633                 }
634
635                 lyxerr[Debug::DEPEND] << "Found file: " 
636                                       << foundfile << endl;
637                 
638                 // Ok now we found a file.
639                 // Now we should make sure that this is a file that we can
640                 // access through the normal paths.
641                 // We will not try any fance search methods to
642                 // find the file.
643                 
644                 // (1) foundfile is an
645                 //     absolute path and should
646                 //     be inserted.
647                 if (AbsolutePath(foundfile)) {
648                         lyxerr[Debug::DEPEND] << "AbsolutePath file: " 
649                                               << foundfile << endl;
650                         // On inital insert we want to do the update at once
651                         // since this file can not be a file generated by
652                         // the latex run.
653                         head.insert(foundfile, true);
654                         continue;
655                 }
656
657                 // (2) foundfile is in the tmpdir
658                 //     insert it into head
659                 if (FileInfo(OnlyFilename(foundfile)).exist()) {
660                         if (unwanted.exact_match(foundfile)) {
661                                 lyxerr[Debug::DEPEND]
662                                         << "We don't want "
663                                         << OnlyFilename(foundfile)
664                                         << " in the dep file"
665                                         << endl;
666                         } else if (suffixIs(foundfile, ".tex")) {
667                                 // This is a tex file generated by LyX
668                                 // and latex is not likely to change this
669                                 // during its runs.
670                                 lyxerr[Debug::DEPEND]
671                                         << "Tmpdir TeX file: "
672                                         << OnlyFilename(foundfile)
673                                         << endl;
674                                 head.insert(foundfile, true);
675                         } else {
676                                 lyxerr[Debug::DEPEND]
677                                         << "In tmpdir file:"
678                                         << OnlyFilename(foundfile)
679                                         << endl;
680                                 head.insert(OnlyFilename(foundfile));
681                         }
682                         continue;
683                 }
684                 lyxerr[Debug::DEPEND]
685                         << "Not a file or we are unable to find it."
686                         << endl;
687         }
688 }