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)
33 // Which part of this is still necessary? (JMarc).
36 # define NAMLEN(dirent) strlen((dirent)->d_name)
38 # define dirent direct
39 # define NAMLEN(dirent) (dirent)->d_namlen
41 # include <sys/ndir.h>
51 extern string system_lyxdir;
52 extern string build_lyxdir;
53 extern string user_lyxdir;
54 extern string system_tempdir;
57 bool IsLyXFilename(string const & filename)
59 return contains(filename, ".lyx");
63 bool IsSGMLFilename(string const & filename)
65 return contains(filename, ".sgml");
69 // Substitutes spaces with underscores in filename (and path)
70 string SpaceLess(string const & file)
72 string name = OnlyFilename(file);
73 string path = OnlyPath(file);
75 for (string::size_type i = 0; i < name.length(); ++i) {
77 if (!isalnum(name[i]) && name[i] != '.')
80 string temp = AddName(path, name);
81 // Replace spaces with underscores, also in directory
82 // No!!! I checked it that it is not necessary.
83 // temp = subst(temp, ' ', '_');
89 /// Returns an unique name to be used as a temporary file.
90 string TmpFileName(string const & dir, string const & mask)
91 {// With all these temporary variables, it should be safe enough :-) (JMarc)
94 tmpdir = system_tempdir;
97 string tmpfl = AddName(tmpdir, mask);
99 // find a uniq postfix for the filename...
100 // using the pid, and...
101 tmpfl += tostr(getpid());
105 for (int a='a'; a<= 'z'; ++a)
106 for (int b='a'; b<= 'z'; ++b)
107 for (int c='a'; c<= 'z'; ++c) {
108 // if this is not enough I have no idea what
110 ret = tmpfl + char(a) + char(b) + char(c);
111 // check if the file exist
112 if (!fnfo.newFile(ret).exist())
115 lyxerr << "Not able to find a uniq tmpfile name." << endl;
120 // Is a file readable ?
121 bool IsFileReadable (string const & path)
124 if (file.isOK() && file.isRegular() && file.readable())
131 // Is a file read_only?
132 // return 1 read-write
134 // -1 error (doesn't exist, no access, anything else)
135 int IsFileWriteable (string const & path)
137 FilePtr fp(path, FilePtr::update);
139 if ((errno == EACCES) || (errno == EROFS)) {
140 //fp = FilePtr(path, FilePtr::read);
141 fp.reopen(path, FilePtr::read);
152 //returns 1: dir writeable
154 // -1: error- couldn't find out
155 int IsDirWriteable (string const & path)
157 string tmpfl = TmpFileName(path);
160 WriteFSAlert(_("LyX Internal Error!"),
161 _("Could not test if directory is writeable"));
164 FilePtr fp(tmpfl, FilePtr::truncate);
166 if (errno == EACCES) {
169 WriteFSAlert(_("LyX Internal Error!"),
170 _("Cannot open directory test file"));
175 if (remove (tmpfl.c_str())) {
176 WriteFSAlert(_("LyX Internal Error!"),
177 _("Created test file but cannot remove it?"));
184 // Uses a string of paths separated by ";"s to find a file to open.
185 // Can't cope with pathnames with a ';' in them. Returns full path to file.
186 // If path entry begins with $$LyX/, use system_lyxdir
187 // If path entry begins with $$User/, use user_lyxdir
188 // Example: "$$User/doc;$$LyX/doc"
189 string FileOpenSearch (string const & path, string const & name,
192 string real_file, path_element;
193 bool notfound = true;
194 string tmppath=split(path, path_element, ';');
196 while (notfound && !path_element.empty()) {
197 path_element = CleanupPath(path_element);
198 if (!suffixIs(path_element, '/'))
200 path_element = subst(path_element, "$$LyX", system_lyxdir);
201 path_element = subst(path_element, "$$User", user_lyxdir);
203 real_file = FileSearch(path_element, name, ext);
205 if (real_file.empty()) {
207 tmppath = split(tmppath, path_element, ';');
208 } while(!tmppath.empty() && path_element.empty());
214 if (ext.empty() && notfound) {
215 real_file = FileOpenSearch(path, name, "exe");
216 if (notfound) real_file = FileOpenSearch(path, name, "cmd");
223 // Returns the real name of file name in directory path, with optional
225 string FileSearch(string const & path, string const & name,
228 // if `name' is an absolute path, we ignore the setting of `path'
229 // Expand Environmentvariables in 'name'
230 string tmpname = ReplaceEnvironmentPath(name);
231 string fullname = MakeAbsPath(tmpname, path);
233 // search first without extension, then with it.
234 if (IsFileReadable(fullname))
236 else if (ext.empty())
238 else { // Is it not more reasonable to use ChangeExtension()? (SMiyata)
241 if (IsFileReadable(fullname))
249 // Search the file name.ext in the subdirectory dir of
251 // 2) build_lyxdir (if not empty)
253 string LibFileSearch(string const & dir, string const & name,
256 string fullname = FileSearch(AddPath(user_lyxdir,dir), name,
258 if (!fullname.empty())
261 if (!build_lyxdir.empty())
262 fullname = FileSearch(AddPath(build_lyxdir, dir),
264 if (!fullname.empty())
267 return FileSearch(AddPath(system_lyxdir,dir), name, ext);
271 string i18nLibFileSearch(string const & dir, string const & name,
274 string lang = token(string(GetEnv("LANG")), '_', 0);
276 if (lang.empty() || lang == "C")
277 return LibFileSearch(dir, name, ext);
279 string tmp = LibFileSearch(dir, lang + '_' + name,
284 return LibFileSearch(dir, name, ext);
289 string GetEnv(string const & envname)
291 // f.ex. what about error checking?
292 char const * const ch = getenv(envname.c_str());
293 string envstr = !ch ? "" : ch;
298 string GetEnvPath(string const & name)
301 string pathlist = subst(GetEnv(name), ':', ';');
303 string pathlist = subst(GetEnv(name), '\\', '/');
305 return strip(pathlist, ';');
309 bool PutEnv(string const & envstr)
312 #warning Look at and fix this.
314 // f.ex. what about error checking?
317 // this leaks, but what can we do about it?
318 // Is doing a getenv() and a free() of the older value
319 // a good idea? (JMarc)
320 retval = putenv((new string(envstr))->c_str());
324 string str = envstr.split(varname,'=');
325 retval = setenv(varname.c_str(), str.c_str(), true);
332 bool PutEnvPath(string const & envstr)
334 return PutEnv(envstr);
339 int DeleteAllFilesInDir (string const & path)
343 dir = opendir(path.c_str());
345 WriteFSAlert (_("Error! Cannot open directory:"), path);
348 while ((de = readdir(dir))) {
349 string temp = de->d_name;
350 if (temp=="." || temp=="..")
352 string unlinkpath = AddName (path, temp);
354 lyxerr.debug() << "Deleting file: " << unlinkpath << endl;
356 if (remove (unlinkpath.c_str()))
357 WriteFSAlert (_("Error! Could not remove file:"),
366 string CreateTmpDir (string const & tempdir, string const & mask)
368 string tmpfl = TmpFileName(tempdir, mask);
370 if ((tmpfl.empty()) || mkdir (tmpfl.c_str(), 0777)) {
371 WriteFSAlert(_("Error! Couldn't create temporary directory:"),
375 return MakeAbsPath(tmpfl);
380 int DestroyTmpDir (string const & tmpdir, bool Allfiles)
385 if (Allfiles && DeleteAllFilesInDir(tmpdir)) return -1;
386 if (rmdir(tmpdir.c_str())) {
387 WriteFSAlert(_("Error! Couldn't delete temporary directory:"),
395 string CreateBufferTmpDir (string const & pathfor)
397 return CreateTmpDir (pathfor, "lyx_bufrtmp");
401 int DestroyBufferTmpDir (string const & tmpdir)
403 return DestroyTmpDir (tmpdir, true);
407 string CreateLyXTmpDir (string const & deflt)
411 if ((!deflt.empty()) && (deflt != "/tmp")) {
412 if (mkdir (deflt.c_str(), 0777)) {
416 t = CreateTmpDir (deflt.c_str(), "lyx_tmp");
424 t = CreateTmpDir ("/tmp", "lyx_tmp");
430 int DestroyLyXTmpDir (string const & tmpdir)
432 return DestroyTmpDir (tmpdir, false); // Why false?
436 // Creates directory. Returns true if succesfull
437 bool createDirectory(string const & path, int permission)
439 string temp = strip(CleanupPath(path), '/');
442 WriteAlert(_("Internal error!"),
443 _("Call to createDirectory with invalid name"));
447 if (mkdir(temp.c_str(), permission)) {
448 WriteFSAlert (_("Error! Couldn't create directory:"), temp);
455 // Returns current working directory
458 int n = 256; // Assume path is less than 256 chars
460 char * tbuf = new char[n];
463 // Safe. Hopefully all getcwds behave this way!
464 while (((err = lyx::getcwd (tbuf, n)) == 0) && (errno == ERANGE)) {
465 // Buffer too small, double the buffersize and try again
471 if (err) result = tbuf;
477 // Strip filename from path name
478 string OnlyPath(string const & Filename)
480 // If empty filename, return empty
481 if (Filename.empty()) return Filename;
483 // Find last / or start of filename
484 string::size_type j = Filename.rfind('/');
485 if (j == string::npos)
487 return Filename.substr(0, j + 1);
491 // Convert relative path into absolute path based on a basepath.
492 // If relpath is absolute, just use that.
493 // If basepath is empty, use CWD as base.
494 string MakeAbsPath(string const & RelPath, string const & BasePath)
496 // checks for already absolute path
497 if (AbsolutePath(RelPath))
499 if(RelPath[0]!='/' && RelPath[0]!='\\')
503 // Copies given paths
504 string TempRel = CleanupPath(RelPath);
508 if (!BasePath.empty()) {
512 char * with_drive = new char[_MAX_PATH];
513 _abspath(with_drive, BasePath.c_str(), _MAX_PATH);
514 TempBase = with_drive;
520 if (AbsolutePath(TempRel))
521 return TempBase.substr(0, 2) + TempRel;
524 // Handle /./ at the end of the path
525 while(suffixIs(TempBase, "/./"))
526 TempBase.erase(TempBase.length() - 2);
528 // processes relative path
529 string RTemp = TempRel;
532 while (!RTemp.empty()) {
534 RTemp = split(RTemp, Temp, '/');
536 if (Temp==".") continue;
538 // Remove one level of TempBase
539 int i = TempBase.length()-2;
542 while (i > 0 && TempBase[i] != '/') --i;
546 while (i > 2 && TempBase[i] != '/') --i;
549 TempBase.erase(i, string::npos);
553 // Add this piece to TempBase
554 if (!suffixIs(TempBase, '/'))
560 // returns absolute path
565 // Correctly append filename to the pathname.
566 // If pathname is '.', then don't use pathname.
567 // Chops any path of filename.
568 string AddName(string const & path, string const & fname)
571 string basename = OnlyFilename(fname);
575 if (path != "." && path != "./" && !path.empty()) {
576 buf = CleanupPath(path);
577 if (!suffixIs(path, '/'))
581 return buf + basename;
585 // Strips path from filename
586 string OnlyFilename(string const & fname)
591 string::size_type j = fname.rfind('/');
592 if (j == string::npos) // no '/' in fname
596 return fname.substr(j + 1);
600 // Is a filename/path absolute?
601 bool AbsolutePath(string const & path)
604 return (!path.empty() && path[0] == '/');
606 return (!path.empty() && (path[0]=='/' || (isalpha((unsigned char) path[0]) && path.length()>1 && path[1]==':')));
611 // Create absolute path. If impossible, don't do anything
612 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
613 string ExpandPath(string const & path)
615 Assert(!path.empty()); // We don't allow empty path. (Lgb)
616 // checks for already absolute path
617 string RTemp = ReplaceEnvironmentPath(path);
618 if (AbsolutePath(RTemp))
625 RTemp=split(RTemp, Temp, '/');
628 return GetCWD() + '/' + RTemp;
629 } else if (Temp=="~") {
630 return GetEnvPath("HOME") + '/' + RTemp;
631 } else if (Temp=="..") {
632 return MakeAbsPath(copy);
634 // Don't know how to handle this
640 // Constracts path/../path
641 // Can't handle "../../" or "/../" (Asger)
642 string NormalizePath(string const & path)
648 if (AbsolutePath(path))
651 // Make implicit current directory explicit
654 while (!RTemp.empty()) {
656 RTemp = split(RTemp, Temp, '/');
660 } else if (Temp=="..") {
661 // Remove one level of TempBase
662 int i = TempBase.length()-2;
663 while (i>0 && TempBase[i] != '/')
665 if (i>=0 && TempBase[i] == '/')
666 TempBase.erase(i+1, string::npos);
670 TempBase += Temp + '/';
674 // returns absolute path
678 string CleanupPath(string const & path)
680 #ifdef __EMX__ /* SMiyata: This should fix searchpath bug. */
681 string temppath = subst(path, '\\', '/');
682 temppath = subst(temppath, "//", "/");
683 return lowercase(temppath);
684 #else // On unix, nothing to do
691 // Search ${...} as Variable-Name inside the string and replace it with
692 // the denoted environmentvariable
693 // Allow Variables according to
694 // variable := '$' '{' [A-Za-z_]{[A-Za-z_0-9]*} '}'
697 string ReplaceEnvironmentPath(string const & path)
699 Assert(!path.empty()); // We don't allow empty path. (Lgb)
701 // CompareChar: Environmentvariables starts with this character
702 // PathChar: Next path component start with this character
703 // while CompareChar found do:
704 // Split String with PathChar
705 // Search Environmentvariable
706 // if found: Replace Strings
708 const char CompareChar = '$';
709 const char FirstChar = '{';
710 const char EndChar = '}';
711 const char UnderscoreChar = '_';
712 string EndString; EndString += EndChar;
713 string FirstString; FirstString += FirstChar;
714 string CompareString; CompareString += CompareChar;
715 const string RegExp("*}*"); // Exist EndChar inside a String?
717 // first: Search for a '$' - Sign.
719 string result1; //(copy); // for split-calls
720 string result0 = split(path, result1, CompareChar);
721 while (!result0.empty()) {
722 string copy1(result0); // contains String after $
724 // Check, if there is an EndChar inside original String.
726 if (!regexMatch(copy1, RegExp)) {
727 // No EndChar inside. So we are finished
728 result1 += CompareString + result0;
734 string res0 = split(copy1, res1, EndChar);
735 // Now res1 holds the environmentvariable
736 // First, check, if Contents is ok.
737 if (res1.empty()) { // No environmentvariable. Continue Loop.
738 result1 += CompareString + FirstString;
742 // check contents of res1
743 const char * res1_contents = res1.c_str();
744 if (*res1_contents != FirstChar) {
745 // Again No Environmentvariable
746 result1 += CompareString;
750 // Check for variable names
751 // Situation ${} is detected as "No Environmentvariable"
752 const char * cp1 = res1_contents+1;
753 bool result = isalpha((unsigned char) *cp1) || (*cp1 == UnderscoreChar);
755 while (*cp1 && result) {
756 result = isalnum((unsigned char) *cp1) ||
757 (*cp1 == UnderscoreChar);
762 // no correct variable name
763 result1 += CompareString + res1 + EndString;
764 result0 = split(res0, res1, CompareChar);
769 string env = GetEnv(res1_contents+1);
771 // Congratulations. Environmentvariable found
774 result1 += CompareString + res1 + EndString;
777 result0 = split(res0, res1, CompareChar);
781 } // ReplaceEnvironmentPath
784 // Make relative path out of two absolute paths
785 string MakeRelPath(string const & abspath0, string const & basepath0)
786 // Makes relative path out of absolute path. If it is deeper than basepath,
787 // it's easy. If basepath and abspath share something (they are all deeper
788 // than some directory), it'll be rendered using ..'s. If they are completely
789 // different, then the absolute path will be used as relative path.
791 // This is a hack. It should probaly be done in another way. Lgb.
792 string abspath = CleanupPath(abspath0);
793 string basepath = CleanupPath(basepath0);
795 return "<unknown_path>";
797 const int abslen = abspath.length();
798 const int baselen = basepath.length();
800 // Find first different character
802 while (i < abslen && i < baselen && abspath[i] == basepath[i]) ++i;
805 if (i < abslen && i < baselen
806 || (i<abslen && abspath[i] != '/' && i==baselen)
807 || (i<baselen && basepath[i] != '/' && i==abslen))
809 if (i) --i; // here was the last match
810 while (i && abspath[i] != '/') --i;
814 // actually no match - cannot make it relative
818 // Count how many dirs there are in basepath above match
819 // and append as many '..''s into relpath
822 while (j < baselen) {
823 if (basepath[j] == '/') {
824 if (j+1 == baselen) break;
830 // Append relative stuff from common directory to abspath
831 if (abspath[i] == '/') ++i;
832 for (; i<abslen; ++i)
835 if (suffixIs(buf, '/'))
836 buf.erase(buf.length() - 1);
837 // Substitute empty with .
844 // Append sub-directory(ies) to a path in an intelligent way
845 string AddPath(string const & path, string const & path_2)
848 string path2 = CleanupPath(path_2);
850 if (!path.empty() && path != "." && path != "./") {
851 buf = CleanupPath(path);
852 if (path[path.length() - 1] != '/')
858 int p2start = path2.find_first_not_of('/');
859 //while (path2[p2start] == '/') ++p2start;
861 int p2end = path2.find_last_not_of('/');
862 //while (path2[p2end] == '/') --p2end;
864 string tmp = path2.substr(p2start, p2end - p2start + 1);
872 Change extension of oldname to extension.
873 Strips path off if no_path == true.
874 If no extension on oldname, just appends.
876 string ChangeExtension(string const & oldname, string const & extension,
879 string::size_type last_slash = oldname.rfind('/');
880 string::size_type last_dot;
881 if (last_slash != string::npos)
882 last_dot = oldname.find('.', last_slash);
884 last_dot = oldname.rfind('.');
887 // Make sure the extension starts with a dot
888 if (!extension.empty() && extension[0] != '.')
893 if (no_path && last_slash != string::npos) {
894 ++last_slash; // step it
895 ret_str = oldname.substr(last_slash,
896 last_dot - last_slash) + ext;
898 ret_str = oldname.substr(0, last_dot) + ext;
899 return CleanupPath(ret_str);
904 // Creates a nice compact path for displaying
905 string MakeDisplayPath (string const & path, unsigned int threshold)
907 const int l1 = path.length();
909 // First, we try a relative path compared to home
910 string home = GetEnvPath("HOME");
911 string relhome = MakeRelPath(path, home);
913 unsigned int l2 = relhome.length();
917 // If we backup from home or don't have a relative path,
918 // this try is no good
919 if (prefixIs(relhome, "../") || AbsolutePath(relhome)) {
920 // relative path was no good, just use the original path
927 // Is the path too long?
928 if (l2 > threshold) {
934 while (relhome.length() > threshold)
935 relhome = split(relhome, temp, '/');
937 // Did we shortend everything away?
938 if (relhome.empty()) {
939 // Yes, filename in itself is too long.
940 // Pick the start and the end of the filename.
941 relhome = OnlyFilename(path);
942 string head = relhome.substr(0, threshold/2 - 3);
944 l2 = relhome.length();
946 relhome.substr(l2 - threshold/2 - 2, l2 - 1);
947 relhome = head + "..." + tail;
950 return prefix + relhome;
953 bool LyXReadLink(string const & File, string & Link)
955 char LinkBuffer[512];
956 // Should be PATH_MAX but that needs autconf support
958 nRead = readlink(File.c_str(), LinkBuffer,sizeof(LinkBuffer)-1);
961 LinkBuffer[nRead] = 0;