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