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