]> git.lyx.org Git - lyx.git/blobdiff - src/support/filetools.C
small changes read ChangeLog
[lyx.git] / src / support / filetools.C
index 1d3831c43ebc38c3ab451a097d33605e485869fd..52e642203bf262f1fe9295f5ee27aabd6d891ece 100644 (file)
 #include <cctype>
 
 #include <utility>
-using std::make_pair;
-using std::pair;
+#include <fstream>
+
+#ifdef HAVE_SSTREAM
+#include <sstream>
+#else
+#include <strstream>
+#endif
 
 #ifdef __GNUG__
 #pragma implementation "filetools.h"
@@ -52,6 +57,11 @@ using std::pair;
 # endif
 #endif
 
+using std::make_pair;
+using std::pair;
+using std::endl;
+using std::ifstream;
+
 extern string system_lyxdir;
 extern string build_lyxdir;
 extern string user_lyxdir;
@@ -64,12 +74,6 @@ bool IsLyXFilename(string const & filename)
 }
 
 
-bool IsSGMLFilename(string const & filename)
-{
-       return contains(filename, ".sgml");
-}
-
-
 // Substitutes spaces with underscores in filename (and path)
 string MakeLatexName(string const & file)
 {
@@ -95,9 +99,7 @@ string MakeLatexName(string const & file)
 // Substitutes spaces with underscores in filename (and path)
 string QuoteName(string const & name)
 {
-#ifdef WITH_WARNINGS
-#warning Add proper emx support here!
-#endif
+       // CHECK Add proper emx support here!
 #ifndef __EMX__
        return '\'' + name + '\'';
 #else
@@ -188,7 +190,7 @@ int IsDirWriteable (string const & path)
 // If path entry begins with $$User/, use user_lyxdir
 // Example: "$$User/doc;$$LyX/doc"
 string FileOpenSearch (string const & path, string const & name, 
-                       string const & ext)
+                      string const & ext)
 {
        string real_file, path_element;
        bool notfound = true;
@@ -202,13 +204,13 @@ string FileOpenSearch (string const & path, string const & name,
                path_element = subst(path_element, "$$User", user_lyxdir);
                
                real_file = FileSearch(path_element, name, ext);
-
+               
                if (real_file.empty()) {
-                 do {
-                   tmppath = split(tmppath, path_element, ';');
-                 } while(!tmppath.empty() && path_element.empty());
+                       do {
+                               tmppath = split(tmppath, path_element, ';');
+                       } while(!tmppath.empty() && path_element.empty());
                } else {
-                 notfound = false;
+                       notfound = false;
                }
        }
 #ifdef __EMX__
@@ -258,13 +260,13 @@ string LibFileSearch(string const & dir, string const & name,
                                     name, ext); 
        if (!fullname.empty())
                return fullname;
-
+       
        if (!build_lyxdir.empty()) 
                fullname = FileSearch(AddPath(build_lyxdir, dir), 
                                      name, ext);
        if (!fullname.empty())
                return fullname;
-
+       
        return FileSearch(AddPath(system_lyxdir, dir), name, ext);
 }
 
@@ -273,12 +275,12 @@ string i18nLibFileSearch(string const & dir, string const & name,
                         string const & ext)
 {
        string lang = token(string(GetEnv("LANG")), '_', 0);
-
+       
        if (lang.empty() || lang == "C")
                return LibFileSearch(dir, name, ext);
        else {
                string tmp = LibFileSearch(dir, lang + '_' + name,
-                                           ext);
+                                          ext);
                if (!tmp.empty())
                        return tmp;
                else
@@ -309,10 +311,9 @@ string GetEnvPath(string const & name)
 
 bool PutEnv(string const & envstr)
 {
-#ifdef WITH_WARNINGS
-#warning Look at and fix this.
-#endif
+       // CHECK Look at and fix this.
         // f.ex. what about error checking?
+
 #if HAVE_PUTENV
         // this leaks, but what can we do about it?
         //   Is doing a getenv() and a free() of the older value 
@@ -322,22 +323,27 @@ bool PutEnv(string const & envstr)
        // does not make a copy of the string. It is also not very wise to
        // put a string on the free store. If we have to leak we should do it
        // like this:
-       /*
        char * leaker = new char[envstr.length() + 1];
        envstr.copy(leaker, envstr.length());
        leaker[envstr.length()] = '\0';
-       int retval = putenv(const_cast<PUTENV_TYPE_ARG>(leaker));
-       */
+       int retval = lyx::putenv(leaker);
 
        // If putenv does not make a copy of the char const * this
        // is very dangerous. OTOH if it does take a copy this is the
        // best solution.
-       int retval = putenv(const_cast<PUTENV_TYPE_ARG>(envstr.c_str()));
+       // The  only implementation of putenv that I have seen does not
+       // allocate memory. _And_ after testing the putenv in glibc it
+       // seems that we need to make a copy of the string contents.
+       // I will enable the above.
+       //int retval = lyx::putenv(envstr.c_str());
 #else
 #ifdef HAVE_SETENV 
         string varname;
         string str = envstr.split(varname,'=');
         int retval = setenv(varname.c_str(), str.c_str(), true);
+#else
+       // No environment setting function. Can this happen?
+       int retval = 1; //return an error condition.
 #endif
 #endif
         return retval == 0;
@@ -353,6 +359,24 @@ bool PutEnvPath(string const & envstr)
 static
 int DeleteAllFilesInDir (string const & path)
 {
+       // I have decided that we will be using parts from the boost
+       // library. Check out http://www.boost.org/
+       // For directory access we will then use the directory_iterator.
+       // Then the code will be something like:
+       // directory_iterator dit(path.c_str());
+       // if (<some way to detect failure>) {
+       //         WriteFSAlert(_("Error! Cannot open directory:"), path);
+       //         return -1;
+       // }
+       // for (; dit != <someend>; ++dit) {
+       //         if ((*dit) == 2." || (*dit) == "..")
+       //                 continue;
+       //         string unlinkpath = AddName(path, temp);
+       //         if (remove(unlinkpath.c_str()))
+       //                 WriteFSAlert(_("Error! Could not remove file:"),
+       //                              unlinkpath);
+       // }
+       // return 0;
        DIR * dir = opendir(path.c_str());
        if (!dir) {
                WriteFSAlert (_("Error! Cannot open directory:"), path);
@@ -381,7 +405,7 @@ string CreateTmpDir (string const & tempdir, string const & mask)
 {
        string tmpfl = TmpFileName(tempdir, mask);
        
-       if ((tmpfl.empty()) || mkdir (tmpfl.c_str(), 0777)) {
+       if ((tmpfl.empty()) || lyx::mkdir (tmpfl.c_str(), 0777)) {
                WriteFSAlert(_("Error! Couldn't create temporary directory:"),
                             tempdir);
                return string();
@@ -421,7 +445,7 @@ int DestroyBufferTmpDir (string const & tmpdir)
 string CreateLyXTmpDir (string const & deflt)
 {
        if ((!deflt.empty()) && (deflt  != "/tmp")) {
-               if (mkdir(deflt.c_str(), 0777)) {
+               if (lyx::mkdir(deflt.c_str(), 0777)) {
 #ifdef __EMX__
                         Path p(user_lyxdir);
 #endif
@@ -456,7 +480,7 @@ bool createDirectory(string const & path, int permission)
                return false;
        }
 
-       if (mkdir(temp.c_str(), permission)) {
+       if (lyx::mkdir(temp.c_str(), permission)) {
                WriteFSAlert (_("Error! Couldn't create directory:"), temp);
                return false;
        }
@@ -697,6 +721,34 @@ string CleanupPath(string const & path)
 #endif
 }
 
+string GetFileContents(string const & fname) {
+       FileInfo finfo(fname);
+       if (finfo.exist()) {
+               ifstream ifs(fname.c_str());
+#ifdef HAVE_SSTREAM
+               std::ostringstream ofs;
+#else
+#warning The rumour goes that this might leak, but who really cares?
+               ostrstream ofs;
+#endif
+               if (ifs && ofs) {
+                       ofs << ifs.rdbuf();
+                       ifs.close();
+#ifdef HAVE_SSTREAM
+                       return ofs.str().c_str();
+#else
+                       ofs << '\0';
+                       char const * tmp = ofs.str();
+                       string ret(tmp);
+                       delete[] tmp;
+                       return ret;
+#endif
+               }
+       }
+       lyxerr << "LyX was not able to read file '" << fname << "'" << endl;
+       return string();
+}
+
 
 //
 // Search ${...} as Variable-Name inside the string and replace it with
@@ -736,7 +788,7 @@ string ReplaceEnvironmentPath(string const & path)
                if (!regexMatch(copy1, RegExp)) {
                        // No EndChar inside. So we are finished
                        result1 += CompareString + result0;
-                       result0.clear();
+                       result0.erase();
                        continue;
                }
 
@@ -831,7 +883,7 @@ string MakeRelPath(string const & abspath0, string const & basepath0)
        int j = i;
        while (j < baselen) {
                if (basepath[j] == '/') {
-                       if (j+1 == baselen) break;
+                       if (j + 1 == baselen) break;
                        buf += "../";
                }
                ++j;
@@ -880,30 +932,21 @@ string AddPath(string const & path, string const & path_2)
  Strips path off if no_path == true.
  If no extension on oldname, just appends.
  */
-string ChangeExtension(string const & oldname, string const & extension, 
-                       bool no_path) 
+string ChangeExtension(string const & oldname, string const & extension)
 {
        string::size_type last_slash = oldname.rfind('/');
-       string::size_type last_dot;
-       if (last_slash != string::npos)
-               last_dot = oldname.find('.', last_slash);
-       else
-               last_dot = oldname.rfind('.');
-
+       string::size_type last_dot = oldname.rfind('.');
+       if (last_dot < last_slash && last_slash != string::npos)
+               last_dot = string::npos;
+       
        string ext;
        // Make sure the extension starts with a dot
        if (!extension.empty() && extension[0] != '.')
                ext= '.' + extension;
        else
                ext = extension;
-       string ret_str;
-       if (no_path && last_slash != string::npos) {
-               ++last_slash; // step it
-               ret_str = oldname.substr(last_slash,
-                                        last_dot - last_slash) + ext;
-       } else
-               ret_str = oldname.substr(0, last_dot) + ext;
-       return CleanupPath(ret_str);
+
+       return CleanupPath(oldname.substr(0, last_dot) + ext);
 }
 
 
@@ -971,7 +1014,8 @@ bool LyXReadLink(string const & File, string & Link)
 
 
 typedef pair<int, string> cmdret;
-static cmdret do_popen(string const & cmd)
+static
+cmdret do_popen(string const & cmd)
 {
        // One question is if we should use popen or
        // create our own popen based on fork, exec, pipe
@@ -990,7 +1034,7 @@ static cmdret do_popen(string const & cmd)
 }
 
 
-string findtexfile(string const & fil, string const & format)
+string findtexfile(string const & fil, string const & /*format*/)
 {
        /* There is no problem to extend this function too use other
           methods to look for files. It could be setup to look
@@ -1001,15 +1045,33 @@ string findtexfile(string const & fil, string const & format)
           Lgb
        */
        
-        // If fil is a file with absolute path we just return it
-        if (AbsolutePath(fil)) return fil;
-       
-        // Check in the current dir.
-        if (FileInfo(OnlyFilename(fil)).exist())
-               return OnlyFilename(fil);
-       
+       // If the file can be found directly, we just return a
+       // absolute path version of it. 
+        if (FileInfo(fil).exist())
+               return MakeAbsPath(fil);
+
         // No we try to find it using kpsewhich.
-        string kpsecmd = "kpsewhich --format= " + format + " " + OnlyFilename(fil);
+       // It seems from the kpsewhich manual page that it is safe to use
+       // kpsewhich without --format: "When the --format option is not
+       // given, the search path used when looking for a file is inferred
+       // from the name given, by looking for a known extension. If no
+       // known extension is found, the search path for TeX source files
+       // is used."
+       // However, we want to take advantage of the format sine almost all
+       // the different formats has environment variables that can be used
+       // to controll which paths to search. f.ex. bib looks in
+       // BIBINPUTS and TEXBIB. Small list follows:
+       // bib - BIBINPUTS, TEXBIB
+       // bst - BSTINPUTS
+       // graphic/figure - TEXPICTS, TEXINPUTS
+       // ist - TEXINDEXSTYLE, INDEXSTYLE
+       // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
+       // tex - TEXINPUTS
+       // tfm - TFMFONTS, TEXFONTS
+       // This means that to use kpsewhich in the best possible way we
+       // should help it by setting additional path in the approp. envir.var.
+        string kpsecmd = "kpsewhich " + fil;
+
         cmdret c = do_popen(kpsecmd);
        
         lyxerr[Debug::LATEX] << "kpse status = " << c.first << "\n"