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