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