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