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