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