]> git.lyx.org Git - lyx.git/blob - src/LaTeX.C
* src/LaTeX.C: whitespace
[lyx.git] / src / LaTeX.C
1 /**
2  * \file LaTeX.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Dekel Tsur
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "bufferlist.h"
18 #include "LaTeX.h"
19 #include "gettext.h"
20 #include "lyxrc.h"
21 #include "debug.h"
22 #include "DepTable.h"
23
24 #include "support/filetools.h"
25 #include "support/convert.h"
26 #include "support/lstrings.h"
27 #include "support/lyxlib.h"
28 #include "support/systemcall.h"
29 #include "support/os.h"
30
31 #include <boost/filesystem/operations.hpp>
32 #include <boost/regex.hpp>
33
34 #include <fstream>
35
36
37 namespace lyx {
38
39 using support::absolutePath;
40 using support::bformat;
41 using support::changeExtension;
42 using support::contains;
43 using support::FileName;
44 using support::findtexfile;
45 using support::getcwd;
46 using support::makeAbsPath;
47 using support::onlyFilename;
48 using support::prefixIs;
49 using support::quoteName;
50 using support::removeExtension;
51 using support::rtrim;
52 using support::rsplit;
53 using support::split;
54 using support::subst;
55 using support::suffixIs;
56 using support::Systemcall;
57 using support::unlink;
58 using support::trim;
59
60 namespace os = support::os;
61 namespace fs = boost::filesystem;
62
63 using boost::regex;
64 using boost::smatch;
65
66
67 #ifndef CXX_GLOBAL_CSTD
68 using std::sscanf;
69 #endif
70
71 using std::endl;
72 using std::getline;
73 using std::string;
74 using std::ifstream;
75 using std::set;
76 using std::vector;
77
78 // TODO: in no particular order
79 // - get rid of the call to
80 //   BufferList::updateIncludedTeXfiles, this should either
81 //   be done before calling LaTeX::funcs or in a completely
82 //   different way.
83 // - the makeindex style files should be taken care of with
84 //   the dependency mechanism.
85 // - makeindex commandline options should be supported
86 // - somewhere support viewing of bibtex and makeindex log files.
87 // - we should perhaps also scan the bibtex log file
88
89 namespace {
90
91 docstring runMessage(unsigned int count)
92 {
93         return bformat(_("Waiting for LaTeX run number %1$d"), count);
94 }
95
96 } // anon namespace
97
98 /*
99  * CLASS TEXERRORS
100  */
101
102 void TeXErrors::insertError(int line, docstring const & error_desc,
103                             docstring const & error_text)
104 {
105         Error newerr(line, error_desc, error_text);
106         errors.push_back(newerr);
107 }
108
109
110 bool operator==(Aux_Info const & a, Aux_Info const & o)
111 {
112         return a.aux_file == o.aux_file &&
113                 a.citations == o.citations &&
114                 a.databases == o.databases &&
115                 a.styles == o.styles;
116 }
117
118
119 bool operator!=(Aux_Info const & a, Aux_Info const & o)
120 {
121         return !(a == o);
122 }
123
124
125 /*
126  * CLASS LaTeX
127  */
128
129 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
130              FileName const & f)
131         : cmd(latex), file(f), runparams(rp)
132 {
133         num_errors = 0;
134         if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
135                 depfile = FileName(file.absFilename() + ".dep-pdf");
136                 output_file = FileName(changeExtension(file.absFilename(), ".pdf"));
137         } else {
138                 depfile = FileName(file.absFilename() + ".dep");
139                 output_file = FileName(changeExtension(file.absFilename(), ".dvi"));
140         }
141 }
142
143
144 void LaTeX::deleteFilesOnError() const
145 {
146         // currently just a dummy function.
147
148         // What files do we have to delete?
149
150         // This will at least make latex do all the runs
151         unlink(depfile);
152
153         // but the reason for the error might be in a generated file...
154
155         // bibtex file
156         FileName const bbl(changeExtension(file.absFilename(), ".bbl"));
157         unlink(bbl);
158
159         // makeindex file
160         FileName const ind(changeExtension(file.absFilename(), ".ind"));
161         unlink(ind);
162
163         // nomencl file
164         FileName const nls(changeExtension(file.absFilename(), ".nls"));
165         unlink(nls);
166
167         // Also remove the aux file
168         FileName const aux(changeExtension(file.absFilename(), ".aux"));
169         unlink(aux);
170 }
171
172
173 int LaTeX::run(TeXErrors & terr)
174         // We know that this function will only be run if the lyx buffer
175         // has been changed. We also know that a newly written .tex file
176         // is always different from the previous one because of the date
177         // in it. However it seems safe to run latex (at least) on time each
178         // time the .tex file changes.
179 {
180         int scanres = NO_ERRORS;
181         unsigned int count = 0; // number of times run
182         num_errors = 0; // just to make sure.
183         unsigned int const MAX_RUN = 6;
184         DepTable head; // empty head
185         bool rerun = false; // rerun requested
186
187         // The class LaTeX does not know the temp path.
188         theBufferList().updateIncludedTeXfiles(getcwd().absFilename(), runparams);
189
190         // Never write the depfile if an error was encountered.
191
192         // 0
193         // first check if the file dependencies exist:
194         //     ->If it does exist
195         //             check if any of the files mentioned in it have
196         //             changed (done using a checksum).
197         //                 -> if changed:
198         //                        run latex once and
199         //                        remake the dependency file
200         //                 -> if not changed:
201         //                        just return there is nothing to do for us.
202         //     ->if it doesn't exist
203         //             make it and
204         //             run latex once (we need to run latex once anyway) and
205         //             remake the dependency file.
206         //
207
208         bool had_depfile = fs::exists(depfile.toFilesystemEncoding());
209         bool run_bibtex = false;
210         FileName const aux_file(changeExtension(file.absFilename(), "aux"));
211
212         if (had_depfile) {
213                 lyxerr[Debug::DEPEND] << "Dependency file exists" << endl;
214                 // Read the dep file:
215                 had_depfile = head.read(depfile);
216         }
217
218         if (had_depfile) {
219                 // Update the checksums
220                 head.update();
221                 // Can't just check if anything has changed because it might have aborted
222                 // on error last time... in which cas we need to re-run latex
223                 // and collect the error messages (even if they are the same).
224                 if (!fs::exists(output_file.toFilesystemEncoding())) {
225                         lyxerr[Debug::DEPEND]
226                                 << "re-running LaTeX because output file doesn't exist." << endl;
227                 } else if (!head.sumchange()) {
228                         lyxerr[Debug::DEPEND] << "return no_change" << endl;
229                         return NO_CHANGE;
230                 } else {
231                         lyxerr[Debug::DEPEND]
232                                 << "Dependency file has changed" << endl;
233                 }
234
235                 if (head.extchanged(".bib") || head.extchanged(".bst"))
236                         run_bibtex = true;
237         } else
238                 lyxerr[Debug::DEPEND]
239                         << "Dependency file does not exist, or has wrong format" << endl;
240
241         /// We scan the aux file even when had_depfile = false,
242         /// because we can run pdflatex on the file after running latex on it,
243         /// in which case we will not need to run bibtex again.
244         vector<Aux_Info> bibtex_info_old;
245         if (!run_bibtex)
246                 bibtex_info_old = scanAuxFiles(aux_file);
247
248         ++count;
249         lyxerr[Debug::LATEX] << "Run #" << count << endl;
250         message(runMessage(count));
251
252         startscript();
253         scanres = scanLogFile(terr);
254         if (scanres & ERROR_RERUN) {
255                 lyxerr[Debug::LATEX] << "Rerunning LaTeX" << endl;
256                 startscript();
257                 scanres = scanLogFile(terr);
258         }
259
260         if (scanres & ERRORS) {
261                 deleteFilesOnError();
262                 return scanres; // return on error
263         }
264
265         vector<Aux_Info> const bibtex_info = scanAuxFiles(aux_file);
266         if (!run_bibtex && bibtex_info_old != bibtex_info)
267                 run_bibtex = true;
268
269         // update the dependencies.
270         deplog(head); // reads the latex log
271         head.update();
272
273         // 0.5
274         // At this point we must run external programs if needed.
275         // makeindex will be run if a .idx file changed or was generated.
276         // And if there were undefined citations or changes in references
277         // the .aux file is checked for signs of bibtex. Bibtex is then run
278         // if needed.
279
280         // memoir (at least) writes an empty *idx file in the first place.
281         // A second latex run is needed.
282         FileName const idxfile(changeExtension(file.absFilename(), ".idx"));
283         rerun = fs::exists(idxfile.toFilesystemEncoding()) &&
284                 fs::is_empty(idxfile.toFilesystemEncoding());
285
286         // run makeindex
287         if (head.haschanged(idxfile)) {
288                 // no checks for now
289                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
290                 message(_("Running MakeIndex."));
291                 // onlyFilename() is needed for cygwin
292                 rerun |= runMakeIndex(onlyFilename(idxfile.absFilename()), runparams);
293         }
294         if (head.haschanged(FileName(changeExtension(file.absFilename(), ".nlo")))) {
295                 lyxerr[Debug::LATEX] << "Running MakeIndex for nomencl." << endl;
296                 message(_("Running MakeIndex for nomencl."));
297                 // onlyFilename() is needed for cygwin
298                 string const nomenclstr = " -s nomencl.ist -o " + onlyFilename(changeExtension(file.toFilesystemEncoding(), ".nls"));
299                 rerun |= runMakeIndex(onlyFilename(changeExtension(file.absFilename(), ".nlo")), runparams, nomenclstr);
300         }
301
302         // run bibtex
303         // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
304         if (scanres & UNDEF_CIT || run_bibtex) {
305                 // Here we must scan the .aux file and look for
306                 // "\bibdata" and/or "\bibstyle". If one of those
307                 // tags is found -> run bibtex and set rerun = true;
308                 // no checks for now
309                 lyxerr[Debug::LATEX] << "Running BibTeX." << endl;
310                 message(_("Running BibTeX."));
311                 updateBibtexDependencies(head, bibtex_info);
312                 rerun |= runBibTeX(bibtex_info);
313         } else if (!had_depfile) {
314                 /// If we run pdflatex on the file after running latex on it,
315                 /// then we do not need to run bibtex, but we do need to
316                 /// insert the .bib and .bst files into the .dep-pdf file.
317                 updateBibtexDependencies(head, bibtex_info);
318         }
319
320         // 1
321         // we know on this point that latex has been run once (or we just
322         // returned) and the question now is to decide if we need to run
323         // it any more. This is done by asking if any of the files in the
324         // dependency file has changed. (remember that the checksum for
325         // a given file is reported to have changed if it just was created)
326         //     -> if changed or rerun == true:
327         //             run latex once more and
328         //             update the dependency structure
329         //     -> if not changed:
330         //             we does nothing at this point
331         //
332         if (rerun || head.sumchange()) {
333                 rerun = false;
334                 ++count;
335                 lyxerr[Debug::DEPEND]
336                         << "Dep. file has changed or rerun requested" << endl;
337                 lyxerr[Debug::LATEX]
338                         << "Run #" << count << endl;
339                 message(runMessage(count));
340                 startscript();
341                 scanres = scanLogFile(terr);
342                 if (scanres & ERRORS) {
343                         deleteFilesOnError();
344                         return scanres; // return on error
345                 }
346
347                 // update the depedencies
348                 deplog(head); // reads the latex log
349                 head.update();
350         } else {
351                 lyxerr[Debug::DEPEND] << "Dep. file has NOT changed" << endl;
352         }
353
354         // 1.5
355         // The inclusion of files generated by external programs like
356         // makeindex or bibtex might have done changes to pagenumbering,
357         // etc. And because of this we must run the external programs
358         // again to make sure everything is redone correctly.
359         // Also there should be no need to run the external programs any
360         // more after this.
361
362         // run makeindex if the <file>.idx has changed or was generated.
363         if (head.haschanged(FileName(changeExtension(file.absFilename(), ".idx")))) {
364                 // no checks for now
365                 lyxerr[Debug::LATEX] << "Running MakeIndex." << endl;
366                 message(_("Running MakeIndex."));
367                 // onlyFilename() is needed for cygwin
368                 rerun = runMakeIndex(onlyFilename(changeExtension(file.absFilename(), ".idx")), runparams);
369         }
370
371         // I am not pretty sure if need this twice. 
372         if (head.haschanged(FileName(changeExtension(file.absFilename(), ".nlo")))) {
373                 lyxerr[Debug::LATEX] << "Running MakeIndex for nomencl." << endl;
374                 message(_("Running MakeIndex for nomencl."));
375                 // onlyFilename() is needed for cygwin
376                 string nomenclstr = " -s nomencl.ist -o " + onlyFilename(changeExtension(file.toFilesystemEncoding(), ".nls"));
377                 rerun |= runMakeIndex(onlyFilename(changeExtension(file.absFilename(), ".nlo")), runparams, nomenclstr);
378         }
379
380         // 2
381         // we will only run latex more if the log file asks for it.
382         // or if the sumchange() is true.
383         //     -> rerun asked for:
384         //             run latex and
385         //             remake the dependency file
386         //             goto 2 or return if max runs are reached.
387         //     -> rerun not asked for:
388         //             just return (fall out of bottom of func)
389         //
390         while ((head.sumchange() || rerun || (scanres & RERUN))
391                && count < MAX_RUN) {
392                 // Yes rerun until message goes away, or until
393                 // MAX_RUNS are reached.
394                 rerun = false;
395                 ++count;
396                 lyxerr[Debug::LATEX] << "Run #" << count << endl;
397                 message(runMessage(count));
398                 startscript();
399                 scanres = scanLogFile(terr);
400                 if (scanres & ERRORS) {
401                         deleteFilesOnError();
402                         return scanres; // return on error
403                 }
404
405                 // keep this updated
406                 head.update();
407         }
408
409         // Write the dependencies to file.
410         head.write(depfile);
411         lyxerr[Debug::LATEX] << "Done." << endl;
412         return scanres;
413 }
414
415
416 int LaTeX::startscript()
417 {
418         // onlyFilename() is needed for cygwin
419         string tmp = cmd + ' ' + quoteName(onlyFilename(file.toFilesystemEncoding())) + " > " + os::nulldev();
420         Systemcall one;
421         return one.startscript(Systemcall::Wait, tmp);
422 }
423
424
425 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
426                          string const & params)
427 {
428         lyxerr[Debug::LATEX]
429                 << "idx file has been made, running makeindex on file "
430                 << f << endl;
431         string tmp = lyxrc.index_command + ' ';
432         
433         tmp = subst(tmp, "$$lang", runparams.document_language);
434         tmp += quoteName(f);
435         tmp += params;
436         Systemcall one;
437         one.startscript(Systemcall::Wait, tmp);
438         return true;
439 }
440
441
442 vector<Aux_Info> const
443 LaTeX::scanAuxFiles(FileName const & file)
444 {
445         vector<Aux_Info> result;
446
447         result.push_back(scanAuxFile(file));
448
449         string const basename = removeExtension(file.absFilename());
450         for (int i = 1; i < 1000; ++i) {
451                 FileName const file2(basename
452                         + '.' + convert<string>(i)
453                         + ".aux");
454                 if (!fs::exists(file2.toFilesystemEncoding()))
455                         break;
456                 result.push_back(scanAuxFile(file2));
457         }
458         return result;
459 }
460
461
462 Aux_Info const LaTeX::scanAuxFile(FileName const & file)
463 {
464         Aux_Info result;
465         result.aux_file = file;
466         scanAuxFile(file, result);
467         return result;
468 }
469
470
471 void LaTeX::scanAuxFile(FileName const & file, Aux_Info & aux_info)
472 {
473         lyxerr[Debug::LATEX] << "Scanning aux file: " << file << endl;
474
475         ifstream ifs(file.toFilesystemEncoding().c_str());
476         string token;
477         static regex const reg1("\\\\citation\\{([^}]+)\\}");
478         static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
479         static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
480         static regex const reg4("\\\\@input\\{([^}]+)\\}");
481
482         while (getline(ifs, token)) {
483                 token = rtrim(token, "\r");
484                 smatch sub;
485                 // FIXME UNICODE: We assume that citation keys and filenames
486                 // in the aux file are in the file system encoding.
487                 token = to_utf8(from_filesystem8bit(token));
488                 if (regex_match(token, sub, reg1)) {
489                         string data = sub.str(1);
490                         while (!data.empty()) {
491                                 string citation;
492                                 data = split(data, citation, ',');
493                                 lyxerr[Debug::LATEX] << "Citation: "
494                                                      << citation << endl;
495                                 aux_info.citations.insert(citation);
496                         }
497                 } else if (regex_match(token, sub, reg2)) {
498                         string data = sub.str(1);
499                         // data is now all the bib files separated by ','
500                         // get them one by one and pass them to the helper
501                         while (!data.empty()) {
502                                 string database;
503                                 data = split(data, database, ',');
504                                 database = changeExtension(database, "bib");
505                                 lyxerr[Debug::LATEX] << "BibTeX database: `"
506                                                      << database << '\'' << endl;
507                                 aux_info.databases.insert(database);
508                         }
509                 } else if (regex_match(token, sub, reg3)) {
510                         string style = sub.str(1);
511                         // token is now the style file
512                         // pass it to the helper
513                         style = changeExtension(style, "bst");
514                         lyxerr[Debug::LATEX] << "BibTeX style: `"
515                                              << style << '\'' << endl;
516                         aux_info.styles.insert(style);
517                 } else if (regex_match(token, sub, reg4)) {
518                         string const file2 = sub.str(1);
519                         scanAuxFile(makeAbsPath(file2), aux_info);
520                 }
521         }
522 }
523
524
525 void LaTeX::updateBibtexDependencies(DepTable & dep,
526                                      vector<Aux_Info> const & bibtex_info)
527 {
528         // Since a run of Bibtex mandates more latex runs it is ok to
529         // remove all ".bib" and ".bst" files.
530         dep.remove_files_with_extension(".bib");
531         dep.remove_files_with_extension(".bst");
532         //string aux = OnlyFilename(ChangeExtension(file, ".aux"));
533
534         for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
535              it != bibtex_info.end(); ++it) {
536                 for (set<string>::const_iterator it2 = it->databases.begin();
537                      it2 != it->databases.end(); ++it2) {
538                         FileName const file = findtexfile(*it2, "bib");
539                         if (!file.empty())
540                                 dep.insert(file, true);
541                 }
542
543                 for (set<string>::const_iterator it2 = it->styles.begin();
544                      it2 != it->styles.end(); ++it2) {
545                         FileName const file = findtexfile(*it2, "bst");
546                         if (!file.empty())
547                                 dep.insert(file, true);
548                 }
549         }
550 }
551
552
553 bool LaTeX::runBibTeX(vector<Aux_Info> const & bibtex_info)
554 {
555         bool result = false;
556         for (vector<Aux_Info>::const_iterator it = bibtex_info.begin();
557              it != bibtex_info.end(); ++it) {
558                 if (it->databases.empty())
559                         continue;
560                 result = true;
561
562                 string tmp = lyxrc.bibtex_command + " ";
563                 // onlyFilename() is needed for cygwin
564                 tmp += quoteName(onlyFilename(removeExtension(it->aux_file.absFilename())));
565                 Systemcall one;
566                 one.startscript(Systemcall::Wait, tmp);
567         }
568         // Return whether bibtex was run
569         return result;
570 }
571
572
573 int LaTeX::scanLogFile(TeXErrors & terr)
574 {
575         int last_line = -1;
576         int line_count = 1;
577         int retval = NO_ERRORS;
578         string tmp = onlyFilename(changeExtension(file.absFilename(), ".log"));
579         lyxerr[Debug::LATEX] << "Log file: " << tmp << endl;
580         FileName const fn = FileName(makeAbsPath(tmp));
581         ifstream ifs(fn.toFilesystemEncoding().c_str());
582
583         string token;
584         while (getline(ifs, token)) {
585                 // MikTeX sometimes inserts \0 in the log file. They can't be
586                 // removed directly with the existing string utility
587                 // functions, so convert them first to \r, and remove all
588                 // \r's afterwards, since we need to remove them anyway.
589                 token = subst(token, '\0', '\r');
590                 token = subst(token, "\r", "");
591
592                 lyxerr[Debug::LATEX] << "Log line: " << token << endl;
593
594                 if (token.empty())
595                         continue;
596
597                 if (prefixIs(token, "LaTeX Warning:") ||
598                     prefixIs(token, "! pdfTeX warning")) {
599                         // Here shall we handle different
600                         // types of warnings
601                         retval |= LATEX_WARNING;
602                         lyxerr[Debug::LATEX] << "LaTeX Warning." << endl;
603                         if (contains(token, "Rerun to get cross-references")) {
604                                 retval |= RERUN;
605                                 lyxerr[Debug::LATEX]
606                                         << "We should rerun." << endl;
607                         } else if (contains(token, "Citation")
608                                    && contains(token, "on page")
609                                    && contains(token, "undefined")) {
610                                 retval |= UNDEF_CIT;
611                         }
612                 } else if (prefixIs(token, "Package")) {
613                         // Package warnings
614                         retval |= PACKAGE_WARNING;
615                         if (contains(token, "natbib Warning:")) {
616                                 // Natbib warnings
617                                 if (contains(token, "Citation")
618                                     && contains(token, "on page")
619                                     && contains(token, "undefined")) {
620                                         retval |= UNDEF_CIT;
621                                 }
622                         } else if (contains(token, "run BibTeX")) {
623                                 retval |= UNDEF_CIT;
624                         } else if (contains(token, "Rerun LaTeX") ||
625                                    contains(token, "Rerun to get")) {
626                                 // at least longtable.sty and bibtopic.sty
627                                 // might use this.
628                                 lyxerr[Debug::LATEX]
629                                         << "We should rerun." << endl;
630                                 retval |= RERUN;
631                         }
632                 } else if (token[0] == '(') {
633                         if (contains(token, "Rerun LaTeX") ||
634                             contains(token, "Rerun to get")) {
635                                 // Used by natbib
636                                 lyxerr[Debug::LATEX]
637                                         << "We should rerun." << endl;
638                                 retval |= RERUN;
639                         }
640                 } else if (prefixIs(token, "! ")) {
641                         // Ok, we have something that looks like a TeX Error
642                         // but what do we really have.
643
644                         // Just get the error description:
645                         string desc(token, 2);
646                         if (contains(token, "LaTeX Error:"))
647                                 retval |= LATEX_ERROR;
648                         // get the next line
649                         string tmp;
650                         int count = 0;
651                         do {
652                                 if (!getline(ifs, tmp))
653                                         break;
654                                 if (++count > 10)
655                                         break;
656                         } while (!prefixIs(tmp, "l."));
657                         if (prefixIs(tmp, "l.")) {
658                                 // we have a latex error
659                                 retval |=  TEX_ERROR;
660                                 if (contains(desc, "Package babel Error: You haven't defined the language"))
661                                         retval |= ERROR_RERUN;
662                                 // get the line number:
663                                 int line = 0;
664                                 sscanf(tmp.c_str(), "l.%d", &line);
665                                 // get the rest of the message:
666                                 string errstr(tmp, tmp.find(' '));
667                                 errstr += '\n';
668                                 getline(ifs, tmp);
669                                 while (!contains(errstr, "l.")
670                                        && !tmp.empty()
671                                        && !prefixIs(tmp, "! ")
672                                        && !contains(tmp, "(job aborted")) {
673                                         errstr += tmp;
674                                         errstr += "\n";
675                                         getline(ifs, tmp);
676                                 }
677                                 lyxerr[Debug::LATEX]
678                                         << "line: " << line << '\n'
679                                         << "Desc: " << desc << '\n'
680                                         << "Text: " << errstr << endl;
681                                 if (line == last_line)
682                                         ++line_count;
683                                 else {
684                                         line_count = 1;
685                                         last_line = line;
686                                 }
687                                 if (line_count <= 5) {
688                                         // FIXME UNICODE
689                                         // We have no idea what the encoding of
690                                         // the log file is.
691                                         // It seems that the output from the
692                                         // latex compiler itself is pure ASCII,
693                                         // but it can include bits from the
694                                         // document, so whatever encoding we
695                                         // assume here it can be wrong.
696                                         terr.insertError(line, from_local8bit(desc), from_local8bit(errstr));
697                                         ++num_errors;
698                                 }
699                         }
700                 } else {
701                         // information messages, TeX warnings and other
702                         // warnings we have not caught earlier.
703                         if (prefixIs(token, "Overfull ")) {
704                                 retval |= TEX_WARNING;
705                         } else if (prefixIs(token, "Underfull ")) {
706                                 retval |= TEX_WARNING;
707                         } else if (contains(token, "Rerun to get citations")) {
708                                 // Natbib seems to use this.
709                                 retval |= UNDEF_CIT;
710                         } else if (contains(token, "No pages of output")) {
711                                 // A dvi file was not created
712                                 retval |= NO_OUTPUT;
713                         } else if (contains(token, "That makes 100 errors")) {
714                                 // More than 100 errors were reprted
715                                 retval |= TOO_MANY_ERRORS;
716                         }
717                 }
718         }
719         lyxerr[Debug::LATEX] << "Log line: " << token << endl;
720         return retval;
721 }
722
723
724 namespace {
725
726 bool handleFoundFile(string const & ff, DepTable & head)
727 {
728         // convert from native os path to unix path
729         string foundfile = os::internal_path(trim(ff));
730
731         lyxerr[Debug::DEPEND] << "Found file: " << foundfile << endl;
732
733         // Ok now we found a file.
734         // Now we should make sure that this is a file that we can
735         // access through the normal paths.
736         // We will not try any fancy search methods to
737         // find the file.
738
739         // (1) foundfile is an
740         //     absolute path and should
741         //     be inserted.
742         if (absolutePath(foundfile)) {
743                 lyxerr[Debug::DEPEND] << "AbsolutePath file: "
744                                       << foundfile << endl;
745                 // On initial insert we want to do the update at once
746                 // since this file cannot be a file generated by
747                 // the latex run.
748                 FileName absname(foundfile);
749                 if (fs::exists(absname.toFilesystemEncoding()) &&
750                     !fs::is_directory(absname.toFilesystemEncoding())) {
751                                 head.insert(absname, true);
752                                 return true;
753                 } else {
754                         // check for spaces
755                         string strippedfile = foundfile;
756                         while (contains(strippedfile, " ")) {
757                                 // strip off part after last space and try again
758                                 string tmp = strippedfile;
759                                 string const stripoff =
760                                         rsplit(tmp, strippedfile, ' ');
761                                 absname.set(strippedfile);
762                                 if (fs::exists(absname.toFilesystemEncoding()) &&
763                                     !fs::is_directory(absname.toFilesystemEncoding())) {
764                                         head.insert(absname, true);
765                                         return true;
766                                 }
767                         }
768                 }
769         }
770
771         string onlyfile = onlyFilename(foundfile);
772         FileName absname(makeAbsPath(onlyfile));
773
774         // check for spaces
775         while (contains(foundfile, " ")) {
776                 if (fs::exists(absname.toFilesystemEncoding()))
777                         // everything o.k.
778                         break;
779                 else {
780                         // strip off part after last space and try again
781                         string strippedfile;
782                         string const stripoff = rsplit(foundfile, strippedfile, ' ');
783                         foundfile = strippedfile;
784                         onlyfile = onlyFilename(strippedfile);
785                         absname = makeAbsPath(onlyfile);
786                 }
787         }
788
789         // (2) foundfile is in the tmpdir
790         //     insert it into head
791         if (fs::exists(absname.toFilesystemEncoding()) &&
792             !fs::is_directory(absname.toFilesystemEncoding())) {
793                 static regex unwanted("^.*\\.(aux|log|dvi|bbl|ind|glo)$");
794                 if (regex_match(onlyfile, unwanted)) {
795                         lyxerr[Debug::DEPEND]
796                                 << "We don't want "
797                                 << onlyfile
798                                 << " in the dep file"
799                                 << endl;
800                 } else if (suffixIs(onlyfile, ".tex")) {
801                         // This is a tex file generated by LyX
802                         // and latex is not likely to change this
803                         // during its runs.
804                         lyxerr[Debug::DEPEND]
805                                 << "Tmpdir TeX file: "
806                                 << onlyfile
807                                 << endl;
808                         head.insert(absname, true);
809                 } else {
810                         lyxerr[Debug::DEPEND]
811                                 << "In tmpdir file:"
812                                 << onlyfile
813                                 << endl;
814                         head.insert(absname);
815                 }
816                 return true;
817         } else {
818                 lyxerr[Debug::DEPEND]
819                         << "Not a file or we are unable to find it."
820                         << endl;
821                 return false;
822         }
823 }
824
825
826 bool checkLineBreak(string const & ff, DepTable & head)
827 {
828         if (contains(ff, '.'))
829                 // if we have a dot, we let handleFoundFile decide
830                 return handleFoundFile(ff, head);
831         else
832                 // else, we suspect a line break
833                 return false;
834 }
835
836 } // anon namespace
837
838
839 void LaTeX::deplog(DepTable & head)
840 {
841         // This function reads the LaTeX log file end extracts all the external
842         // files used by the LaTeX run. The files are then entered into the
843         // dependency file.
844
845         string const logfile = onlyFilename(changeExtension(file.absFilename(), ".log"));
846
847         static regex reg1("File: (.+).*");
848         static regex reg2("No file (.+)(.).*");
849         static regex reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
850         // If an index should be created, MikTex does not write a line like
851         //    \openout# = 'sample.idx'.
852         // but instead only a line like this into the log:
853         //   Writing index file sample.idx
854         static regex reg4("Writing index file (.+).*");
855         // files also can be enclosed in <...>
856         static regex reg5("<([^>]+)(.).*");
857         static regex regnomencl("Writing nomenclature file (.+).*");
858         // If a toc should be created, MikTex does not write a line like
859         //    \openout# = `sample.toc'.
860         // but only a line like this into the log:
861         //    \tf@toc=\write#
862         // This line is also written by tetex.
863         // This line is not present if no toc should be created.
864         static regex miktexTocReg("\\\\tf@toc=\\\\write.*");
865         static regex reg6(".*\\([^)]+.*");
866
867         FileName const fn(makeAbsPath(logfile));
868         ifstream ifs(fn.toFilesystemEncoding().c_str());
869         string lastline;
870         while (ifs) {
871                 // Ok, the scanning of files here is not sufficient.
872                 // Sometimes files are named by "File: xxx" only
873                 // So I think we should use some regexps to find files instead.
874                 // Note: all file names and paths might contains spaces.
875
876                 bool found_file = false;
877                 string token;
878                 getline(ifs, token);
879                 // MikTeX sometimes inserts \0 in the log file. They can't be
880                 // removed directly with the existing string utility
881                 // functions, so convert them first to \r, and remove all
882                 // \r's afterwards, since we need to remove them anyway.
883                 token = subst(token, '\0', '\r');
884                 token = subst(token, "\r", "");
885                 if (token.empty() || token == ")") {
886                         lastline = string();
887                         continue;
888                 }
889
890                 // Sometimes, filenames are broken across lines.
891                 // We care for that and save suspicious lines.
892                 // Here we exclude some cases where we are sure 
893                 // that there is no continued filename
894                 if (!lastline.empty()) {
895                         static regex package_info("Package \\w+ Info: .*");
896                         static regex package_warning("Package \\w+ Warning: .*");
897                         if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
898                         || prefixIs(token, "Package:")
899                         || prefixIs(token, "Language:")
900                         || prefixIs(token, "LaTeX Info:")
901                         || prefixIs(token, "LaTeX Font Info:")
902                         || prefixIs(token, "\\openout[")
903                         || prefixIs(token, "))")
904                         || regex_match(token, package_info)
905                         || regex_match(token, package_warning))
906                                 lastline = string();
907                 }
908
909                 if (!lastline.empty())
910                         // probably a continued filename from last line
911                         token = lastline + token;
912                 if (token.length() > 255) {
913                         // string too long. Cut off.
914                         int r = token.length() - 250;
915                         string ntoken = token.substr(r, token.length());
916                         token = ntoken;
917                 }
918
919                 smatch sub;
920
921                 // FIXME UNICODE: We assume that the file names in the log
922                 // file are in the file system encoding.
923                 token = to_utf8(from_filesystem8bit(token));
924
925                 // (1) "File: file.ext"
926                 if (regex_match(token, sub, reg1)) {
927                         // check for dot
928                         found_file = checkLineBreak(sub.str(1), head);
929                         // However, ...
930                         if (suffixIs(token, ")"))
931                                 // no line break for sure
932                                 // pretend we've been succesfully searching
933                                 found_file = true;
934                 // (2) "No file file.ext"
935                 } else if (regex_match(token, sub, reg2)) {
936                         // file names must contains a dot, line ends with dot
937                         if (contains(sub.str(1), '.') && sub.str(2) == ".")
938                                 found_file = handleFoundFile(sub.str(1), head);
939                         else
940                                 // we suspect a line break
941                                 found_file = false;
942                 // (3) "\openout<nr> = `file.ext'."
943                 } else if (regex_match(token, sub, reg3)) {
944                         // search for closing '. at the end of the line
945                         if (sub.str(2) == "\'.")
946                                 found_file = handleFoundFile(sub.str(1), head);
947                         else
948                                 // probable line break
949                                 found_file = false;
950                 // (4) "Writing index file file.ext"
951                 } else if (regex_match(token, sub, reg4))
952                         // check for dot
953                         found_file = checkLineBreak(sub.str(1), head);
954                 // (5) "<file.ext>"
955                 else if (regex_match(token, sub, reg5)) {
956                         // search for closing '>' and dot ('*.*>') at the eol
957                         if (contains(sub.str(1), '.') && sub.str(2) == ">")
958                                 found_file = handleFoundFile(sub.str(1), head);
959                         else
960                                 // probable line break
961                                 found_file = false;
962                 // (6) "Writing nomenclature file file.ext"
963                 } else if (regex_match(token, sub, regnomencl))
964                         // check for dot
965                         found_file = checkLineBreak(sub.str(1), head);
966                 // (7) "\tf@toc=\write<nr>" (for MikTeX)
967                 else if (regex_match(token, sub, miktexTocReg))
968                         found_file = handleFoundFile(onlyFilename(changeExtension(
969                                                 file.absFilename(), ".toc")), head);
970                 else
971                         // not found, but we won't check further
972                         // pretend we've been succesfully searching
973                         found_file = true;
974
975                 // (8) "(file.ext"
976                 // note that we can have several of these on one line
977                 // this must be queried separated, because of
978                 // cases such as "File: file.ext (type eps)"
979                 // where "File: file.ext" would be skipped
980                 if (regex_match(token, sub, reg6)) {
981                         // search for strings in (...)
982                         static regex reg6_1("\\(([^()]+)(.).*");
983                         smatch what;
984                         string::const_iterator first = token.begin();
985                         string::const_iterator end = token.end();
986
987                         while (regex_search(first, end, what, reg6_1)) {
988                                 // if we have a dot, try to handle as file
989                                 if (contains(what.str(1), '.')) {
990                                         first = what[0].second;
991                                         if (what.str(2) == ")") {
992                                                 handleFoundFile(what.str(1), head);
993                                                 // since we had a closing bracket,
994                                                 // do not investigate further
995                                                 found_file = true;
996                                         } else
997                                                 // if we have no closing bracket,
998                                                 // try to handle as file nevertheless
999                                                 found_file = handleFoundFile(
1000                                                         what.str(1) + what.str(2), head);
1001                                 }
1002                                 // if we do not have a dot, check if the line has
1003                                 // a closing bracket (else, we suspect a line break)
1004                                 else if (what.str(2) != ")") {
1005                                         first = what[0].second;
1006                                         found_file = false;
1007                                 } else {
1008                                         // we have a closing bracket, so the content
1009                                         // is not a file name.
1010                                         // no need to investigate further
1011                                         // pretend we've been succesfully searching
1012                                         first = what[0].second;
1013                                         found_file = true;
1014                                 }
1015                         }
1016                 }
1017
1018                 if (!found_file)
1019                         // probable linebreak:
1020                         // save this line
1021                         lastline = token;
1022                 else
1023                         // no linebreak: reset
1024                         lastline = string();
1025         }
1026
1027         // Make sure that the main .tex file is in the dependency file.
1028         head.insert(file, true);
1029 }
1030
1031
1032 } // namespace lyx