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