2 filetools.C (former paths.C) - part of LyX project
3 General path-mangling functions
4 Copyright 1996 Ivan Schreter
5 Parts Copyright 1996 Dirk Niggemann
6 Parts Copyright 1985, 1990, 1993 Free Software Foundation, Inc.
7 Parts Copyright 1996 Asger Alstrup
11 lyx-filetool.C : tools functions for file/path handling
12 this file is part of LyX, the High Level Word Processor
13 Copyright 1995-1996, Matthias Ettrich and the LyX Team
22 #pragma implementation "filetools.h"
25 #include "filetools.h"
26 #include "lyx_gui_misc.h"
28 #include "support/path.h" // I know it's OS/2 specific (SMiyata)
32 // Which part of this is still necessary? (JMarc).
35 # define NAMLEN(dirent) strlen((dirent)->d_name)
37 # define dirent direct
38 # define NAMLEN(dirent) (dirent)->d_namlen
40 # include <sys/ndir.h>
50 extern string system_lyxdir;
51 extern string build_lyxdir;
52 extern string user_lyxdir;
53 extern string system_tempdir;
56 bool IsLyXFilename(string const & filename)
58 return contains(filename, ".lyx");
62 bool IsSGMLFilename(string const & filename)
64 return contains(filename, ".sgml");
68 // Substitutes spaces with underscores in filename (and path)
69 string SpaceLess(string const & file)
71 string name = OnlyFilename(file);
72 string path = OnlyPath(file);
74 for (string::size_type i = 0; i < name.length(); ++i) {
76 if (!isalnum(name[i]) && name[i] != '.')
79 string temp = AddName(path, name);
80 // Replace spaces with underscores, also in directory
81 // No!!! I checked it that it is not necessary.
82 // temp.subst(' ','_');
88 /// Returns an unique name to be used as a temporary file.
89 string TmpFileName(string const & dir, string const & mask)
90 {// With all these temporary variables, it should be safe enough :-) (JMarc)
93 tmpdir = system_tempdir;
96 string tmpfl = AddName(tmpdir, mask);
98 // find a uniq postfix for the filename...
99 // using the pid, and...
100 tmpfl += tostr(getpid());
104 for (int a='a'; a<= 'z'; ++a)
105 for (int b='a'; b<= 'z'; ++b)
106 for (int c='a'; c<= 'z'; ++c) {
107 // if this is not enough I have no idea what
109 ret = tmpfl + char(a) + char(b) + char(c);
110 // check if the file exist
111 if (!fnfo.newFile(ret).exist())
114 lyxerr << "Not able to find a uniq tmpfile name." << endl;
119 // Is a file readable ?
120 bool IsFileReadable (string const & path)
123 if (file.isOK() && file.isRegular() && file.readable())
130 // Is a file read_only?
131 // return 1 read-write
133 // -1 error (doesn't exist, no access, anything else)
134 int IsFileWriteable (string const & path)
136 FilePtr fp(path, FilePtr::update);
138 if ((errno == EACCES) || (errno == EROFS)) {
139 //fp = FilePtr(path, FilePtr::read);
140 fp.reopen(path, FilePtr::read);
151 //returns 1: dir writeable
153 // -1: error- couldn't find out
154 int IsDirWriteable (string const & path)
156 string tmpfl = TmpFileName(path);
159 WriteFSAlert(_("LyX Internal Error!"),
160 _("Could not test if directory is writeable"));
163 FilePtr fp(tmpfl, FilePtr::truncate);
165 if (errno == EACCES) {
168 WriteFSAlert(_("LyX Internal Error!"),
169 _("Cannot open directory test file"));
174 if (remove (tmpfl.c_str())) {
175 WriteFSAlert(_("LyX Internal Error!"),
176 _("Created test file but cannot remove it?"));
183 // Uses a string of paths separated by ";"s to find a file to open.
184 // Can't cope with pathnames with a ';' in them. Returns full path to file.
185 // If path entry begins with $$LyX/, use system_lyxdir
186 // If path entry begins with $$User/, use user_lyxdir
187 // Example: "$$User/doc;$$LyX/doc"
188 string FileOpenSearch (string const & path, string const & name,
191 string real_file, path_element;
192 bool notfound = true;
193 string tmppath=split(path, path_element, ';');
195 while (notfound && !path_element.empty()) {
196 path_element = CleanupPath(path_element);
197 if (!suffixIs(path_element, '/'))
199 path_element = subst(path_element, "$$LyX", system_lyxdir);
200 path_element = subst(path_element, "$$User", user_lyxdir);
202 real_file = FileSearch(path_element, name, ext);
204 if (real_file.empty()) {
206 tmppath = split(tmppath, path_element, ';');
207 } while(!tmppath.empty() && path_element.empty());
213 if (ext.empty() && notfound) {
214 real_file = FileOpenSearch(path, name, "exe");
215 if (notfound) real_file = FileOpenSearch(path, name, "cmd");
222 // Returns the real name of file name in directory path, with optional
224 string FileSearch(string const & path, string const & name,
227 // if `name' is an absolute path, we ignore the setting of `path'
228 // Expand Environmentvariables in 'name'
229 string tmpname = ReplaceEnvironmentPath(name);
230 string fullname = MakeAbsPath(tmpname, path);
232 // search first without extension, then with it.
233 if (IsFileReadable(fullname))
235 else if (ext.empty())
237 else { // Is it not more reasonable to use ChangeExtension()? (SMiyata)
240 if (IsFileReadable(fullname))
248 // Search the file name.ext in the subdirectory dir of
250 // 2) build_lyxdir (if not empty)
252 string LibFileSearch(string const & dir, string const & name,
255 string fullname = FileSearch(AddPath(user_lyxdir,dir), name,
257 if (!fullname.empty())
260 if (!build_lyxdir.empty())
261 fullname = FileSearch(AddPath(build_lyxdir, dir),
263 if (!fullname.empty())
266 return FileSearch(AddPath(system_lyxdir,dir), name, ext);
270 string i18nLibFileSearch(string const & dir, string const & name,
273 string lang = token(string(GetEnv("LANG")), '_', 0);
275 if (lang.empty() || lang == "C")
276 return LibFileSearch(dir, name, ext);
278 string tmp = LibFileSearch(dir, lang + '_' + name,
283 return LibFileSearch(dir, name, ext);
288 string GetEnv(string const & envname)
290 // f.ex. what about error checking?
291 char const * const ch = getenv(envname.c_str());
292 string envstr = !ch ? "" : ch;
297 string GetEnvPath(string const & name)
300 string pathlist = subst(GetEnv(name), ':', ';');
302 string pathlist = subst(GetEnv(name), '\\', '/');
304 return strip(pathlist, ';');
308 bool PutEnv(string const & envstr)
310 #warning Look at and fix this.
311 // f.ex. what about error checking?
314 // this leaks, but what can we do about it?
315 // Is doing a getenv() and a free() of the older value
316 // a good idea? (JMarc)
317 retval = putenv((new string(envstr))->c_str());
321 string str = envstr.split(varname,'=');
322 retval = setenv(varname.c_str(), str.c_str(), true);
329 bool PutEnvPath(string const & envstr)
331 string pathlist = envstr;
332 #warning Verify that this is correct.
334 pathlist.subst(':', ';');
335 pathlist.subst('/', '\\');
337 return PutEnv(pathlist);
342 int DeleteAllFilesInDir (string const & path)
346 dir = opendir(path.c_str());
348 WriteFSAlert (_("Error! Cannot open directory:"), path);
351 while ((de = readdir(dir))) {
352 string temp = de->d_name;
353 if (temp=="." || temp=="..")
355 string unlinkpath = AddName (path, temp);
357 lyxerr.debug() << "Deleting file: " << unlinkpath << endl;
359 if (remove (unlinkpath.c_str()))
360 WriteFSAlert (_("Error! Could not remove file:"),
369 string CreateTmpDir (string const & tempdir, string const & mask)
371 string tmpfl = TmpFileName(tempdir, mask);
373 if ((tmpfl.empty()) || mkdir (tmpfl.c_str(), 0777)) {
374 WriteFSAlert(_("Error! Couldn't create temporary directory:"),
378 return MakeAbsPath(tmpfl);
383 int DestroyTmpDir (string const & tmpdir, bool Allfiles)
385 if ((Allfiles) && (DeleteAllFilesInDir (tmpdir))) return -1;
386 if (rmdir(tmpdir.c_str())) {
388 if (errno == EBUSY) {
389 chdir(user_lyxdir.c_str()); // They are in the same drive.
390 if (!rmdir(tmpdir.c_str())) return 0;
393 WriteFSAlert(_("Error! Couldn't delete temporary directory:"),
401 string CreateBufferTmpDir (string const & pathfor)
403 return CreateTmpDir (pathfor, "lyx_bufrtmp");
407 int DestroyBufferTmpDir (string const & tmpdir)
409 return DestroyTmpDir (tmpdir, true);
413 string CreateLyXTmpDir (string const & deflt)
417 if ((!deflt.empty()) && (deflt != "/tmp")) {
418 if (mkdir (deflt.c_str(), 0777)) {
420 PathPush(user_lyxdir);
422 t = CreateTmpDir (deflt.c_str(), "lyx_tmp");
431 PathPush(user_lyxdir);
433 t = CreateTmpDir ("/tmp", "lyx_tmp");
442 int DestroyLyXTmpDir (string const & tmpdir)
444 return DestroyTmpDir (tmpdir, false); // Why false?
448 // Creates directory. Returns true if succesfull
449 bool createDirectory(string const & path, int permission)
451 string temp = strip(CleanupPath(path), '/');
454 WriteAlert(_("Internal error!"),
455 _("Call to createDirectory with invalid name"));
459 if (mkdir(temp.c_str(), permission)) {
460 WriteFSAlert (_("Error! Couldn't create directory:"), temp);
467 // Returns current working directory
470 int n = 256; // Assume path is less than 256 chars
472 char * tbuf = new char [n];
475 // Safe. Hopefully all getcwds behave this way!
476 while (((err = getcwd (tbuf, n)) == 0) && (errno == ERANGE)) {
477 // Buffer too small, double the buffersize and try again
483 if (err) result = tbuf;
489 // Strip filename from path name
490 string OnlyPath(string const & Filename)
492 // If empty filename, return empty
493 if (Filename.empty()) return Filename;
495 // Find last / or start of filename
496 string::size_type j = Filename.rfind('/');
499 return Filename.substr(0, j + 1);
503 // Convert relative path into absolute path based on a basepath.
504 // If relpath is absolute, just use that.
505 // If basepath is empty, use CWD as base.
506 string MakeAbsPath(string const & RelPath, string const & BasePath)
508 // checks for already absolute path
509 if (AbsolutePath(RelPath))
511 if(RelPath[0]!='/' || RelPath[0]!='\\')
515 // Copies given paths
516 string TempRel = CleanupPath(RelPath);
520 if (!BasePath.empty()) {
524 char * with_drive = new char[_MAX_PATH];
525 _abspath(with_drive, BasePath.c_str(), _MAX_PATH);
526 TempBase = with_drive;
532 if (AbsolutePath(TempRel))
533 return TempBase[0] + TempRel;
536 // Handle /./ at the end of the path
537 while(suffixIs(TempBase, "/./"))
538 TempBase.erase(TempBase.length() - 2);
540 // processes relative path
541 string RTemp = TempRel;
544 while (!RTemp.empty()) {
546 RTemp = split(RTemp, Temp, '/');
548 if (Temp==".") continue;
550 // Remove one level of TempBase
551 int i = TempBase.length()-2;
554 while (i>0 && TempBase[i] != '/') --i;
558 while (i>2 && TempBase[i] != '/') --i;
561 TempBase.erase(i, string::npos);
565 // Add this piece to TempBase
566 if (!suffixIs(TempBase, '/'))
572 // returns absolute path
577 // Correctly append filename to the pathname.
578 // If pathname is '.', then don't use pathname.
579 // Chops any path of filename.
580 string AddName(string const & path, string const & fname)
583 string basename = OnlyFilename(fname);
587 if (path != "." && path != "./" && !path.empty()) {
588 buf = CleanupPath(path);
589 if (!suffixIs(path, '/'))
593 return buf + basename;
597 // Strips path from filename
598 string OnlyFilename(string const & fname)
600 Assert(!fname.empty()); // We don't allow empty filename. (Lgb)
602 string::size_type j = fname.rfind('/');
603 if (j == string::npos) // no '/' in fname
607 return fname.substr(j + 1);
611 // Is a filename/path absolute?
612 bool AbsolutePath(string const & path)
615 return (!path.empty() && path[0] == '/');
617 return (!path.empty() && path[0]=='/' || (isalpha((unsigned char) path[0]) && path[1]==':'));
622 // Create absolute path. If impossible, don't do anything
623 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
624 string ExpandPath(string const & path)
626 Assert(!path.empty()); // We don't allow empty path. (Lgb)
627 // checks for already absolute path
628 string RTemp = ReplaceEnvironmentPath(path);
629 if (AbsolutePath(RTemp))
636 RTemp=split(RTemp, Temp, '/');
639 return GetCWD() + '/' + RTemp;
640 } else if (Temp=="~") {
641 return GetEnvPath("HOME") + '/' + RTemp;
642 } else if (Temp=="..") {
643 return MakeAbsPath(copy);
645 // Don't know how to handle this
651 // Constracts path/../path
652 // Can't handle "../../" or "/../" (Asger)
653 string NormalizePath(string const & path)
659 if (AbsolutePath(path))
662 // Make implicit current directory explicit
665 while (!RTemp.empty()) {
667 RTemp = split(RTemp, Temp, '/');
671 } else if (Temp=="..") {
672 // Remove one level of TempBase
673 int i = TempBase.length()-2;
674 while (i>0 && TempBase[i] != '/')
676 if (i>=0 && TempBase[i] == '/')
677 TempBase.erase(i+1, string::npos);
681 TempBase += Temp + '/';
685 // returns absolute path
689 string CleanupPath(string const & path)
691 #ifdef __EMX__ /* SMiyata: This should fix searchpath bug. */
692 string temppath(path);
693 subst(tmppath, '\\', '/');
694 subst(tmppath, "//", "/");
695 return lowercase(temppath);
696 #else // On unix, nothing to do
703 // Search ${...} as Variable-Name inside the string and replace it with
704 // the denoted environmentvariable
705 // Allow Variables according to
706 // variable := '$' '{' [A-Za-z_]{[A-Za-z_0-9]*} '}'
709 string ReplaceEnvironmentPath(string const & path)
711 Assert(!path.empty()); // We don't allow empty path. (Lgb)
713 // CompareChar: Environmentvariables starts with this character
714 // PathChar: Next path component start with this character
715 // while CompareChar found do:
716 // Split String with PathChar
717 // Search Environmentvariable
718 // if found: Replace Strings
720 const char CompareChar = '$';
721 const char FirstChar = '{';
722 const char EndChar = '}';
723 const char UnderscoreChar = '_';
724 string EndString; EndString += EndChar;
725 string FirstString; FirstString += FirstChar;
726 string CompareString; CompareString += CompareChar;
727 const string RegExp("*}*"); // Exist EndChar inside a String?
729 // first: Search for a '$' - Sign.
731 string result1; //(copy); // for split-calls
732 string result0 = split(path, result1, CompareChar);
733 while (!result0.empty()) {
734 string copy1(result0); // contains String after $
736 // Check, if there is an EndChar inside original String.
738 if (!regexMatch(copy1, RegExp)) {
739 // No EndChar inside. So we are finished
740 result1 += CompareString + result0;
746 string res0 = split(copy1, res1, EndChar);
747 // Now res1 holds the environmentvariable
748 // First, check, if Contents is ok.
749 if (res1.empty()) { // No environmentvariable. Continue Loop.
750 result1 += CompareString + FirstString;
754 // check contents of res1
755 const char * res1_contents = res1.c_str();
756 if (*res1_contents != FirstChar) {
757 // Again No Environmentvariable
758 result1 += CompareString;
762 // Check for variable names
763 // Situation ${} is detected as "No Environmentvariable"
764 const char * cp1 = res1_contents+1;
765 bool result = isalpha((unsigned char) *cp1) || (*cp1 == UnderscoreChar);
767 while (*cp1 && result) {
768 result = isalnum((unsigned char) *cp1) ||
769 (*cp1 == UnderscoreChar);
774 // no correct variable name
775 result1 += CompareString + res1 + EndString;
776 result0 = split(res0, res1, CompareChar);
781 string env = GetEnv(res1_contents+1);
783 // Congratulations. Environmentvariable found
786 result1 += CompareString + res1 + EndString;
789 result0 = split(res0, res1, CompareChar);
793 } // ReplaceEnvironmentPath
796 // Make relative path out of two absolute paths
797 string MakeRelPath(string const & abspath0, string const & basepath0)
798 // Makes relative path out of absolute path. If it is deeper than basepath,
799 // it's easy. If basepath and abspath share something (they are all deeper
800 // than some directory), it'll be rendered using ..'s. If they are completely
801 // different, then the absolute path will be used as relative path.
803 // This is a hack. It should probaly be done in another way. Lgb.
804 string abspath = CleanupPath(abspath0);
805 string basepath = CleanupPath(basepath0);
807 return "<unknown_path>";
809 const int abslen = abspath.length();
810 const int baselen = basepath.length();
812 // Find first different character
814 while (i < abslen && i < baselen && abspath[i] == basepath[i]) ++i;
817 if (i < abslen && i < baselen
818 || (i<abslen && abspath[i] != '/' && i==baselen)
819 || (i<baselen && basepath[i] != '/' && i==abslen))
821 if (i) --i; // here was the last match
822 while (i && abspath[i] != '/') --i;
826 // actually no match - cannot make it relative
830 // Count how many dirs there are in basepath above match
831 // and append as many '..''s into relpath
834 while (j < baselen) {
835 if (basepath[j] == '/') {
836 if (j+1 == baselen) break;
842 // Append relative stuff from common directory to abspath
843 if (abspath[i] == '/') ++i;
844 for (; i<abslen; ++i)
847 if (suffixIs(buf, '/'))
848 buf.erase(buf.length() - 1);
849 // Substitute empty with .
856 // Append sub-directory(ies) to a path in an intelligent way
857 string AddPath(string const & path, string const & path_2)
860 string path2 = CleanupPath(path_2);
862 if (!path.empty() && path != "." && path != "./") {
863 buf = CleanupPath(path);
864 if (path[path.length() - 1] != '/')
870 int p2start = path2.find_first_not_of('/');
871 //while (path2[p2start] == '/') ++p2start;
873 int p2end = path2.find_last_not_of('/');
874 //while (path2[p2end] == '/') --p2end;
876 string tmp = path2.substr(p2start, p2end - p2start + 1);
884 Change extension of oldname to extension.
885 Strips path off if no_path == true.
886 If no extension on oldname, just appends.
888 string ChangeExtension(string const & oldname, string const & extension,
891 string::size_type last_slash = oldname.rfind('/');
892 string::size_type last_dot;
893 if (last_slash != string::npos)
894 last_dot = oldname.find('.', last_slash);
896 last_dot = oldname.rfind('.');
899 // Make sure the extension starts with a dot
900 if (!extension.empty() && extension[0] != '.')
905 if (no_path && last_slash != string::npos) {
906 ++last_slash; // step it
907 ret_str = oldname.substr(last_slash,
908 last_dot - last_slash) + ext;
910 ret_str = oldname.substr(0, last_dot) + ext;
911 return CleanupPath(ret_str);
916 // Creates a nice compact path for displaying
917 string MakeDisplayPath (string const & path, unsigned int threshold)
919 const int l1 = path.length();
921 // First, we try a relative path compared to home
922 string home = GetEnvPath("HOME");
923 string relhome = MakeRelPath(path, home);
925 unsigned int l2 = relhome.length();
929 // If we backup from home or don't have a relative path,
930 // this try is no good
931 if (prefixIs(relhome, "../") || AbsolutePath(relhome)) {
932 // relative path was no good, just use the original path
939 // Is the path too long?
940 if (l2 > threshold) {
946 while (relhome.length() > threshold)
947 relhome = split(relhome, temp, '/');
949 // Did we shortend everything away?
950 if (relhome.empty()) {
951 // Yes, filename in itself is too long.
952 // Pick the start and the end of the filename.
953 relhome = OnlyFilename(path);
954 string head = relhome.substr(0, threshold/2 - 3);
956 l2 = relhome.length();
958 relhome.substr(l2 - threshold/2 - 2, l2 - 1);
959 relhome = head + "..." + tail;
962 return prefix + relhome;
965 bool LyXReadLink(string const & File, string & Link)
967 char LinkBuffer[512];
968 // Should be PATH_MAX but that needs autconf support
970 nRead = readlink(File.c_str(), LinkBuffer,sizeof(LinkBuffer)-1);
973 LinkBuffer[nRead] = 0;