]> git.lyx.org Git - lyx.git/blob - src/support/filetools.cpp
Embedding: merge lyx::EmbeddedFiles to lyx::support::EmbeddedFileList
[lyx.git] / src / support / filetools.cpp
1 /**
2  * \file filetools.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * parts Copyright 1985, 1990, 1993 Free Software Foundation, Inc.
7  *
8  * \author Ivan Schreter
9  * \author Dirk Niggemann
10  * \author Asger Alstrup
11  * \author Lars Gullik Bjønnes
12  * \author Jean-Marc Lasgouttes
13  * \author Angus Leeming
14  * \author John Levon
15  * \author Herbert Voß
16  *
17  * Full author contact details are available in file CREDITS.
18  *
19  * General path-mangling functions
20  */
21
22 #include <config.h>
23
24 #include "support/filetools.h"
25
26 #include "support/convert.h"
27 #include "support/debug.h"
28 #include "support/environment.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/os.h"
32 #include "support/Package.h"
33 #include "support/Path.h"
34 #include "support/Systemcall.h"
35 #include "support/qstring_helpers.h"
36
37 #include <QDir>
38
39 #include <boost/assert.hpp>
40 #include <boost/regex.hpp>
41
42 #include <fcntl.h>
43
44 #include <cerrno>
45 #include <cstdlib>
46 #include <cstdio>
47
48 #include <utility>
49 #include <fstream>
50 #include <sstream>
51
52 using namespace std;
53
54 namespace lyx {
55 namespace support {
56
57 bool isLyXFilename(string const & filename)
58 {
59         return suffixIs(ascii_lowercase(filename), ".lyx");
60 }
61
62
63 bool isSGMLFilename(string const & filename)
64 {
65         return suffixIs(ascii_lowercase(filename), ".sgml");
66 }
67
68
69 bool isValidLaTeXFilename(string const & filename)
70 {
71         string const invalid_chars("#$%{}()[]\"^");
72         return filename.find_first_of(invalid_chars) == string::npos;
73 }
74
75
76 string const latex_path(string const & original_path,
77                 latex_path_extension extension,
78                 latex_path_dots dots)
79 {
80         // On cygwin, we may need windows or posix style paths.
81         string path = os::latex_path(original_path);
82         path = subst(path, "~", "\\string~");
83         if (path.find(' ') != string::npos) {
84                 // We can't use '"' because " is sometimes active (e.g. if
85                 // babel is loaded with the "german" option)
86                 if (extension == EXCLUDE_EXTENSION) {
87                         // ChangeExtension calls os::internal_path internally
88                         // so don't use it to remove the extension.
89                         string const ext = getExtension(path);
90                         string const base = ext.empty() ?
91                                 path :
92                                 path.substr(0, path.length() - ext.length() - 1);
93                         // ChangeExtension calls os::internal_path internally
94                         // so don't use it to re-add the extension.
95                         path = "\\string\"" + base + "\\string\"." + ext;
96                 } else {
97                         path = "\\string\"" + path + "\\string\"";
98                 }
99         }
100
101         return dots == ESCAPE_DOTS ? subst(path, ".", "\\lyxdot ") : path;
102 }
103
104
105 // Substitutes spaces with underscores in filename (and path)
106 FileName const makeLatexName(FileName const & file)
107 {
108         string name = file.onlyFileName();
109         string const path = file.onlyPath().absFilename() + "/";
110
111         // ok so we scan through the string twice, but who cares.
112         // FIXME: in Unicode time this will break for sure! There is
113         // a non-latin world out there...
114         string const keep = "abcdefghijklmnopqrstuvwxyz"
115                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
116                 "@!'()*+,-./0123456789:;<=>?[]`|";
117
118         string::size_type pos = 0;
119         while ((pos = name.find_first_not_of(keep, pos)) != string::npos)
120                 name[pos++] = '_';
121
122         FileName latex_name(path + name);
123         latex_name.changeExtension(".tex");
124         return latex_name;
125 }
126
127
128 string const quoteName(string const & name, quote_style style)
129 {
130         switch(style) {
131         case quote_shell:
132                 // This does not work for filenames containing " (windows)
133                 // or ' (all other OSes). This can't be changed easily, since
134                 // we would need to adapt the command line parser in
135                 // Forkedcall::generateChild. Therefore we don't pass user
136                 // filenames to child processes if possible. We store them in
137                 // a python script instead, where we don't have these
138                 // limitations.
139                 return (os::shell() == os::UNIX) ?
140                         '\'' + name + '\'':
141                         '"' + name + '"';
142         case quote_python:
143                 return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
144                      + "\"";
145         }
146         // shut up stupid compiler
147         return string();
148 }
149
150
151 #if 0
152 // Uses a string of paths separated by ";"s to find a file to open.
153 // Can't cope with pathnames with a ';' in them. Returns full path to file.
154 // If path entry begins with $$LyX/, use system_lyxdir
155 // If path entry begins with $$User/, use user_lyxdir
156 // Example: "$$User/doc;$$LyX/doc"
157 FileName const fileOpenSearch(string const & path, string const & name,
158                              string const & ext)
159 {
160         FileName real_file;
161         string path_element;
162         bool notfound = true;
163         string tmppath = split(path, path_element, ';');
164
165         while (notfound && !path_element.empty()) {
166                 path_element = os::internal_path(path_element);
167                 if (!suffixIs(path_element, '/'))
168                         path_element += '/';
169                 path_element = subst(path_element, "$$LyX",
170                                      package().system_support().absFilename());
171                 path_element = subst(path_element, "$$User",
172                                      package().user_support().absFilename());
173
174                 real_file = fileSearch(path_element, name, ext);
175
176                 if (real_file.empty()) {
177                         do {
178                                 tmppath = split(tmppath, path_element, ';');
179                         } while (!tmppath.empty() && path_element.empty());
180                 } else {
181                         notfound = false;
182                 }
183         }
184         return real_file;
185 }
186 #endif
187
188
189 // Returns the real name of file name in directory path, with optional
190 // extension ext.
191 FileName const fileSearch(string const & path, string const & name,
192                           string const & ext, search_mode mode)
193 {
194         // if `name' is an absolute path, we ignore the setting of `path'
195         // Expand Environmentvariables in 'name'
196         string const tmpname = replaceEnvironmentPath(name);
197         FileName fullname(makeAbsPath(tmpname, path));
198         // search first without extension, then with it.
199         if (fullname.isReadableFile())
200                 return fullname;
201         if (ext.empty())
202                 // We are done.
203                 return mode == allow_unreadable ? fullname : FileName();
204         // Only add the extension if it is not already the extension of
205         // fullname.
206         if (getExtension(fullname.absFilename()) != ext)
207                 fullname = FileName(addExtension(fullname.absFilename(), ext));
208         if (fullname.isReadableFile() || mode == allow_unreadable)
209                 return fullname;
210         return FileName();
211 }
212
213
214 // Search the file name.ext in the subdirectory dir of
215 //   1) user_lyxdir
216 //   2) build_lyxdir (if not empty)
217 //   3) system_lyxdir
218 FileName const libFileSearch(string const & dir, string const & name,
219                            string const & ext)
220 {
221         FileName fullname = fileSearch(addPath(package().user_support().absFilename(), dir),
222                                      name, ext);
223         if (!fullname.empty())
224                 return fullname;
225
226         if (!package().build_support().empty())
227                 fullname = fileSearch(addPath(package().build_support().absFilename(), dir),
228                                       name, ext);
229         if (!fullname.empty())
230                 return fullname;
231
232         return fileSearch(addPath(package().system_support().absFilename(), dir), name, ext);
233 }
234
235
236 FileName const i18nLibFileSearch(string const & dir, string const & name,
237                   string const & ext)
238 {
239         /* The highest priority value is the `LANGUAGE' environment
240            variable. But we don't use the value if the currently
241            selected locale is the C locale. This is a GNU extension.
242
243            Otherwise, w use a trick to guess what support/gettext.has done:
244            each po file is able to tell us its name. (JMarc)
245         */
246
247         string lang = to_ascii(_("[[Replace with the code of your language]]"));
248         string const language = getEnv("LANGUAGE");
249         if (!lang.empty() && !language.empty())
250                 lang = language;
251
252         string l;
253         lang = split(lang, l, ':');
254         while (!l.empty()) {
255                 FileName tmp;
256                 // First try with the full name
257                 tmp = libFileSearch(addPath(dir, l), name, ext);
258                 if (!tmp.empty())
259                         return tmp;
260
261                 // Then the name without country code
262                 string const shortl = token(l, '_', 0);
263                 if (shortl != l) {
264                         tmp = libFileSearch(addPath(dir, shortl), name, ext);
265                         if (!tmp.empty())
266                                 return tmp;
267                 }
268
269 #if 1
270                 // For compatibility, to be removed later (JMarc)
271                 tmp = libFileSearch(dir, token(l, '_', 0) + '_' + name,
272                                     ext);
273                 if (!tmp.empty()) {
274                         lyxerr << "i18nLibFileSearch: File `" << tmp
275                                << "' has been found by the old method" <<endl;
276                         return tmp;
277                 }
278 #endif
279                 lang = split(lang, l, ':');
280         }
281
282         return libFileSearch(dir, name, ext);
283 }
284
285
286 string const libScriptSearch(string const & command_in, quote_style style)
287 {
288         static string const token_scriptpath = "$$s/";
289
290         string command = command_in;
291         // Find the starting position of "$$s/"
292         string::size_type const pos1 = command.find(token_scriptpath);
293         if (pos1 == string::npos)
294                 return command;
295         // Find the end of the "$$s/some_subdir/some_script" word within
296         // command. Assumes that the script name does not contain spaces.
297         string::size_type const start_script = pos1 + 4;
298         string::size_type const pos2 = command.find(' ', start_script);
299         string::size_type const size_script = pos2 == string::npos?
300                 (command.size() - start_script) : pos2 - start_script;
301
302         // Does this script file exist?
303         string const script =
304                 libFileSearch(".", command.substr(start_script, size_script)).absFilename();
305
306         if (script.empty()) {
307                 // Replace "$$s/" with ""
308                 command.erase(pos1, 4);
309         } else {
310                 // Replace "$$s/foo/some_script" with "<path to>/some_script".
311                 string::size_type const size_replace = size_script + 4;
312                 command.replace(pos1, size_replace, quoteName(script, style));
313         }
314
315         return command;
316 }
317
318
319 static FileName createTmpDir(FileName const & tempdir, string const & mask)
320 {
321         LYXERR(Debug::FILES, "createTmpDir: tempdir=`" << tempdir << "'\n"
322                 << "createTmpDir:    mask=`" << mask << '\'');
323
324         FileName const tmpfl = FileName::tempName(tempdir.absFilename()
325                 + "/" + mask);
326         // FileName::tempName actually creates a file to make sure that it
327         // stays unique. So we have to delete it before we can create
328         // a dir with the same name. Note also that we are not thread
329         // safe because of the gap between unlink and mkdir. (Lgb)
330         tmpfl.removeFile();
331
332         if (tmpfl.empty() || !tmpfl.createDirectory(0700)) {
333                 lyxerr << "LyX could not create the temporary directory '"
334                        << tmpfl << "'" << endl;
335                 return FileName();
336         }
337
338         return tmpfl;
339 }
340
341
342 FileName const createLyXTmpDir(FileName const & deflt)
343 {
344         if (deflt.empty() || deflt.absFilename() == "/tmp")
345                 return createTmpDir(FileName("/tmp"), "lyx_tmpdir");
346
347         if (deflt.createDirectory(0777)) 
348                 return deflt;
349
350         if (deflt.isDirWritable()) {
351                 // deflt could not be created because it
352                 // did exist already, so let's create our own
353                 // dir inside deflt.
354                 return createTmpDir(deflt, "lyx_tmpdir");
355         } else {
356                 // some other error occured.
357                 return createTmpDir(FileName("/tmp"), "lyx_tmpdir");
358         }
359 }
360
361
362 // Strip filename from path name
363 string const onlyPath(string const & filename)
364 {
365         // If empty filename, return empty
366         if (filename.empty())
367                 return filename;
368
369         // Find last / or start of filename
370         size_t j = filename.rfind('/');
371         return j == string::npos ? "./" : filename.substr(0, j + 1);
372 }
373
374
375 // Convert relative path into absolute path based on a basepath.
376 // If relpath is absolute, just use that.
377 // If basepath is empty, use CWD as base.
378 FileName const makeAbsPath(string const & relPath, string const & basePath)
379 {
380         FileName relative_path(relPath);
381         // checks for already absolute path
382         if (relative_path.isAbsolute())
383                 return relative_path;
384
385         // Copies given paths
386         string tempRel = os::internal_path(relPath);
387         // Since TempRel is NOT absolute, we can safely replace "//" with "/"
388         tempRel = subst(tempRel, "//", "/");
389
390         string tempBase;
391
392         FileName base_path(basePath);
393         if (base_path.isAbsolute())
394                 tempBase = basePath;
395         else
396                 tempBase = addPath(FileName::getcwd().absFilename(), basePath);
397
398         // Handle /./ at the end of the path
399         while (suffixIs(tempBase, "/./"))
400                 tempBase.erase(tempBase.length() - 2);
401
402         // processes relative path
403         string rTemp = tempRel;
404         string temp;
405
406         while (!rTemp.empty()) {
407                 // Split by next /
408                 rTemp = split(rTemp, temp, '/');
409
410                 if (temp == ".") continue;
411                 if (temp == "..") {
412                         // Remove one level of TempBase
413                         string::difference_type i = tempBase.length() - 2;
414                         if (i < 0)
415                                 i = 0;
416                         while (i > 0 && tempBase[i] != '/')
417                                 --i;
418                         if (i > 0)
419                                 tempBase.erase(i, string::npos);
420                         else
421                                 tempBase += '/';
422                 } else if (temp.empty() && !rTemp.empty()) {
423                                 tempBase = os::current_root() + rTemp;
424                                 rTemp.erase();
425                 } else {
426                         // Add this piece to TempBase
427                         if (!suffixIs(tempBase, '/'))
428                                 tempBase += '/';
429                         tempBase += temp;
430                 }
431         }
432
433         // returns absolute path
434         return FileName(tempBase);
435 }
436
437
438 // Correctly append filename to the pathname.
439 // If pathname is '.', then don't use pathname.
440 // Chops any path of filename.
441 string const addName(string const & path, string const & fname)
442 {
443         string const basename = onlyFilename(fname);
444         string buf;
445
446         if (path != "." && path != "./" && !path.empty()) {
447                 buf = os::internal_path(path);
448                 if (!suffixIs(path, '/'))
449                         buf += '/';
450         }
451
452         return buf + basename;
453 }
454
455
456 // Strips path from filename
457 string const onlyFilename(string const & fname)
458 {
459         if (fname.empty())
460                 return fname;
461
462         string::size_type j = fname.rfind('/');
463         if (j == string::npos) // no '/' in fname
464                 return fname;
465
466         // Strip to basename
467         return fname.substr(j + 1);
468 }
469
470
471 // Create absolute path. If impossible, don't do anything
472 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
473 string const expandPath(string const & path)
474 {
475         // checks for already absolute path
476         string rTemp = replaceEnvironmentPath(path);
477         FileName abs_path(rTemp);
478         if (abs_path.isAbsolute())
479                 return rTemp;
480
481         string temp;
482         string const copy = rTemp;
483
484         // Split by next /
485         rTemp = split(rTemp, temp, '/');
486
487         if (temp == ".")
488                 return FileName::getcwd().absFilename() + '/' + rTemp;
489
490         if (temp == "~")
491                 return package().home_dir().absFilename() + '/' + rTemp;
492
493         if (temp == "..")
494                 return makeAbsPath(copy).absFilename();
495
496         // Don't know how to handle this
497         return copy;
498 }
499
500
501 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
502 string const replaceEnvironmentPath(string const & path)
503 {
504         // ${VAR} is defined as
505         // $\{[A-Za-z_][A-Za-z_0-9]*\}
506         static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
507
508         // $VAR is defined as:
509         // $\{[A-Za-z_][A-Za-z_0-9]*\}
510         static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
511
512         static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
513         static boost::regex envvar_re("(.*)" + envvar + "(.*)");
514         boost::smatch what;
515
516         string result = path;
517         while (1) {
518                 regex_match(result, what, envvar_br_re);
519                 if (!what[0].matched) {
520                         regex_match(result, what, envvar_re);
521                         if (!what[0].matched)
522                                 break;
523                 }
524                 result = what.str(1) + getEnv(what.str(2)) + what.str(3);
525         }
526         return result;
527 }
528
529
530 // Make relative path out of two absolute paths
531 docstring const makeRelPath(docstring const & abspath, docstring const & basepath)
532 // Makes relative path out of absolute path. If it is deeper than basepath,
533 // it's easy. If basepath and abspath share something (they are all deeper
534 // than some directory), it'll be rendered using ..'s. If they are completely
535 // different, then the absolute path will be used as relative path.
536 {
537         docstring::size_type const abslen = abspath.length();
538         docstring::size_type const baselen = basepath.length();
539
540         docstring::size_type i = os::common_path(abspath, basepath);
541
542         if (i == 0) {
543                 // actually no match - cannot make it relative
544                 return abspath;
545         }
546
547         // Count how many dirs there are in basepath above match
548         // and append as many '..''s into relpath
549         docstring buf;
550         docstring::size_type j = i;
551         while (j < baselen) {
552                 if (basepath[j] == '/') {
553                         if (j + 1 == baselen)
554                                 break;
555                         buf += "../";
556                 }
557                 ++j;
558         }
559
560         // Append relative stuff from common directory to abspath
561         if (abspath[i] == '/')
562                 ++i;
563         for (; i < abslen; ++i)
564                 buf += abspath[i];
565         // Remove trailing /
566         if (suffixIs(buf, '/'))
567                 buf.erase(buf.length() - 1);
568         // Substitute empty with .
569         if (buf.empty())
570                 buf = '.';
571         return buf;
572 }
573
574
575 // Append sub-directory(ies) to a path in an intelligent way
576 string const addPath(string const & path, string const & path_2)
577 {
578         string buf;
579         string const path2 = os::internal_path(path_2);
580
581         if (!path.empty() && path != "." && path != "./") {
582                 buf = os::internal_path(path);
583                 if (path[path.length() - 1] != '/')
584                         buf += '/';
585         }
586
587         if (!path2.empty()) {
588                 string::size_type const p2start = path2.find_first_not_of('/');
589                 string::size_type const p2end = path2.find_last_not_of('/');
590                 string const tmp = path2.substr(p2start, p2end - p2start + 1);
591                 buf += tmp + '/';
592         }
593         return buf;
594 }
595
596
597 string const changeExtension(string const & oldname, string const & extension)
598 {
599         string::size_type const last_slash = oldname.rfind('/');
600         string::size_type last_dot = oldname.rfind('.');
601         if (last_dot < last_slash && last_slash != string::npos)
602                 last_dot = string::npos;
603
604         string ext;
605         // Make sure the extension starts with a dot
606         if (!extension.empty() && extension[0] != '.')
607                 ext= '.' + extension;
608         else
609                 ext = extension;
610
611         return os::internal_path(oldname.substr(0, last_dot) + ext);
612 }
613
614
615 string const removeExtension(string const & name)
616 {
617         return changeExtension(name, string());
618 }
619
620
621 string const addExtension(string const & name, string const & extension)
622 {
623         if (!extension.empty() && extension[0] != '.')
624                 return name + '.' + extension;
625         return name + extension;
626 }
627
628
629 /// Return the extension of the file (not including the .)
630 string const getExtension(string const & name)
631 {
632         string::size_type const last_slash = name.rfind('/');
633         string::size_type const last_dot = name.rfind('.');
634         if (last_dot != string::npos &&
635             (last_slash == string::npos || last_dot > last_slash))
636                 return name.substr(last_dot + 1,
637                                    name.length() - (last_dot + 1));
638         else
639                 return string();
640 }
641
642
643 string const unzippedFileName(string const & zipped_file)
644 {
645         string const ext = getExtension(zipped_file);
646         if (ext == "gz" || ext == "z" || ext == "Z")
647                 return changeExtension(zipped_file, string());
648         return "unzipped_" + zipped_file;
649 }
650
651
652 FileName const unzipFile(FileName const & zipped_file, string const & unzipped_file)
653 {
654         FileName const tempfile = FileName(unzipped_file.empty() ?
655                 unzippedFileName(zipped_file.toFilesystemEncoding()) :
656                 unzipped_file);
657         // Run gunzip
658         string const command = "gunzip -c " +
659                 zipped_file.toFilesystemEncoding() + " > " +
660                 tempfile.toFilesystemEncoding();
661         Systemcall one;
662         one.startscript(Systemcall::Wait, command);
663         // test that command was executed successfully (anon)
664         // yes, please do. (Lgb)
665         return tempfile;
666 }
667
668
669 docstring const makeDisplayPath(string const & path, unsigned int threshold)
670 {
671         string str = path;
672
673         // If file is from LyXDir, display it as if it were relative.
674         string const system = package().system_support().absFilename();
675         if (prefixIs(str, system) && str != system)
676                 return from_utf8("[" + str.erase(0, system.length()) + "]");
677
678         // replace /home/blah with ~/
679         string const home = package().home_dir().absFilename();
680         if (!home.empty() && prefixIs(str, home))
681                 str = subst(str, home, "~");
682
683         if (str.length() <= threshold)
684                 return from_utf8(os::external_path(str));
685
686         string const prefix = ".../";
687         string temp;
688
689         while (str.length() > threshold)
690                 str = split(str, temp, '/');
691
692         // Did we shorten everything away?
693         if (str.empty()) {
694                 // Yes, filename itself is too long.
695                 // Pick the start and the end of the filename.
696                 str = onlyFilename(path);
697                 string const head = str.substr(0, threshold / 2 - 3);
698
699                 string::size_type len = str.length();
700                 string const tail =
701                         str.substr(len - threshold / 2 - 2, len - 1);
702                 str = head + "..." + tail;
703         }
704
705         return from_utf8(os::external_path(prefix + str));
706 }
707
708
709 bool readLink(FileName const & file, FileName & link)
710 {
711 #ifdef HAVE_READLINK
712         char linkbuffer[512];
713         // Should be PATH_MAX but that needs autconf support
714         string const encoded = file.toFilesystemEncoding();
715         int const nRead = ::readlink(encoded.c_str(),
716                                      linkbuffer, sizeof(linkbuffer) - 1);
717         if (nRead <= 0)
718                 return false;
719         linkbuffer[nRead] = '\0'; // terminator
720         link = makeAbsPath(linkbuffer, onlyPath(file.absFilename()));
721         return true;
722 #else
723         return false;
724 #endif
725 }
726
727
728 cmd_ret const runCommand(string const & cmd)
729 {
730         // FIXME: replace all calls to RunCommand with ForkedCall
731         // (if the output is not needed) or the code in ISpell.cpp
732         // (if the output is needed).
733
734         // One question is if we should use popen or
735         // create our own popen based on fork, exec, pipe
736         // of course the best would be to have a
737         // pstream (process stream), with the
738         // variants ipstream, opstream
739
740 #if defined (HAVE_POPEN)
741         FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
742 #elif defined (HAVE__POPEN)
743         FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
744 #else
745 #error No popen() function.
746 #endif
747
748         // (Claus Hentschel) Check if popen was succesful ;-)
749         if (!inf) {
750                 lyxerr << "RunCommand:: could not start child process" << endl;
751                 return make_pair(-1, string());
752         }
753
754         string ret;
755         int c = fgetc(inf);
756         while (c != EOF) {
757                 ret += static_cast<char>(c);
758                 c = fgetc(inf);
759         }
760
761 #if defined (HAVE_PCLOSE)
762         int const pret = pclose(inf);
763 #elif defined (HAVE__PCLOSE)
764         int const pret = _pclose(inf);
765 #else
766 #error No pclose() function.
767 #endif
768
769         if (pret == -1)
770                 perror("RunCommand:: could not terminate child process");
771
772         return make_pair(pret, ret);
773 }
774
775
776 FileName const findtexfile(string const & fil, string const & /*format*/)
777 {
778         /* There is no problem to extend this function too use other
779            methods to look for files. It could be setup to look
780            in environment paths and also if wanted as a last resort
781            to a recursive find. One of the easier extensions would
782            perhaps be to use the LyX file lookup methods. But! I am
783            going to implement this until I see some demand for it.
784            Lgb
785         */
786
787         // If the file can be found directly, we just return a
788         // absolute path version of it.
789         FileName const absfile(makeAbsPath(fil));
790         if (absfile.exists())
791                 return absfile;
792
793         // No we try to find it using kpsewhich.
794         // It seems from the kpsewhich manual page that it is safe to use
795         // kpsewhich without --format: "When the --format option is not
796         // given, the search path used when looking for a file is inferred
797         // from the name given, by looking for a known extension. If no
798         // known extension is found, the search path for TeX source files
799         // is used."
800         // However, we want to take advantage of the format sine almost all
801         // the different formats has environment variables that can be used
802         // to controll which paths to search. f.ex. bib looks in
803         // BIBINPUTS and TEXBIB. Small list follows:
804         // bib - BIBINPUTS, TEXBIB
805         // bst - BSTINPUTS
806         // graphic/figure - TEXPICTS, TEXINPUTS
807         // ist - TEXINDEXSTYLE, INDEXSTYLE
808         // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
809         // tex - TEXINPUTS
810         // tfm - TFMFONTS, TEXFONTS
811         // This means that to use kpsewhich in the best possible way we
812         // should help it by setting additional path in the approp. envir.var.
813         string const kpsecmd = "kpsewhich " + fil;
814
815         cmd_ret const c = runCommand(kpsecmd);
816
817         LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
818                  << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
819         if (c.first != -1)
820                 return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
821         else
822                 return FileName();
823 }
824
825
826 void removeAutosaveFile(string const & filename)
827 {
828         string a = onlyPath(filename);
829         a += '#';
830         a += onlyFilename(filename);
831         a += '#';
832         FileName const autosave(a);
833         if (autosave.exists())
834                 autosave.removeFile();
835 }
836
837
838 void readBB_lyxerrMessage(FileName const & file, bool & zipped,
839         string const & message)
840 {
841         LYXERR(Debug::GRAPHICS, "[readBB_from_PSFile] " << message);
842         // FIXME: Why is this func deleting a file? (Lgb)
843         if (zipped)
844                 file.removeFile();
845 }
846
847
848 string const readBB_from_PSFile(FileName const & file)
849 {
850         // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
851         // It seems that every command in the header has an own line,
852         // getline() should work for all files.
853         // On the other hand some plot programs write the bb at the
854         // end of the file. Than we have in the header:
855         // %%BoundingBox: (atend)
856         // In this case we must check the end.
857         bool zipped = file.isZippedFile();
858         FileName const file_ = zipped ? unzipFile(file) : file;
859         string const format = file_.guessFormatFromContents();
860
861         if (format != "eps" && format != "ps") {
862                 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
863                 return string();
864         }
865
866         static boost::regex bbox_re(
867                 "^%%BoundingBox:\\s*([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)");
868         ifstream is(file_.toFilesystemEncoding().c_str());
869         while (is) {
870                 string s;
871                 getline(is,s);
872                 boost::smatch what;
873                 if (regex_match(s, what, bbox_re)) {
874                         // Our callers expect the tokens in the string
875                         // separated by single spaces.
876                         // FIXME: change return type from string to something
877                         // sensible
878                         ostringstream os;
879                         os << what.str(1) << ' ' << what.str(2) << ' '
880                            << what.str(3) << ' ' << what.str(4);
881                         string const bb = os.str();
882                         readBB_lyxerrMessage(file_, zipped, bb);
883                         return bb;
884                 }
885         }
886         readBB_lyxerrMessage(file_, zipped, "no bb found");
887         return string();
888 }
889
890
891 int compare_timestamps(FileName const & file1, FileName const & file2)
892 {
893         // If the original is newer than the copy, then copy the original
894         // to the new directory.
895
896         int cmp = 0;
897         if (file1.exists() && file2.exists()) {
898                 double const tmp = difftime(file1.lastModified(), file2.lastModified());
899                 if (tmp != 0)
900                         cmp = tmp > 0 ? 1 : -1;
901
902         } else if (file1.exists()) {
903                 cmp = 1;
904         } else if (file2.exists()) {
905                 cmp = -1;
906         }
907
908         return cmp;
909 }
910
911
912 } //namespace support
913 } // namespace lyx