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