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) {
76 name[i] &= 0x7f; // set 8th bit to 0
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.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)
311 #warning Look at and fix this.
313 // f.ex. what about error checking?
316 // this leaks, but what can we do about it?
317 // Is doing a getenv() and a free() of the older value
318 // a good idea? (JMarc)
319 retval = putenv((new string(envstr))->c_str());
323 string str = envstr.split(varname,'=');
324 retval = setenv(varname.c_str(), str.c_str(), true);
331 bool PutEnvPath(string const & envstr)
333 return PutEnv(envstr);
338 int DeleteAllFilesInDir (string const & path)
341 DIR * dir = opendir(path.c_str());
343 WriteFSAlert (_("Error! Cannot open directory:"), path);
346 while ((de = readdir(dir))) {
347 string temp = de->d_name;
348 if (temp=="." || temp=="..")
350 string unlinkpath = AddName (path, temp);
352 lyxerr.debug() << "Deleting file: " << unlinkpath << endl;
354 if (remove (unlinkpath.c_str()))
355 WriteFSAlert (_("Error! Could not remove file:"),
364 string CreateTmpDir (string const & tempdir, string const & mask)
366 string tmpfl = TmpFileName(tempdir, mask);
368 if ((tmpfl.empty()) || mkdir (tmpfl.c_str(), 0777)) {
369 WriteFSAlert(_("Error! Couldn't create temporary directory:"),
373 return MakeAbsPath(tmpfl);
378 int DestroyTmpDir (string const & tmpdir, bool Allfiles)
383 if (Allfiles && DeleteAllFilesInDir(tmpdir)) return -1;
384 if (rmdir(tmpdir.c_str())) {
385 WriteFSAlert(_("Error! Couldn't delete temporary directory:"),
393 string CreateBufferTmpDir (string const & pathfor)
395 return CreateTmpDir (pathfor, "lyx_bufrtmp");
399 int DestroyBufferTmpDir (string const & tmpdir)
401 return DestroyTmpDir (tmpdir, true);
405 string CreateLyXTmpDir (string const & deflt)
409 if ((!deflt.empty()) && (deflt != "/tmp")) {
410 if (mkdir (deflt.c_str(), 0777)) {
414 t = CreateTmpDir (deflt.c_str(), "lyx_tmp");
422 t = CreateTmpDir ("/tmp", "lyx_tmp");
428 int DestroyLyXTmpDir (string const & tmpdir)
430 return DestroyTmpDir (tmpdir, false); // Why false?
434 // Creates directory. Returns true if succesfull
435 bool createDirectory(string const & path, int permission)
437 string temp = strip(CleanupPath(path), '/');
440 WriteAlert(_("Internal error!"),
441 _("Call to createDirectory with invalid name"));
445 if (mkdir(temp.c_str(), permission)) {
446 WriteFSAlert (_("Error! Couldn't create directory:"), temp);
453 // Returns current working directory
456 int n = 256; // Assume path is less than 256 chars
458 char * tbuf = new char[n];
461 // Safe. Hopefully all getcwds behave this way!
462 while (((err = lyx::getcwd (tbuf, n)) == 0) && (errno == ERANGE)) {
463 // Buffer too small, double the buffersize and try again
469 if (err) result = tbuf;
475 // Strip filename from path name
476 string OnlyPath(string const & Filename)
478 // If empty filename, return empty
479 if (Filename.empty()) return Filename;
481 // Find last / or start of filename
482 string::size_type j = Filename.rfind('/');
483 if (j == string::npos)
485 return Filename.substr(0, j + 1);
489 // Convert relative path into absolute path based on a basepath.
490 // If relpath is absolute, just use that.
491 // If basepath is empty, use CWD as base.
492 string MakeAbsPath(string const & RelPath, string const & BasePath)
494 // checks for already absolute path
495 if (AbsolutePath(RelPath))
497 if(RelPath[0]!='/' && RelPath[0]!='\\')
501 // Copies given paths
502 string TempRel = CleanupPath(RelPath);
506 if (!BasePath.empty()) {
510 char * with_drive = new char[_MAX_PATH];
511 _abspath(with_drive, BasePath.c_str(), _MAX_PATH);
512 TempBase = with_drive;
518 if (AbsolutePath(TempRel))
519 return TempBase.substr(0, 2) + TempRel;
522 // Handle /./ at the end of the path
523 while(suffixIs(TempBase, "/./"))
524 TempBase.erase(TempBase.length() - 2);
526 // processes relative path
527 string RTemp = TempRel;
530 while (!RTemp.empty()) {
532 RTemp = split(RTemp, Temp, '/');
534 if (Temp==".") continue;
536 // Remove one level of TempBase
537 int i = TempBase.length()-2;
540 while (i > 0 && TempBase[i] != '/') --i;
544 while (i > 2 && TempBase[i] != '/') --i;
547 TempBase.erase(i, string::npos);
551 // Add this piece to TempBase
552 if (!suffixIs(TempBase, '/'))
558 // returns absolute path
563 // Correctly append filename to the pathname.
564 // If pathname is '.', then don't use pathname.
565 // Chops any path of filename.
566 string AddName(string const & path, string const & fname)
569 string basename = OnlyFilename(fname);
573 if (path != "." && path != "./" && !path.empty()) {
574 buf = CleanupPath(path);
575 if (!suffixIs(path, '/'))
579 return buf + basename;
583 // Strips path from filename
584 string OnlyFilename(string const & fname)
589 string::size_type j = fname.rfind('/');
590 if (j == string::npos) // no '/' in fname
594 return fname.substr(j + 1);
598 // Is a filename/path absolute?
599 bool AbsolutePath(string const & path)
602 return (!path.empty() && path[0] == '/');
604 return (!path.empty() && (path[0]=='/' || (isalpha((unsigned char) path[0]) && path.length()>1 && path[1]==':')));
609 // Create absolute path. If impossible, don't do anything
610 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
611 string ExpandPath(string const & path)
613 Assert(!path.empty()); // We don't allow empty path. (Lgb)
614 // checks for already absolute path
615 string RTemp = ReplaceEnvironmentPath(path);
616 if (AbsolutePath(RTemp))
623 RTemp=split(RTemp, Temp, '/');
626 return GetCWD() + '/' + RTemp;
627 } else if (Temp=="~") {
628 return GetEnvPath("HOME") + '/' + RTemp;
629 } else if (Temp=="..") {
630 return MakeAbsPath(copy);
632 // Don't know how to handle this
638 // Constracts path/../path
639 // Can't handle "../../" or "/../" (Asger)
640 string NormalizePath(string const & path)
646 if (AbsolutePath(path))
649 // Make implicit current directory explicit
652 while (!RTemp.empty()) {
654 RTemp = split(RTemp, Temp, '/');
658 } else if (Temp=="..") {
659 // Remove one level of TempBase
660 int i = TempBase.length()-2;
661 while (i>0 && TempBase[i] != '/')
663 if (i>=0 && TempBase[i] == '/')
664 TempBase.erase(i+1, string::npos);
668 TempBase += Temp + '/';
672 // returns absolute path
676 string CleanupPath(string const & path)
678 #ifdef __EMX__ /* SMiyata: This should fix searchpath bug. */
679 string temppath = subst(path, '\\', '/');
680 temppath = subst(temppath, "//", "/");
681 return lowercase(temppath);
682 #else // On unix, nothing to do
689 // Search ${...} as Variable-Name inside the string and replace it with
690 // the denoted environmentvariable
691 // Allow Variables according to
692 // variable := '$' '{' [A-Za-z_]{[A-Za-z_0-9]*} '}'
695 string ReplaceEnvironmentPath(string const & path)
697 Assert(!path.empty()); // We don't allow empty path. (Lgb)
699 // CompareChar: Environmentvariables starts with this character
700 // PathChar: Next path component start with this character
701 // while CompareChar found do:
702 // Split String with PathChar
703 // Search Environmentvariable
704 // if found: Replace Strings
706 const char CompareChar = '$';
707 const char FirstChar = '{';
708 const char EndChar = '}';
709 const char UnderscoreChar = '_';
710 string EndString; EndString += EndChar;
711 string FirstString; FirstString += FirstChar;
712 string CompareString; CompareString += CompareChar;
713 const string RegExp("*}*"); // Exist EndChar inside a String?
715 // first: Search for a '$' - Sign.
717 string result1; //(copy); // for split-calls
718 string result0 = split(path, result1, CompareChar);
719 while (!result0.empty()) {
720 string copy1(result0); // contains String after $
722 // Check, if there is an EndChar inside original String.
724 if (!regexMatch(copy1, RegExp)) {
725 // No EndChar inside. So we are finished
726 result1 += CompareString + result0;
732 string res0 = split(copy1, res1, EndChar);
733 // Now res1 holds the environmentvariable
734 // First, check, if Contents is ok.
735 if (res1.empty()) { // No environmentvariable. Continue Loop.
736 result1 += CompareString + FirstString;
740 // check contents of res1
741 const char * res1_contents = res1.c_str();
742 if (*res1_contents != FirstChar) {
743 // Again No Environmentvariable
744 result1 += CompareString;
748 // Check for variable names
749 // Situation ${} is detected as "No Environmentvariable"
750 const char * cp1 = res1_contents+1;
751 bool result = isalpha((unsigned char) *cp1) || (*cp1 == UnderscoreChar);
753 while (*cp1 && result) {
754 result = isalnum((unsigned char) *cp1) ||
755 (*cp1 == UnderscoreChar);
760 // no correct variable name
761 result1 += CompareString + res1 + EndString;
762 result0 = split(res0, res1, CompareChar);
767 string env = GetEnv(res1_contents+1);
769 // Congratulations. Environmentvariable found
772 result1 += CompareString + res1 + EndString;
775 result0 = split(res0, res1, CompareChar);
779 } // ReplaceEnvironmentPath
782 // Make relative path out of two absolute paths
783 string MakeRelPath(string const & abspath0, string const & basepath0)
784 // Makes relative path out of absolute path. If it is deeper than basepath,
785 // it's easy. If basepath and abspath share something (they are all deeper
786 // than some directory), it'll be rendered using ..'s. If they are completely
787 // different, then the absolute path will be used as relative path.
789 // This is a hack. It should probaly be done in another way. Lgb.
790 string abspath = CleanupPath(abspath0);
791 string basepath = CleanupPath(basepath0);
793 return "<unknown_path>";
795 const int abslen = abspath.length();
796 const int baselen = basepath.length();
798 // Find first different character
800 while (i < abslen && i < baselen && abspath[i] == basepath[i]) ++i;
803 if (i < abslen && i < baselen
804 || (i<abslen && abspath[i] != '/' && i==baselen)
805 || (i<baselen && basepath[i] != '/' && i==abslen))
807 if (i) --i; // here was the last match
808 while (i && abspath[i] != '/') --i;
812 // actually no match - cannot make it relative
816 // Count how many dirs there are in basepath above match
817 // and append as many '..''s into relpath
820 while (j < baselen) {
821 if (basepath[j] == '/') {
822 if (j+1 == baselen) break;
828 // Append relative stuff from common directory to abspath
829 if (abspath[i] == '/') ++i;
830 for (; i<abslen; ++i)
833 if (suffixIs(buf, '/'))
834 buf.erase(buf.length() - 1);
835 // Substitute empty with .
842 // Append sub-directory(ies) to a path in an intelligent way
843 string AddPath(string const & path, string const & path_2)
846 string path2 = CleanupPath(path_2);
848 if (!path.empty() && path != "." && path != "./") {
849 buf = CleanupPath(path);
850 if (path[path.length() - 1] != '/')
856 int p2start = path2.find_first_not_of('/');
858 int p2end = path2.find_last_not_of('/');
860 string tmp = path2.substr(p2start, p2end - p2start + 1);
868 Change extension of oldname to extension.
869 Strips path off if no_path == true.
870 If no extension on oldname, just appends.
872 string ChangeExtension(string const & oldname, string const & extension,
875 string::size_type last_slash = oldname.rfind('/');
876 string::size_type last_dot;
877 if (last_slash != string::npos)
878 last_dot = oldname.find('.', last_slash);
880 last_dot = oldname.rfind('.');
883 // Make sure the extension starts with a dot
884 if (!extension.empty() && extension[0] != '.')
889 if (no_path && last_slash != string::npos) {
890 ++last_slash; // step it
891 ret_str = oldname.substr(last_slash,
892 last_dot - last_slash) + ext;
894 ret_str = oldname.substr(0, last_dot) + ext;
895 return CleanupPath(ret_str);
900 // Creates a nice compact path for displaying
901 string MakeDisplayPath (string const & path, unsigned int threshold)
903 const int l1 = path.length();
905 // First, we try a relative path compared to home
906 string home = GetEnvPath("HOME");
907 string relhome = MakeRelPath(path, home);
909 unsigned int l2 = relhome.length();
913 // If we backup from home or don't have a relative path,
914 // this try is no good
915 if (prefixIs(relhome, "../") || AbsolutePath(relhome)) {
916 // relative path was no good, just use the original path
923 // Is the path too long?
924 if (l2 > threshold) {
930 while (relhome.length() > threshold)
931 relhome = split(relhome, temp, '/');
933 // Did we shortend everything away?
934 if (relhome.empty()) {
935 // Yes, filename in itself is too long.
936 // Pick the start and the end of the filename.
937 relhome = OnlyFilename(path);
938 string head = relhome.substr(0, threshold/2 - 3);
940 l2 = relhome.length();
942 relhome.substr(l2 - threshold/2 - 2, l2 - 1);
943 relhome = head + "..." + tail;
946 return prefix + relhome;
950 bool LyXReadLink(string const & File, string & Link)
952 char LinkBuffer[512];
953 // Should be PATH_MAX but that needs autconf support
955 nRead = readlink(File.c_str(), LinkBuffer,sizeof(LinkBuffer)-1);
958 LinkBuffer[nRead] = 0;