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