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