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