]> git.lyx.org Git - lyx.git/blob - src/LaTeX.cpp
#5502 add binding for full screen toggle on mac
[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 #include <stack>
36
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42
43 namespace os = support::os;
44
45 // TODO: in no particular order
46 // - get rid of the call to
47 //   BufferList::updateIncludedTeXfiles, this should either
48 //   be done before calling LaTeX::funcs or in a completely
49 //   different way.
50 // - the makeindex style files should be taken care of with
51 //   the dependency mechanism.
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                             string const & child_name)
69 {
70         Error newerr(line, error_desc, error_text, child_name);
71         errors.push_back(newerr);
72 }
73
74
75 bool operator==(AuxInfo const & a, AuxInfo const & o)
76 {
77         return a.aux_file == o.aux_file
78                 && a.citations == o.citations
79                 && a.databases == o.databases
80                 && a.styles == o.styles;
81 }
82
83
84 bool operator!=(AuxInfo const & a, AuxInfo const & o)
85 {
86         return !(a == o);
87 }
88
89
90 /*
91  * CLASS LaTeX
92  */
93
94 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
95              FileName const & f, string const & p, bool const clean_start)
96         : cmd(latex), file(f), path(p), runparams(rp), biber(false)
97 {
98         num_errors = 0;
99         if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
100                 depfile = FileName(file.absFileName() + ".dep-pdf");
101                 output_file =
102                         FileName(changeExtension(file.absFileName(), ".pdf"));
103         } else {
104                 depfile = FileName(file.absFileName() + ".dep");
105                 output_file =
106                         FileName(changeExtension(file.absFileName(), ".dvi"));
107         }
108         if (clean_start)
109                 removeAuxiliaryFiles();
110 }
111
112
113 void LaTeX::removeAuxiliaryFiles() const
114 {
115         // Note that we do not always call this function when there is an error.
116         // For example, if there is an error but an output file is produced we
117         // still would like to output (export/view) the file.
118
119         // What files do we have to delete?
120
121         // This will at least make latex do all the runs
122         depfile.removeFile();
123
124         // but the reason for the error might be in a generated file...
125
126         // bibtex file
127         FileName const bbl(changeExtension(file.absFileName(), ".bbl"));
128         bbl.removeFile();
129
130         // biber file
131         FileName const bcf(changeExtension(file.absFileName(), ".bcf"));
132         bcf.removeFile();
133
134         // makeindex file
135         FileName const ind(changeExtension(file.absFileName(), ".ind"));
136         ind.removeFile();
137
138         // nomencl file
139         FileName const nls(changeExtension(file.absFileName(), ".nls"));
140         nls.removeFile();
141
142         // nomencl file (old version of the package)
143         FileName const gls(changeExtension(file.absFileName(), ".gls"));
144         gls.removeFile();
145
146         // Also remove the aux file
147         FileName const aux(changeExtension(file.absFileName(), ".aux"));
148         aux.removeFile();
149
150         // Remove the output file, which is often generated even if error
151         output_file.removeFile();
152 }
153
154
155 int LaTeX::run(TeXErrors & terr)
156         // We know that this function will only be run if the lyx buffer
157         // has been changed. We also know that a newly written .tex file
158         // is always different from the previous one because of the date
159         // in it. However it seems safe to run latex (at least) one time
160         // each time the .tex file changes.
161 {
162         int scanres = NO_ERRORS;
163         int bscanres = NO_ERRORS;
164         unsigned int count = 0; // number of times run
165         num_errors = 0; // just to make sure.
166         unsigned int const MAX_RUN = 6;
167         DepTable head; // empty head
168         bool rerun = false; // rerun requested
169
170         // The class LaTeX does not know the temp path.
171         theBufferList().updateIncludedTeXfiles(FileName::getcwd().absFileName(),
172                 runparams);
173
174         // 0
175         // first check if the file dependencies exist:
176         //     ->If it does exist
177         //             check if any of the files mentioned in it have
178         //             changed (done using a checksum).
179         //                 -> if changed:
180         //                        run latex once and
181         //                        remake the dependency file
182         //                 -> if not changed:
183         //                        just return there is nothing to do for us.
184         //     ->if it doesn't exist
185         //             make it and
186         //             run latex once (we need to run latex once anyway) and
187         //             remake the dependency file.
188         //
189
190         bool had_depfile = depfile.exists();
191         bool run_bibtex = false;
192         FileName const aux_file(changeExtension(file.absFileName(), ".aux"));
193
194         if (had_depfile) {
195                 LYXERR(Debug::DEPEND, "Dependency file exists");
196                 // Read the dep file:
197                 had_depfile = head.read(depfile);
198         }
199
200         if (had_depfile) {
201                 // Update the checksums
202                 head.update();
203                 // Can't just check if anything has changed because it might
204                 // have aborted on error last time... in which cas we need
205                 // to re-run latex and collect the error messages
206                 // (even if they are the same).
207                 if (!output_file.exists()) {
208                         LYXERR(Debug::DEPEND,
209                                 "re-running LaTeX because output file doesn't exist.");
210                 } else if (!head.sumchange()) {
211                         LYXERR(Debug::DEPEND, "return no_change");
212                         return NO_CHANGE;
213                 } else {
214                         LYXERR(Debug::DEPEND, "Dependency file has changed");
215                 }
216
217                 if (head.extchanged(".bib") || head.extchanged(".bst"))
218                         run_bibtex = true;
219         } else
220                 LYXERR(Debug::DEPEND,
221                         "Dependency file does not exist, or has wrong format");
222
223         /// We scan the aux file even when had_depfile = false,
224         /// because we can run pdflatex on the file after running latex on it,
225         /// in which case we will not need to run bibtex again.
226         vector<AuxInfo> bibtex_info_old;
227         if (!run_bibtex)
228                 bibtex_info_old = scanAuxFiles(aux_file);
229
230         ++count;
231         LYXERR(Debug::LATEX, "Run #" << count);
232         message(runMessage(count));
233
234         int const exit_code = startscript();
235
236         scanres = scanLogFile(terr);
237         if (scanres & ERROR_RERUN) {
238                 LYXERR(Debug::LATEX, "Rerunning LaTeX");
239                 startscript();
240                 scanres = scanLogFile(terr);
241         }
242
243         vector<AuxInfo> const bibtex_info = scanAuxFiles(aux_file);
244         if (!run_bibtex && bibtex_info_old != bibtex_info)
245                 run_bibtex = true;
246
247         // update the dependencies.
248         deplog(head); // reads the latex log
249         head.update();
250
251         // 1
252         // At this point we must run external programs if needed.
253         // makeindex will be run if a .idx file changed or was generated.
254         // And if there were undefined citations or changes in references
255         // the .aux file is checked for signs of bibtex. Bibtex is then run
256         // if needed.
257
258         // memoir (at least) writes an empty *idx file in the first place.
259         // A second latex run is needed.
260         FileName const idxfile(changeExtension(file.absFileName(), ".idx"));
261         rerun = idxfile.exists() && idxfile.isFileEmpty();
262
263         // run makeindex
264         if (head.haschanged(idxfile)) {
265                 // no checks for now
266                 LYXERR(Debug::LATEX, "Running MakeIndex.");
267                 message(_("Running Index Processor."));
268                 // onlyFileName() is needed for cygwin
269                 rerun |= runMakeIndex(onlyFileName(idxfile.absFileName()),
270                                 runparams);
271         }
272         FileName const nlofile(changeExtension(file.absFileName(), ".nlo"));
273         // If all nomencl entries are removed, nomencl writes an empty nlo file.
274         // DepTable::hasChanged() returns false in this case, since it does not
275         // distinguish empty files from non-existing files. This is why we need
276         // the extra checks here (to trigger a rerun). Cf. discussions in #8905.
277         // FIXME: Sort out the real problem in DepTable.
278         if (head.haschanged(nlofile) || (nlofile.exists() && nlofile.isFileEmpty()))
279                 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
280         FileName const glofile(changeExtension(file.absFileName(), ".glo"));
281         if (head.haschanged(glofile))
282                 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
283
284         // check if we're using biber instead of bibtex
285         // biber writes no info to the aux file, so we just check
286         // if a bcf file exists (and if it was updated)
287         FileName const bcffile(changeExtension(file.absFileName(), ".bcf"));
288         biber |= head.exist(bcffile);
289
290         // run bibtex
291         // if (scanres & UNDEF_CIT || scanres & RERUN || run_bibtex)
292         if (scanres & UNDEF_CIT || run_bibtex) {
293                 // Here we must scan the .aux file and look for
294                 // "\bibdata" and/or "\bibstyle". If one of those
295                 // tags is found -> run bibtex and set rerun = true;
296                 // no checks for now
297                 LYXERR(Debug::LATEX, "Running BibTeX.");
298                 message(_("Running BibTeX."));
299                 updateBibtexDependencies(head, bibtex_info);
300                 rerun |= runBibTeX(bibtex_info, runparams);
301                 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
302                 if (blgfile.exists())
303                         bscanres = scanBlgFile(head, terr);
304         } else if (!had_depfile) {
305                 /// If we run pdflatex on the file after running latex on it,
306                 /// then we do not need to run bibtex, but we do need to
307                 /// insert the .bib and .bst files into the .dep-pdf file.
308                 updateBibtexDependencies(head, bibtex_info);
309         }
310
311         // 2
312         // we know on this point that latex has been run once (or we just
313         // returned) and the question now is to decide if we need to run
314         // it any more. This is done by asking if any of the files in the
315         // dependency file has changed. (remember that the checksum for
316         // a given file is reported to have changed if it just was created)
317         //     -> if changed or rerun == true:
318         //             run latex once more and
319         //             update the dependency structure
320         //     -> if not changed:
321         //             we do nothing at this point
322         //
323         if (rerun || head.sumchange()) {
324                 rerun = false;
325                 ++count;
326                 LYXERR(Debug::DEPEND, "Dep. file has changed or rerun requested");
327                 LYXERR(Debug::LATEX, "Run #" << count);
328                 message(runMessage(count));
329                 startscript();
330                 scanres = scanLogFile(terr);
331
332                 // update the depedencies
333                 deplog(head); // reads the latex log
334                 head.update();
335         } else {
336                 LYXERR(Debug::DEPEND, "Dep. file has NOT changed");
337         }
338         
339         // 3
340         // rerun bibtex?
341         // Complex bibliography packages such as Biblatex require
342         // an additional bibtex cycle sometimes.
343         if (scanres & UNDEF_CIT) {
344                 // Here we must scan the .aux file and look for
345                 // "\bibdata" and/or "\bibstyle". If one of those
346                 // tags is found -> run bibtex and set rerun = true;
347                 // no checks for now
348                 LYXERR(Debug::LATEX, "Running BibTeX.");
349                 message(_("Running BibTeX."));
350                 updateBibtexDependencies(head, bibtex_info);
351                 rerun |= runBibTeX(bibtex_info, runparams);
352                 FileName const blgfile(changeExtension(file.absFileName(), ".blg"));
353                 if (blgfile.exists())
354                         bscanres = scanBlgFile(head, terr);
355         }
356
357         // 4
358         // The inclusion of files generated by external programs such as
359         // makeindex or bibtex might have done changes to pagenumbering,
360         // etc. And because of this we must run the external programs
361         // again to make sure everything is redone correctly.
362         // Also there should be no need to run the external programs any
363         // more after this.
364
365         // run makeindex if the <file>.idx has changed or was generated.
366         if (head.haschanged(idxfile)) {
367                 // no checks for now
368                 LYXERR(Debug::LATEX, "Running MakeIndex.");
369                 message(_("Running Index Processor."));
370                 // onlyFileName() is needed for cygwin
371                 rerun = runMakeIndex(onlyFileName(changeExtension(
372                                 file.absFileName(), ".idx")), runparams);
373         }
374
375         // I am not pretty sure if need this twice.
376         if (head.haschanged(nlofile))
377                 rerun |= runMakeIndexNomencl(file, ".nlo", ".nls");
378         if (head.haschanged(glofile))
379                 rerun |= runMakeIndexNomencl(file, ".glo", ".gls");
380
381         // 5
382         // we will only run latex more if the log file asks for it.
383         // or if the sumchange() is true.
384         //     -> rerun asked for:
385         //             run latex and
386         //             remake the dependency file
387         //             goto 2 or return if max runs are reached.
388         //     -> rerun not asked for:
389         //             just return (fall out of bottom of func)
390         //
391         while ((head.sumchange() || rerun || (scanres & RERUN))
392                && count < MAX_RUN) {
393                 // Yes rerun until message goes away, or until
394                 // MAX_RUNS are reached.
395                 rerun = false;
396                 ++count;
397                 LYXERR(Debug::LATEX, "Run #" << count);
398                 message(runMessage(count));
399                 startscript();
400                 scanres = scanLogFile(terr);
401
402                 // keep this updated
403                 head.update();
404         }
405
406         // Write the dependencies to file.
407         head.write(depfile);
408
409         if (exit_code)
410                 scanres |= NONZERO_ERROR;
411
412         LYXERR(Debug::LATEX, "Done.");
413
414         if (bscanres & ERRORS)
415                 return bscanres; // return on error
416
417         return scanres;
418 }
419
420
421 int LaTeX::startscript()
422 {
423         // onlyFileName() is needed for cygwin
424         string tmp = cmd + ' '
425                      + quoteName(onlyFileName(file.toFilesystemEncoding()))
426                      + " > " + os::nulldev();
427         Systemcall one;
428         return one.startscript(Systemcall::Wait, tmp, path);
429 }
430
431
432 bool LaTeX::runMakeIndex(string const & f, OutputParams const & runparams,
433                          string const & params)
434 {
435         string tmp = runparams.use_japanese ?
436                 lyxrc.jindex_command : lyxrc.index_command;
437         
438         if (!runparams.index_command.empty())
439                 tmp = runparams.index_command;
440
441         LYXERR(Debug::LATEX,
442                 "idx file has been made, running index processor ("
443                 << tmp << ") on file " << f);
444
445         tmp = subst(tmp, "$$lang", runparams.document_language);
446         if (runparams.use_indices) {
447                 tmp = lyxrc.splitindex_command + " -m " + quoteName(tmp);
448                 LYXERR(Debug::LATEX,
449                 "Multiple indices. Using splitindex command: " << tmp);
450         }
451         tmp += ' ';
452         tmp += quoteName(f);
453         tmp += params;
454         Systemcall one;
455         one.startscript(Systemcall::Wait, tmp, path);
456         return true;
457 }
458
459
460 bool LaTeX::runMakeIndexNomencl(FileName const & file,
461                 string const & nlo, string const & nls)
462 {
463         LYXERR(Debug::LATEX, "Running MakeIndex for nomencl.");
464         message(_("Running MakeIndex for nomencl."));
465         string tmp = lyxrc.nomencl_command + ' ';
466         // onlyFileName() is needed for cygwin
467         tmp += quoteName(onlyFileName(changeExtension(file.absFileName(), nlo)));
468         tmp += " -o "
469                 + onlyFileName(changeExtension(file.toFilesystemEncoding(), nls));
470         Systemcall one;
471         one.startscript(Systemcall::Wait, tmp, path);
472         return true;
473 }
474
475
476 vector<AuxInfo> const
477 LaTeX::scanAuxFiles(FileName const & file)
478 {
479         vector<AuxInfo> result;
480
481         result.push_back(scanAuxFile(file));
482
483         string const basename = removeExtension(file.absFileName());
484         for (int i = 1; i < 1000; ++i) {
485                 FileName const file2(basename
486                         + '.' + convert<string>(i)
487                         + ".aux");
488                 if (!file2.exists())
489                         break;
490                 result.push_back(scanAuxFile(file2));
491         }
492         return result;
493 }
494
495
496 AuxInfo const LaTeX::scanAuxFile(FileName const & file)
497 {
498         AuxInfo result;
499         result.aux_file = file;
500         scanAuxFile(file, result);
501         return result;
502 }
503
504
505 void LaTeX::scanAuxFile(FileName const & file, AuxInfo & aux_info)
506 {
507         LYXERR(Debug::LATEX, "Scanning aux file: " << file);
508
509         ifstream ifs(file.toFilesystemEncoding().c_str());
510         string token;
511         static regex const reg1("\\\\citation\\{([^}]+)\\}");
512         static regex const reg2("\\\\bibdata\\{([^}]+)\\}");
513         static regex const reg3("\\\\bibstyle\\{([^}]+)\\}");
514         static regex const reg4("\\\\@input\\{([^}]+)\\}");
515
516         while (getline(ifs, token)) {
517                 token = rtrim(token, "\r");
518                 smatch sub;
519                 // FIXME UNICODE: We assume that citation keys and filenames
520                 // in the aux file are in the file system encoding.
521                 token = to_utf8(from_filesystem8bit(token));
522                 if (regex_match(token, sub, reg1)) {
523                         string data = sub.str(1);
524                         while (!data.empty()) {
525                                 string citation;
526                                 data = split(data, citation, ',');
527                                 LYXERR(Debug::LATEX, "Citation: " << citation);
528                                 aux_info.citations.insert(citation);
529                         }
530                 } else if (regex_match(token, sub, reg2)) {
531                         string data = sub.str(1);
532                         // data is now all the bib files separated by ','
533                         // get them one by one and pass them to the helper
534                         while (!data.empty()) {
535                                 string database;
536                                 data = split(data, database, ',');
537                                 database = changeExtension(database, "bib");
538                                 LYXERR(Debug::LATEX, "BibTeX database: `" << database << '\'');
539                                 aux_info.databases.insert(database);
540                         }
541                 } else if (regex_match(token, sub, reg3)) {
542                         string style = sub.str(1);
543                         // token is now the style file
544                         // pass it to the helper
545                         style = changeExtension(style, "bst");
546                         LYXERR(Debug::LATEX, "BibTeX style: `" << style << '\'');
547                         aux_info.styles.insert(style);
548                 } else if (regex_match(token, sub, reg4)) {
549                         string const file2 = sub.str(1);
550                         scanAuxFile(makeAbsPath(file2), aux_info);
551                 }
552         }
553 }
554
555
556 void LaTeX::updateBibtexDependencies(DepTable & dep,
557                                      vector<AuxInfo> const & bibtex_info)
558 {
559         // Since a run of Bibtex mandates more latex runs it is ok to
560         // remove all ".bib" and ".bst" files.
561         dep.remove_files_with_extension(".bib");
562         dep.remove_files_with_extension(".bst");
563         //string aux = OnlyFileName(ChangeExtension(file, ".aux"));
564
565         for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
566              it != bibtex_info.end(); ++it) {
567                 for (set<string>::const_iterator it2 = it->databases.begin();
568                      it2 != it->databases.end(); ++it2) {
569                         FileName const file = findtexfile(*it2, "bib");
570                         if (!file.empty())
571                                 dep.insert(file, true);
572                 }
573
574                 for (set<string>::const_iterator it2 = it->styles.begin();
575                      it2 != it->styles.end(); ++it2) {
576                         FileName const file = findtexfile(*it2, "bst");
577                         if (!file.empty())
578                                 dep.insert(file, true);
579                 }
580         }
581
582         // biber writes nothing into the aux file.
583         // Instead, we have to scan the blg file
584         if (biber) {
585                 TeXErrors terr;
586                 scanBlgFile(dep, terr);
587         }
588 }
589
590
591 bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
592                       OutputParams const & runparams)
593 {
594         bool result = false;
595         for (vector<AuxInfo>::const_iterator it = bibtex_info.begin();
596              it != bibtex_info.end(); ++it) {
597                 if (!biber && it->databases.empty())
598                         continue;
599                 result = true;
600
601                 string tmp = runparams.use_japanese ?
602                         lyxrc.jbibtex_command : lyxrc.bibtex_command;
603
604                 if (!runparams.bibtex_command.empty())
605                         tmp = runparams.bibtex_command;
606                 tmp += " ";
607                 // onlyFileName() is needed for cygwin
608                 tmp += quoteName(onlyFileName(removeExtension(
609                                 it->aux_file.absFileName())));
610                 Systemcall one;
611                 one.startscript(Systemcall::Wait, tmp, path);
612         }
613         // Return whether bibtex was run
614         return result;
615 }
616
617
618 int LaTeX::scanLogFile(TeXErrors & terr)
619 {
620         int last_line = -1;
621         int line_count = 1;
622         int retval = NO_ERRORS;
623         string tmp =
624                 onlyFileName(changeExtension(file.absFileName(), ".log"));
625         LYXERR(Debug::LATEX, "Log file: " << tmp);
626         FileName const fn = FileName(makeAbsPath(tmp));
627         ifstream ifs(fn.toFilesystemEncoding().c_str());
628         bool fle_style = false;
629         static regex const file_line_error(".+\\.\\D+:[0-9]+: (.+)");
630         static regex const child_file(".*([0-9]+[A-Za-z]*_.+\\.tex).*");
631         // Flag for 'File ended while scanning' message.
632         // We need to wait for subsequent processing.
633         string wait_for_error;
634         string child_name;
635         int pnest = 0;
636         stack <pair<string, int> > child;
637
638         string token;
639         while (getline(ifs, token)) {
640                 // MikTeX sometimes inserts \0 in the log file. They can't be
641                 // removed directly with the existing string utility
642                 // functions, so convert them first to \r, and remove all
643                 // \r's afterwards, since we need to remove them anyway.
644                 token = subst(token, '\0', '\r');
645                 token = subst(token, "\r", "");
646                 smatch sub;
647
648                 LYXERR(Debug::LATEX, "Log line: " << token);
649
650                 if (token.empty())
651                         continue;
652
653                 // Track child documents
654                 for (size_t i = 0; i < token.length(); ++i) {
655                         if (token[i] == '(') {
656                                 ++pnest;
657                                 size_t j = token.find('(', i + 1);
658                                 size_t len = j == string::npos
659                                                 ? token.substr(i + 1).length()
660                                                 : j - i - 1;
661                                 string const substr = token.substr(i + 1, len);
662                                 if (regex_match(substr, sub, child_file)) {
663                                         string const name = sub.str(1);
664                                         child.push(make_pair(name, pnest));
665                                         i += len;
666                                 }
667                         } else if (token[i] == ')') {
668                                 if (!child.empty()
669                                     && child.top().second == pnest)
670                                         child.pop();
671                                 --pnest;
672                         }
673                 }
674                 child_name = child.empty() ? empty_string() : child.top().first;
675
676                 if (contains(token, "file:line:error style messages enabled"))
677                         fle_style = true;
678
679                 if (prefixIs(token, "LaTeX Warning:") ||
680                     prefixIs(token, "! pdfTeX warning")) {
681                         // Here shall we handle different
682                         // types of warnings
683                         retval |= LATEX_WARNING;
684                         LYXERR(Debug::LATEX, "LaTeX Warning.");
685                         if (contains(token, "Rerun to get cross-references")) {
686                                 retval |= RERUN;
687                                 LYXERR(Debug::LATEX, "We should rerun.");
688                         // package clefval needs 2 latex runs before bibtex
689                         } else if (contains(token, "Value of")
690                                    && contains(token, "on page")
691                                    && contains(token, "undefined")) {
692                                 retval |= ERROR_RERUN;
693                                 LYXERR(Debug::LATEX, "Force rerun.");
694                         // package etaremune
695                         } else if (contains(token, "Etaremune labels have changed")) {
696                                 retval |= ERROR_RERUN;
697                                 LYXERR(Debug::LATEX, "Force rerun.");
698                         } else if (contains(token, "Citation")
699                                    && contains(token, "on page")
700                                    && contains(token, "undefined")) {
701                                 retval |= UNDEF_CIT;
702                         } else if (contains(token, "Citation")
703                                    && contains(token, "on input line")
704                                    && contains(token, "undefined")) {
705                                 retval |= UNDEF_CIT;
706                         }
707                 } else if (prefixIs(token, "Package")) {
708                         // Package warnings
709                         retval |= PACKAGE_WARNING;
710                         if (contains(token, "natbib Warning:")) {
711                                 // Natbib warnings
712                                 if (contains(token, "Citation")
713                                     && contains(token, "on page")
714                                     && contains(token, "undefined")) {
715                                         retval |= UNDEF_CIT;
716                                 }
717                         } else if (contains(token, "run BibTeX")) {
718                                 retval |= UNDEF_CIT;
719                         } else if (contains(token, "run Biber")) {
720                                 retval |= UNDEF_CIT;
721                                 biber = true;
722                         } else if (contains(token, "Rerun LaTeX") ||
723                                    contains(token, "Please rerun LaTeX") ||
724                                    contains(token, "Rerun to get")) {
725                                 // at least longtable.sty and bibtopic.sty
726                                 // might use this.
727                                 LYXERR(Debug::LATEX, "We should rerun.");
728                                 retval |= RERUN;
729                         }
730                 } else if (prefixIs(token, "LETTRE WARNING:")) {
731                         if (contains(token, "veuillez recompiler")) {
732                                 // lettre.cls
733                                 LYXERR(Debug::LATEX, "We should rerun.");
734                                 retval |= RERUN;
735                         }
736                 } else if (token[0] == '(') {
737                         if (contains(token, "Rerun LaTeX") ||
738                             contains(token, "Rerun to get")) {
739                                 // Used by natbib
740                                 LYXERR(Debug::LATEX, "We should rerun.");
741                                 retval |= RERUN;
742                         }
743                 } else if (prefixIs(token, "! ")
744                             || (fle_style
745                                 && regex_match(token, sub, file_line_error)
746                                 && !contains(token, "pdfTeX warning"))) {
747                            // Ok, we have something that looks like a TeX Error
748                            // but what do we really have.
749
750                         // Just get the error description:
751                         string desc;
752                         if (prefixIs(token, "! "))
753                                 desc = string(token, 2);
754                         else if (fle_style)
755                                 desc = sub.str();
756                         if (contains(token, "LaTeX Error:"))
757                                 retval |= LATEX_ERROR;
758
759                         if (prefixIs(token, "! File ended while scanning")){
760                                 if (prefixIs(token, "! File ended while scanning use of \\Hy@setref@link.")){
761                                         // bug 7344. We must rerun LaTeX if hyperref has been toggled.
762                                         retval |= ERROR_RERUN;
763                                         LYXERR(Debug::LATEX, "Force rerun.");
764                                 } else {
765                                         // bug 6445. At this point its not clear we finish with error.
766                                         wait_for_error = desc;
767                                         continue;
768                                 }
769                         }
770
771                         if (prefixIs(token, "! Paragraph ended before \\Hy@setref@link was complete.")){
772                                         // bug 7344. We must rerun LaTeX if hyperref has been toggled.
773                                         retval |= ERROR_RERUN;
774                                         LYXERR(Debug::LATEX, "Force rerun.");
775                         }
776
777                         if (!wait_for_error.empty() && prefixIs(token, "! Emergency stop.")){
778                                 retval |= LATEX_ERROR;
779                                 string errstr;
780                                 int count = 0;
781                                 errstr = wait_for_error;
782                                 do {
783                                         if (!getline(ifs, tmp))
784                                                 break;
785                                         tmp = rtrim(tmp, "\r");
786                                         errstr += "\n" + tmp;
787                                         if (++count > 5)
788                                                 break;
789                                 } while (!contains(tmp, "(job aborted"));
790
791                                 terr.insertError(0,
792                                                  from_local8bit("Emergency stop"),
793                                                  from_local8bit(errstr),
794                                                  child_name);
795                         }
796
797                         // get the next line
798                         string tmp;
799                         int count = 0;
800                         do {
801                                 if (!getline(ifs, tmp))
802                                         break;
803                                 tmp = rtrim(tmp, "\r");
804                                 // 15 is somewhat arbitrarily chosen, based on practice.
805                                 // We used 10 for 14 years and increased it to 15 when we
806                                 // saw one case.
807                                 if (++count > 15)
808                                         break;
809                         } while (!prefixIs(tmp, "l."));
810                         if (prefixIs(tmp, "l.")) {
811                                 // we have a latex error
812                                 retval |=  TEX_ERROR;
813                                 if (contains(desc,
814                                         "Package babel Error: You haven't defined the language")
815                                     || contains(desc,
816                                         "Package babel Error: You haven't loaded the option")
817                                     || contains(desc,
818                                         "Package babel Error: Unknown language"))
819                                         retval |= ERROR_RERUN;
820                                 // get the line number:
821                                 int line = 0;
822                                 sscanf(tmp.c_str(), "l.%d", &line);
823                                 // get the rest of the message:
824                                 string errstr(tmp, tmp.find(' '));
825                                 errstr += '\n';
826                                 getline(ifs, tmp);
827                                 tmp = rtrim(tmp, "\r");
828                                 while (!contains(errstr, "l.")
829                                        && !tmp.empty()
830                                        && !prefixIs(tmp, "! ")
831                                        && !contains(tmp, "(job aborted")) {
832                                         errstr += tmp;
833                                         errstr += "\n";
834                                         getline(ifs, tmp);
835                                         tmp = rtrim(tmp, "\r");
836                                 }
837                                 LYXERR(Debug::LATEX, "line: " << line << '\n'
838                                         << "Desc: " << desc << '\n' << "Text: " << errstr);
839                                 if (line == last_line)
840                                         ++line_count;
841                                 else {
842                                         line_count = 1;
843                                         last_line = line;
844                                 }
845                                 if (line_count <= 5) {
846                                         // FIXME UNICODE
847                                         // We have no idea what the encoding of
848                                         // the log file is.
849                                         // It seems that the output from the
850                                         // latex compiler itself is pure ASCII,
851                                         // but it can include bits from the
852                                         // document, so whatever encoding we
853                                         // assume here it can be wrong.
854                                         terr.insertError(line,
855                                                          from_local8bit(desc),
856                                                          from_local8bit(errstr),
857                                                          child_name);
858                                         ++num_errors;
859                                 }
860                         }
861                 } else {
862                         // information messages, TeX warnings and other
863                         // warnings we have not caught earlier.
864                         if (prefixIs(token, "Overfull ")) {
865                                 retval |= TEX_WARNING;
866                         } else if (prefixIs(token, "Underfull ")) {
867                                 retval |= TEX_WARNING;
868                         } else if (contains(token, "Rerun to get citations")) {
869                                 // Natbib seems to use this.
870                                 retval |= UNDEF_CIT;
871                         } else if (contains(token, "No pages of output")) {
872                                 // A dvi file was not created
873                                 retval |= NO_OUTPUT;
874                         } else if (contains(token, "That makes 100 errors")) {
875                                 // More than 100 errors were reprted
876                                 retval |= TOO_MANY_ERRORS;
877                         } else if (prefixIs(token, "!pdfTeX error:")){
878                                 // otherwise we dont catch e.g.:
879                                 // !pdfTeX error: pdflatex (file feyn10): Font feyn10 at 600 not found
880                                 retval |= ERRORS;
881                                         terr.insertError(0,
882                                                          from_local8bit("pdfTeX Error"),
883                                                          from_local8bit(token),
884                                                          child_name);
885                         }
886                 }
887         }
888         LYXERR(Debug::LATEX, "Log line: " << token);
889         return retval;
890 }
891
892
893 namespace {
894
895 bool insertIfExists(FileName const & absname, DepTable & head)
896 {
897         if (absname.exists() && !absname.isDirectory()) {
898                 head.insert(absname, true);
899                 return true;
900         }
901         return false;
902 }
903
904
905 bool handleFoundFile(string const & ff, DepTable & head)
906 {
907         // convert from native os path to unix path
908         string foundfile = os::internal_path(trim(ff));
909
910         LYXERR(Debug::DEPEND, "Found file: " << foundfile);
911
912         // Ok now we found a file.
913         // Now we should make sure that this is a file that we can
914         // access through the normal paths.
915         // We will not try any fancy search methods to
916         // find the file.
917
918         // (1) foundfile is an
919         //     absolute path and should
920         //     be inserted.
921         FileName absname;
922         if (FileName::isAbsolute(foundfile)) {
923                 LYXERR(Debug::DEPEND, "AbsolutePath file: " << foundfile);
924                 // On initial insert we want to do the update at once
925                 // since this file cannot be a file generated by
926                 // the latex run.
927                 absname.set(foundfile);
928                 if (!insertIfExists(absname, head)) {
929                         // check for spaces
930                         string strippedfile = foundfile;
931                         while (contains(strippedfile, " ")) {
932                                 // files with spaces are often enclosed in quotation
933                                 // marks; those have to be removed
934                                 string unquoted = subst(strippedfile, "\"", "");
935                                 absname.set(unquoted);
936                                 if (insertIfExists(absname, head))
937                                         return true;
938                                 // strip off part after last space and try again
939                                 string tmp = strippedfile;
940                                 string const stripoff =
941                                         rsplit(tmp, strippedfile, ' ');
942                                 absname.set(strippedfile);
943                                 if (insertIfExists(absname, head))
944                                         return true;
945                         }
946                 }
947         }
948
949         string onlyfile = onlyFileName(foundfile);
950         absname = makeAbsPath(onlyfile);
951
952         // check for spaces
953         while (contains(foundfile, ' ')) {
954                 if (absname.exists())
955                         // everything o.k.
956                         break;
957                 else {
958                         // files with spaces are often enclosed in quotation
959                         // marks; those have to be removed
960                         string unquoted = subst(foundfile, "\"", "");
961                         absname = makeAbsPath(unquoted);
962                         if (absname.exists())
963                                 break;
964                         // strip off part after last space and try again
965                         string strippedfile;
966                         string const stripoff =
967                                 rsplit(foundfile, strippedfile, ' ');
968                         foundfile = strippedfile;
969                         onlyfile = onlyFileName(strippedfile);
970                         absname = makeAbsPath(onlyfile);
971                 }
972         }
973
974         // (2) foundfile is in the tmpdir
975         //     insert it into head
976         if (absname.exists() && !absname.isDirectory()) {
977                 // FIXME: This regex contained glo, but glo is used by the old
978                 // version of nomencl.sty. Do we need to put it back?
979                 static regex const unwanted("^.*\\.(aux|log|dvi|bbl|ind)$");
980                 if (regex_match(onlyfile, unwanted)) {
981                         LYXERR(Debug::DEPEND, "We don't want " << onlyfile
982                                 << " in the dep file");
983                 } else if (suffixIs(onlyfile, ".tex")) {
984                         // This is a tex file generated by LyX
985                         // and latex is not likely to change this
986                         // during its runs.
987                         LYXERR(Debug::DEPEND, "Tmpdir TeX file: " << onlyfile);
988                         head.insert(absname, true);
989                 } else {
990                         LYXERR(Debug::DEPEND, "In tmpdir file:" << onlyfile);
991                         head.insert(absname);
992                 }
993                 return true;
994         } else {
995                 LYXERR(Debug::DEPEND, "Not a file or we are unable to find it.");
996                 return false;
997         }
998 }
999
1000
1001 bool completeFilename(string const & ff, DepTable & head)
1002 {
1003         // If we do not find a dot, we suspect
1004         // a fragmental file name
1005         if (!contains(ff, '.'))
1006                 return false;
1007
1008         // if we have a dot, we let handleFoundFile decide
1009         return handleFoundFile(ff, head);
1010 }
1011
1012
1013 int iterateLine(string const & token, regex const & reg, string const & closing,
1014                 int fragment_pos, DepTable & head)
1015 {
1016         smatch what;
1017         string::const_iterator first = token.begin();
1018         string::const_iterator end = token.end();
1019         bool fragment = false;
1020         string last_match;
1021
1022         while (regex_search(first, end, what, reg)) {
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) == closing) {
1027                                 handleFoundFile(what.str(1), head);
1028                                 // since we had a closing bracket,
1029                                 // do not investigate further
1030                                 fragment = false;
1031                         } else
1032                                 // if we have no closing bracket,
1033                                 // try to handle as file nevertheless
1034                                 fragment = !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) != closing) {
1040                         first = what[0].second;
1041                         fragment = true;
1042                 } else {
1043                         // we have a closing bracket, so the content
1044                         // is not a file name.
1045                         // no need to investigate further
1046                         first = what[0].second;
1047                         fragment = false;
1048                 }
1049                 last_match = what.str(1);
1050         }
1051
1052         // We need to consider the result from previous line iterations:
1053         // We might not find a fragment here, but another one might follow
1054         // E.g.: (filename.ext) <filenam
1055         // Vice versa, we consider the search completed if a real match
1056         // follows a potential fragment from a previous iteration.
1057         // E.g. <some text we considered a fragment (filename.ext)
1058         // result = -1 means we did not find a fragment!
1059         int result = -1;
1060         int last_match_pos = -1;
1061         if (!last_match.empty() && token.find(last_match) != string::npos)
1062                 last_match_pos = int(token.find(last_match));
1063         if (fragment) {
1064                 if (last_match_pos > fragment_pos)
1065                         result = last_match_pos;
1066                 else
1067                         result = fragment_pos;
1068         } else
1069                 if (last_match_pos < fragment_pos)
1070                         result = fragment_pos;
1071
1072         return result;
1073 }
1074
1075 } // anon namespace
1076
1077
1078 void LaTeX::deplog(DepTable & head)
1079 {
1080         // This function reads the LaTeX log file end extracts all the
1081         // external files used by the LaTeX run. The files are then
1082         // entered into the dependency file.
1083
1084         string const logfile =
1085                 onlyFileName(changeExtension(file.absFileName(), ".log"));
1086
1087         static regex const reg1("File: (.+).*");
1088         static regex const reg2("No file (.+)(.).*");
1089         static regex const reg3("\\\\openout[0-9]+.*=.*`(.+)(..).*");
1090         // If an index should be created, MikTex does not write a line like
1091         //    \openout# = 'sample.idx'.
1092         // but instead only a line like this into the log:
1093         //   Writing index file sample.idx
1094         static regex const reg4("Writing index file (.+).*");
1095         static regex const regoldnomencl("Writing glossary file (.+).*");
1096         static regex const regnomencl("Writing nomenclature file (.+).*");
1097         // If a toc should be created, MikTex does not write a line like
1098         //    \openout# = `sample.toc'.
1099         // but only a line like this into the log:
1100         //    \tf@toc=\write#
1101         // This line is also written by tetex.
1102         // This line is not present if no toc should be created.
1103         static regex const miktexTocReg("\\\\tf@toc=\\\\write.*");
1104         // file names can be enclosed in <...> (anywhere on the line)
1105         static regex const reg5(".*<[^>]+.*");
1106         // and also (...) anywhere on the line
1107         static regex const reg6(".*\\([^)]+.*");
1108
1109         FileName const fn = makeAbsPath(logfile);
1110         ifstream ifs(fn.toFilesystemEncoding().c_str());
1111         string lastline;
1112         while (ifs) {
1113                 // Ok, the scanning of files here is not sufficient.
1114                 // Sometimes files are named by "File: xxx" only
1115                 // Therefore we use some regexps to find files instead.
1116                 // Note: all file names and paths might contains spaces.
1117                 // Also, file names might be broken across lines. Therefore
1118                 // we mark (potential) fragments and merge those lines.
1119                 bool fragment = false;
1120                 string token;
1121                 getline(ifs, token);
1122                 // MikTeX sometimes inserts \0 in the log file. They can't be
1123                 // removed directly with the existing string utility
1124                 // functions, so convert them first to \r, and remove all
1125                 // \r's afterwards, since we need to remove them anyway.
1126                 token = subst(token, '\0', '\r');
1127                 token = subst(token, "\r", "");
1128                 if (token.empty() || token == ")") {
1129                         lastline = string();
1130                         continue;
1131                 }
1132
1133                 // FIXME UNICODE: We assume that the file names in the log
1134                 // file are in the file system encoding.
1135                 token = to_utf8(from_filesystem8bit(token));
1136
1137                 // Sometimes, filenames are broken across lines.
1138                 // We care for that and save suspicious lines.
1139                 // Here we exclude some cases where we are sure
1140                 // that there is no continued filename
1141                 if (!lastline.empty()) {
1142                         static regex const package_info("Package \\w+ Info: .*");
1143                         static regex const package_warning("Package \\w+ Warning: .*");
1144                         if (prefixIs(token, "File:") || prefixIs(token, "(Font)")
1145                             || prefixIs(token, "Package:")
1146                             || prefixIs(token, "Language:")
1147                             || prefixIs(token, "LaTeX Info:")
1148                             || prefixIs(token, "LaTeX Font Info:")
1149                             || prefixIs(token, "\\openout[")
1150                             || prefixIs(token, "))")
1151                             || regex_match(token, package_info)
1152                             || regex_match(token, package_warning))
1153                                 lastline = string();
1154                 }
1155
1156                 if (!lastline.empty())
1157                         // probably a continued filename from last line
1158                         token = lastline + token;
1159                 if (token.length() > 255) {
1160                         // string too long. Cut off.
1161                         token.erase(0, token.length() - 251);
1162                 }
1163
1164                 smatch sub;
1165
1166                 // (1) "File: file.ext"
1167                 if (regex_match(token, sub, reg1)) {
1168                         // is this a fragmental file name?
1169                         fragment = !completeFilename(sub.str(1), head);
1170                         // However, ...
1171                         if (suffixIs(token, ")"))
1172                                 // no fragment for sure
1173                                 fragment = false;
1174                 // (2) "No file file.ext"
1175                 } else if (regex_match(token, sub, reg2)) {
1176                         // file names must contains a dot, line ends with dot
1177                         if (contains(sub.str(1), '.') && sub.str(2) == ".")
1178                                 fragment = !handleFoundFile(sub.str(1), head);
1179                         else
1180                                 // we suspect a line break
1181                                 fragment = true;
1182                 // (3) "\openout<nr> = `file.ext'."
1183                 } else if (regex_match(token, sub, reg3)) {
1184                         // search for closing '. at the end of the line
1185                         if (sub.str(2) == "\'.")
1186                                 fragment = !handleFoundFile(sub.str(1), head);
1187                         else
1188                                 // potential fragment
1189                                 fragment = true;
1190                 // (4) "Writing index file file.ext"
1191                 } else if (regex_match(token, sub, reg4))
1192                         // fragmential file name?
1193                         fragment = !completeFilename(sub.str(1), head);
1194                 // (5) "Writing nomenclature file file.ext"
1195                 else if (regex_match(token, sub, regnomencl) ||
1196                            regex_match(token, sub, regoldnomencl))
1197                         // fragmental file name?
1198                         fragment= !completeFilename(sub.str(1), head);
1199                 // (6) "\tf@toc=\write<nr>" (for MikTeX)
1200                 else if (regex_match(token, sub, miktexTocReg))
1201                         fragment = !handleFoundFile(onlyFileName(changeExtension(
1202                                                 file.absFileName(), ".toc")), head);
1203                 else
1204                         // not found, but we won't check further
1205                         fragment = false;
1206
1207                 int fragment_pos = -1;
1208                 // (7) "<file.ext>"
1209                 // We can have several of these on one line
1210                 // (and in addition to those above)
1211                 if (regex_match(token, sub, reg5)) {
1212                         // search for strings in <...>
1213                         static regex const reg5_1("<([^>]+)(.)");
1214                         fragment_pos = iterateLine(token, reg5_1, ">",
1215                                                    fragment_pos, head);
1216                         fragment = (fragment_pos != -1);
1217                 }
1218
1219                 // (8) "(file.ext)"
1220                 // We can have several of these on one line
1221                 // this must be queried separated, because of
1222                 // cases such as "File: file.ext (type eps)"
1223                 // where "File: file.ext" would be skipped
1224                 if (regex_match(token, sub, reg6)) {
1225                         // search for strings in (...)
1226                         static regex const reg6_1("\\(([^()]+)(.)");
1227                         fragment_pos = iterateLine(token, reg6_1, ")",
1228                                                    fragment_pos, head);
1229                         fragment = (fragment_pos != -1);
1230                 }
1231
1232                 if (fragment)
1233                         // probable linebreak within file name:
1234                         // save this line
1235                         lastline = token;
1236                 else
1237                         // no linebreak: reset
1238                         lastline = string();
1239         }
1240
1241         // Make sure that the main .tex file is in the dependency file.
1242         head.insert(file, true);
1243 }
1244
1245
1246 int LaTeX::scanBlgFile(DepTable & dep, TeXErrors & terr)
1247 {
1248         FileName const blg_file(changeExtension(file.absFileName(), "blg"));
1249         LYXERR(Debug::LATEX, "Scanning blg file: " << blg_file);
1250
1251         ifstream ifs(blg_file.toFilesystemEncoding().c_str());
1252         string token;
1253         static regex const reg1(".*Found (bibtex|BibTeX) data (file|source) '([^']+).*");
1254         static regex const bibtexError("^(.*---line [0-9]+ of file).*$");
1255         static regex const bibtexError2("^(.*---while reading file).*$");
1256         static regex const bibtexError3("(A bad cross reference---).*");
1257         static regex const bibtexError4("(Sorry---you've exceeded BibTeX's).*");
1258         static regex const bibtexError5("\\*Please notify the BibTeX maintainer\\*");
1259         static regex const biberError("^.*> (FATAL|ERROR) - (.*)$");
1260         int retval = NO_ERRORS;
1261
1262         string prevtoken;
1263         while (getline(ifs, token)) {
1264                 token = rtrim(token, "\r");
1265                 smatch sub;
1266                 // FIXME UNICODE: We assume that citation keys and filenames
1267                 // in the aux file are in the file system encoding.
1268                 token = to_utf8(from_filesystem8bit(token));
1269                 if (regex_match(token, sub, reg1)) {
1270                         string data = sub.str(3);
1271                         if (!data.empty()) {
1272                                 LYXERR(Debug::LATEX, "Found bib file: " << data);
1273                                 handleFoundFile(data, dep);
1274                         }
1275                 }
1276                 else if (regex_match(token, sub, bibtexError)
1277                          || regex_match(token, sub, bibtexError2)
1278                          || regex_match(token, sub, bibtexError4)
1279                          || regex_match(token, sub, bibtexError5)) {
1280                         retval |= BIBTEX_ERROR;
1281                         string errstr = N_("BibTeX error: ") + token;
1282                         string message;
1283                         if ((prefixIs(token, "while executing---line")
1284                              || prefixIs(token, "---line ")
1285                              || prefixIs(token, "*Please notify the BibTeX"))
1286                             && !prevtoken.empty()) {
1287                                 errstr = N_("BibTeX error: ") + prevtoken;
1288                                 message = prevtoken + '\n';
1289                         }
1290                         message += token;
1291                         terr.insertError(0,
1292                                          from_local8bit(errstr),
1293                                          from_local8bit(message));
1294                 } else if (regex_match(prevtoken, sub, bibtexError3)) {
1295                         retval |= BIBTEX_ERROR;
1296                         string errstr = N_("BibTeX error: ") + prevtoken;
1297                         string message = prevtoken + '\n' + token;
1298                         terr.insertError(0,
1299                                          from_local8bit(errstr),
1300                                          from_local8bit(message));
1301                 } else if (regex_match(token, sub, biberError)) {
1302                         retval |= BIBTEX_ERROR;
1303                         string errstr = N_("Biber error: ") + sub.str(2);
1304                         string message = token;
1305                         terr.insertError(0,
1306                                          from_local8bit(errstr),
1307                                          from_local8bit(message));
1308                 }
1309                 prevtoken = token;
1310         }
1311         return retval;
1312 }
1313
1314
1315 } // namespace lyx