]> git.lyx.org Git - lyx.git/blob - src/LaTeX.C
411519627e95491480c560e88ee241dd5a60f9e9
[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 & f)
300 {
301         lyxerr[Debug::LATEX] << "idx file has been made,"
302                 " running makeindex on file "
303                              <<  f << 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 += f;
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 & f, 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(f.c_str());
380         string token;
381         bool using_bibtex = false;
382         LRegex reg1("\\\\bibdata\\{([^}]+)\\}");
383         LRegex reg2("\\\\bibstyle\\{([^}]+)\\}");
384         while (getline(ifs, token)) {
385                 if (reg1.exact_match(token)) {
386                         using_bibtex = true;
387                         LRegex::SubMatches const & sub = reg1.exec(token);
388                         string data = LSubstring(token, sub[1].first,
389                                                  sub[1].second);
390                         // data is now all the bib files separated by ','
391                         // get them one by one and pass them to the helper
392                         string::size_type b;
393                         do {
394                                 b = data.find_first_of(',', 0);
395                                 string l;
396                                 if (b == string::npos)
397                                         l = data;
398                                 else {
399                                         l = data.substr(0, b - 0);
400                                         data.erase(0, b + 1);
401                                 }
402                                 string full_l = 
403                                         findtexfile(
404                                                 ChangeExtension(l, "bib", false),
405                                                 "bib");
406                                 lyxerr[Debug::LATEX] << "Bibtex database: `"
407                                                      << full_l << "'" << endl;
408                                 if (!full_l.empty()) {
409                                         // add full_l to the dep file.
410                                         dep.insert(full_l, true);
411                                 }
412                         } while (b != string::npos);
413                 } else if (reg2.exact_match(token)) {
414                         using_bibtex = true;
415                         LRegex::SubMatches const & sub = reg2.exec(token);
416                         string style = LSubstring(token, sub[1].first,
417                                                   sub[1].second);
418                         // token is now the style file
419                         // pass it to the helper
420                         string full_l = 
421                                 findtexfile(
422                                         ChangeExtension(style, "bst", false),
423                                         "bst");
424                         lyxerr[Debug::LATEX] << "Bibtex style: `"
425                                              << full_l << "'" << endl;
426                         if (!full_l.empty()) {
427                                 // add full_l to the dep file.
428                                 dep.insert(full_l, true);
429                         }
430                 }
431         }
432         if (using_bibtex) {
433                 // run bibtex and
434                 string tmp = "bibtex ";
435                 tmp += ChangeExtension(file, string(), true);
436                 Systemcalls one;
437                 one.startscript(Systemcalls::System, tmp);
438                 return true;
439         }
440         // bibtex was not run.
441         return false;
442 }
443
444
445 int LaTeX::scanLogFile(TeXErrors & terr)
446 {
447         int retval = NO_ERRORS;
448         string tmp = ChangeExtension(file, ".log", true);
449         lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
450         ifstream ifs(tmp.c_str());
451
452         string token;
453         while (getline(ifs, token)) {
454                 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
455                 
456                 if (token.empty())
457                         continue;
458
459                 if (prefixIs(token, "LaTeX Warning:")) {
460                         // Here shall we handle different
461                         // types of warnings
462                         retval |= LATEX_WARNING;
463                         lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
464                         if (contains(token, "Rerun to get cross-references")) {
465                                 retval |= RERUN;
466                                 lyxerr[Debug::LATEX]
467                                         << "We should rerun." << endl;
468                         } else if (contains(token, "Citation")
469                                    && contains(token, "on page")
470                                    && contains(token, "undefined")) {
471                                 retval |= UNDEF_CIT;
472                         }
473                 } else if (prefixIs(token, "Package")) {
474                         // Package warnings
475                         retval |= PACKAGE_WARNING;
476                         if (contains(token, "natbib Warning:")) {
477                                 // Natbib warnings
478                                 if (contains(token, "Citation")
479                                     && contains(token, "on page")
480                                     && contains(token, "undefined")) {
481                                         retval |= UNDEF_CIT;
482                                 }
483                         } else if (contains(token, "Rerun LaTeX.")) {
484                                 // at least longtable.sty might use this.
485                                 retval |= RERUN;
486                         }
487                 } else if (prefixIs(token, "! ")) {
488                         // Ok, we have something that looks like a TeX Error
489                         // but what do we really have.
490
491                         // Just get the error description:
492                         string desc(token, 2);
493                         if (contains(token, "LaTeX Error:"))
494                                 retval |= LATEX_ERROR;
495                         // get the next line
496                         string tmp;
497                         getline(ifs, tmp);
498                         if (prefixIs(tmp, "l.")) {
499                                 // we have a latex error
500                                 retval |=  TEX_ERROR;
501                                 // get the line number:
502                                 int line = 0;
503                                 sscanf(tmp.c_str(), "l.%d", &line);
504                                 // get the rest of the message:
505                                 string errstr(tmp, tmp.find(' '));
506                                 errstr += '\n';
507                                 getline(ifs, tmp);
508                                 while (!contains(errstr, "l.")
509                                        && !tmp.empty()
510                                        && !prefixIs(tmp, "! ")
511                                        && !contains(tmp, "(job aborted")) {
512                                         errstr += tmp;
513                                         errstr += "\n";
514                                         getline(ifs, tmp);
515                                 }
516                                 lyxerr[Debug::LATEX]
517                                         << "line: " << line << '\n'
518                                         << "Desc: " << desc << '\n'
519                                         << "Text: " << errstr << endl;
520                                 terr.insertError(line, desc, errstr);
521                                 ++num_errors;
522                         }
523                 } else {
524                         // information messages, TeX warnings and other
525                         // warnings we have not caught earlier.
526                         if (prefixIs(token, "Overfull ")) {
527                                 retval |= TEX_WARNING;
528                         } else if (prefixIs(token, "Underfull ")) {
529                                 retval |= TEX_WARNING;
530                         } else if (contains(token, "Rerun to get citations")) {
531                                 // Natbib seems to use this.
532                                 retval |= RERUN;
533                         } else if (contains(token, "No pages of output")) {
534                                 // A dvi file was not created
535                                 retval |= NO_OUTPUT;
536                         } else if (contains(token, "That makes 100 errors")) {
537                                 // More than 100 errors were reprted
538                                 retval |= TOO_MANY_ERRORS;
539                         }
540                 }
541         }
542         lyxerr[Debug::LATEX] << "Log line: " << token << endl;
543         return retval;
544 }
545
546
547 void LaTeX::deplog(DepTable & head)
548 {
549         // This function reads the LaTeX log file end extracts all the external
550         // files used by the LaTeX run. The files are then entered into the
551         // dependency file.
552
553         string logfile = ChangeExtension(file, ".log", true);
554         
555         ifstream ifs(logfile.c_str());
556         while (ifs) {
557                 // Now we read chars until we find a '('
558                 char c = 0;
559                 while(ifs.get(c)) {
560                         if (c == '(') break;
561                 };
562                 if (!ifs) break;
563                 
564                 // We now have c == '(', we now read the the sequence of
565                 // chars until reaching EOL, ' ' or ')' and put that
566                 // into a string.
567                 string foundfile;
568                 while (ifs.get(c)) {
569                         if (c == '\n' || c == ' ' || c == ')')
570                                 break;
571                         foundfile += c;
572                 }
573                 lyxerr[Debug::LATEX] << "Found file: " 
574                                      << foundfile << endl;
575                 
576                 // Ok now we found a file.
577                 // Now we should make sure that
578                 // this is a file that we can
579                 // access through the normal
580                 // paths:
581                 // (1) foundfile is an
582                 //     absolute path and should
583                 //     be inserted.
584                 if (AbsolutePath(foundfile)) {
585                         lyxerr[Debug::LATEX] << "AbsolutePath file: " 
586                                              << foundfile << endl;
587                         // On inital insert we want to do the update at once
588                         // since this file can not be a file generated by
589                         // the latex run.
590                         head.insert(foundfile, true);
591                         continue;
592                 }
593
594                 // (2) foundfile is in the tmpdir
595                 //     insert it into head
596                 if (FileInfo(OnlyFilename(foundfile)).exist()) {
597                         if (suffixIs(foundfile, ".aux")) {
598                                 lyxerr[Debug::LATEX] << "We don't want "
599                                                      << OnlyFilename(foundfile)
600                                                      << " in the dep file"
601                                                      << endl;
602                         } else if (suffixIs(foundfile, ".tex")) {
603                                 // This is a tex file generated by LyX
604                                 // and latex is not likely to change this
605                                 // during its runs.
606                                 lyxerr[Debug::LATEX] << "Tmpdir TeX file: "
607                                                      << OnlyFilename(foundfile)
608                                                      << endl;
609                                 head.insert(foundfile, true);
610                         } else {
611                                 lyxerr[Debug::LATEX] << "In tmpdir file:"
612                                                      << OnlyFilename(foundfile)
613                                                      << endl;
614                                 head.insert(OnlyFilename(foundfile));
615                         }
616                         continue;
617                 }
618                 lyxerr[Debug::LATEX]
619                         << "Not a file or we are unable to find it."
620                         << endl;
621         }
622 }
623
624
625 void LaTeX::deptex(DepTable & head)
626 {
627         int except = AUX|LOG|DVI|BBL|IND|GLO; 
628         string tmp;
629         FileInfo fi;
630         for (int i = 0; i < file_count; ++i) {
631                 if (!(all_files[i].file & except)) {
632                         tmp = ChangeExtension(file,
633                                               all_files[i].extension,
634                                               true);
635                         lyxerr[Debug::LATEX] << "deptex: " << tmp << endl;
636                         if (fi.newFile(tmp).exist())
637                                 head.insert(tmp);
638                 }
639         }
640 }
641