]> git.lyx.org Git - lyx.git/blobdiff - src/support/filetools.cpp
add onoff support for "inset-modify changetype xxx" in include inset
[lyx.git] / src / support / filetools.cpp
index 0d04782818f06c4afeec3a189a813a177a52a118..810694ec785c74ea8ce2fb7bcfea02bfc63790ba 100644 (file)
@@ -8,11 +8,11 @@
  * \author Ivan Schreter
  * \author Dirk Niggemann
  * \author Asger Alstrup
- * \author Lars Gullik Bjønnes
+ * \author Lars Gullik Bjønnes
  * \author Jean-Marc Lasgouttes
  * \author Angus Leeming
  * \author John Levon
- * \author Herbert Voß
+ * \author Herbert Voß
  *
  * Full author contact details are available in file CREDITS.
  *
 
 #include <config.h>
 
-#include "support/convert.h"
-#include "support/environment.h"
 #include "support/filetools.h"
-#include "support/fs_extras.h"
+
+#include "support/debug.h"
+#include "support/environment.h"
+#include "support/gettext.h"
 #include "support/lstrings.h"
-#include "support/lyxlib.h"
 #include "support/os.h"
 #include "support/Package.h"
 #include "support/Path.h"
 #include "support/Systemcall.h"
+#include "support/qstring_helpers.h"
 
-// FIXME Interface violation
-#include "gettext.h"
-#include "debug.h"
+#include <QDir>
 
-#include <boost/assert.hpp>
-#include <boost/filesystem/operations.hpp>
+#include "support/lassert.h"
 #include <boost/regex.hpp>
 
 #include <fcntl.h>
 #include <fstream>
 #include <sstream>
 
-using std::endl;
-using std::getline;
-using std::make_pair;
-using std::string;
-using std::ifstream;
-using std::ostringstream;
-using std::vector;
-using std::pair;
+using namespace std;
 
-namespace fs = boost::filesystem;
+#define USE_QPROCESS
 
 namespace lyx {
 namespace support {
@@ -113,12 +104,14 @@ string const latex_path(string const & original_path,
 
 
 // Substitutes spaces with underscores in filename (and path)
-string const makeLatexName(string const & file)
+FileName const makeLatexName(FileName const & file)
 {
-       string name = onlyFilename(file);
-       string const path = onlyPath(file);
+       string name = file.onlyFileName();
+       string const path = file.onlyPath().absFilename() + "/";
 
        // ok so we scan through the string twice, but who cares.
+       // FIXME: in Unicode time this will break for sure! There is
+       // a non-latin world out there...
        string const keep = "abcdefghijklmnopqrstuvwxyz"
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                "@!'()*+,-./0123456789:;<=>?[]`|";
@@ -127,7 +120,9 @@ string const makeLatexName(string const & file)
        while ((pos = name.find_first_not_of(keep, pos)) != string::npos)
                name[pos++] = '_';
 
-       return addName(path, name);
+       FileName latex_name(path + name);
+       latex_name.changeExtension(".tex");
+       return latex_name;
 }
 
 
@@ -142,9 +137,13 @@ string const quoteName(string const & name, quote_style style)
                // filenames to child processes if possible. We store them in
                // a python script instead, where we don't have these
                // limitations.
+#ifndef USE_QPROCESS
                return (os::shell() == os::UNIX) ?
                        '\'' + name + '\'':
                        '"' + name + '"';
+#else
+               return '"' + name + '"';
+#endif
        case quote_python:
                return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
                     + "\"";
@@ -192,37 +191,6 @@ FileName const fileOpenSearch(string const & path, string const & name,
 #endif
 
 
-/// Returns a vector of all files in directory dir having extension ext.
-vector<FileName> const dirList(FileName const & dir, string const & ext)
-{
-       // EXCEPTIONS FIXME. Rewrite needed when we turn on exceptions. (Lgb)
-       vector<FileName> dirlist;
-
-       if (!(dir.exists() && dir.isDirectory())) {
-               LYXERR(Debug::FILES)
-                       << "Directory \"" << dir
-                       << "\" does not exist to DirList." << endl;
-               return dirlist;
-       }
-
-       string extension;
-       if (!ext.empty() && ext[0] != '.')
-               extension += '.';
-       extension += ext;
-
-       string const encoded_dir = dir.toFilesystemEncoding();
-       fs::directory_iterator dit(encoded_dir);
-       fs::directory_iterator end;
-       for (; dit != end; ++dit) {
-               string const & fil = dit->leaf();
-               if (suffixIs(fil, extension))
-                       dirlist.push_back(FileName::fromFilesystemEncoding(
-                                       encoded_dir + '/' + fil));
-       }
-       return dirlist;
-}
-
-
 // Returns the real name of file name in directory path, with optional
 // extension ext.
 FileName const fileSearch(string const & path, string const & name,
@@ -233,16 +201,16 @@ FileName const fileSearch(string const & path, string const & name,
        string const tmpname = replaceEnvironmentPath(name);
        FileName fullname(makeAbsPath(tmpname, path));
        // search first without extension, then with it.
-       if (fullname.isReadable())
+       if (fullname.isReadableFile())
                return fullname;
        if (ext.empty())
                // We are done.
-               return mode == allow_unreadable ? fullname : FileName();
+               return mode == may_not_exist ? fullname : FileName();
        // Only add the extension if it is not already the extension of
        // fullname.
        if (getExtension(fullname.absFilename()) != ext)
                fullname = FileName(addExtension(fullname.absFilename(), ext));
-       if (fullname.isReadable() || mode == allow_unreadable)
+       if (fullname.isReadableFile() || mode == may_not_exist)
                return fullname;
        return FileName();
 }
@@ -277,7 +245,7 @@ FileName const i18nLibFileSearch(string const & dir, string const & name,
           variable. But we don't use the value if the currently
           selected locale is the C locale. This is a GNU extension.
 
-          Otherwise, w use a trick to guess what gettext has done:
+          Otherwise, w use a trick to guess what support/gettext.has done:
           each po file is able to tell us its name. (JMarc)
        */
 
@@ -355,62 +323,37 @@ string const libScriptSearch(string const & command_in, quote_style style)
 
 static FileName createTmpDir(FileName const & tempdir, string const & mask)
 {
-       LYXERR(Debug::FILES)
-               << "createTmpDir: tempdir=`" << tempdir << "'\n"
-               << "createTmpDir:    mask=`" << mask << '\'' << endl;
+       LYXERR(Debug::FILES, "createTmpDir: tempdir=`" << tempdir << "'\n"
+               << "createTmpDir:    mask=`" << mask << '\'');
 
-       FileName const tmpfl(tempName(tempdir, mask));
-       // lyx::tempName actually creates a file to make sure that it
-       // stays unique. So we have to delete it before we can create
-       // a dir with the same name. Note also that we are not thread
-       // safe because of the gap between unlink and mkdir. (Lgb)
-       unlink(tmpfl);
+       FileName const tmpfl = FileName::tempName(tempdir, mask);
 
-       if (tmpfl.empty() || mkdir(tmpfl, 0700)) {
-               lyxerr << "LyX could not create the temporary directory '"
-                      << tmpfl << "'" << endl;
+       if (tmpfl.empty() || !tmpfl.createDirectory(0700)) {
+               LYXERR0("LyX could not create temporary directory in " << tempdir
+                       << "'");
                return FileName();
        }
 
        return tmpfl;
 }
 
-string const createBufferTmpDir()
-{
-       static int count;
-       // We are in our own directory.  Why bother to mangle name?
-       // In fact I wrote this code to circumvent a problematic behaviour
-       // (bug?) of EMX mkstemp().
-       string const tmpfl =
-               package().temp_dir().absFilename() + "/lyx_tmpbuf" +
-               convert<string>(count++);
-
-       if (mkdir(FileName(tmpfl), 0777)) {
-               lyxerr << "LyX could not create the temporary directory '"
-                      << tmpfl << "'" << endl;
-               return string();
-       }
-       return tmpfl;
-}
-
 
 FileName const createLyXTmpDir(FileName const & deflt)
 {
-       if (!deflt.empty() && deflt.absFilename() != "/tmp") {
-               if (mkdir(deflt, 0777)) {
-                       if (deflt.isDirWritable()) {
-                               // deflt could not be created because it
-                               // did exist already, so let's create our own
-                               // dir inside deflt.
-                               return createTmpDir(deflt, "lyx_tmpdir");
-                       } else {
-                               // some other error occured.
-                               return createTmpDir(FileName("/tmp"), "lyx_tmpdir");
-                       }
-               } else
-                       return deflt;
+       if (deflt.empty() || deflt == package().system_temp_dir())
+               return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
+
+       if (deflt.createDirectory(0777)) 
+               return deflt;
+
+       if (deflt.isDirWritable()) {
+               // deflt could not be created because it
+               // did exist already, so let's create our own
+               // dir inside deflt.
+               return createTmpDir(deflt, "lyx_tmpdir");
        } else {
-               return createTmpDir(FileName("/tmp"), "lyx_tmpdir");
+               // some other error occured.
+               return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
        }
 }
 
@@ -423,7 +366,7 @@ string const onlyPath(string const & filename)
                return filename;
 
        // Find last / or start of filename
-       string::size_type j = filename.rfind('/');
+       size_t j = filename.rfind('/');
        return j == string::npos ? "./" : filename.substr(0, j + 1);
 }
 
@@ -431,10 +374,14 @@ string const onlyPath(string const & filename)
 // Convert relative path into absolute path based on a basepath.
 // If relpath is absolute, just use that.
 // If basepath is empty, use CWD as base.
+// Note that basePath can be a relative path, in the sense that it may
+// not begin with "/" (e.g.), but it should NOT contain such constructs
+// as "/../".
+// FIXME It might be nice if the code didn't simply assume that.
 FileName const makeAbsPath(string const & relPath, string const & basePath)
 {
        // checks for already absolute path
-       if (os::is_absolute_path(relPath))
+       if (FileName::isAbsolute(relPath))
                return FileName(relPath);
 
        // Copies given paths
@@ -444,10 +391,10 @@ FileName const makeAbsPath(string const & relPath, string const & basePath)
 
        string tempBase;
 
-       if (os::is_absolute_path(basePath))
+       if (FileName::isAbsolute(basePath))
                tempBase = basePath;
        else
-               tempBase = addPath(getcwd().absFilename(), basePath);
+               tempBase = addPath(FileName::getcwd().absFilename(), basePath);
 
        // Handle /./ at the end of the path
        while (suffixIs(tempBase, "/./"))
@@ -457,6 +404,15 @@ FileName const makeAbsPath(string const & relPath, string const & basePath)
        string rTemp = tempRel;
        string temp;
 
+       // Check for a leading "~"
+       // Split by first /
+       rTemp = split(rTemp, temp, '/');
+       if (temp == "~") {
+               tempBase = package().home_dir().absFilename();
+               tempRel = rTemp;
+       }
+
+       rTemp = tempRel;
        while (!rTemp.empty()) {
                // Split by next /
                rTemp = split(rTemp, temp, '/');
@@ -464,15 +420,22 @@ FileName const makeAbsPath(string const & relPath, string const & basePath)
                if (temp == ".") continue;
                if (temp == "..") {
                        // Remove one level of TempBase
-                       string::difference_type i = tempBase.length() - 2;
-                       if (i < 0)
-                               i = 0;
+                       if (tempBase.length() <= 1) {
+                               //this is supposed to be an absolute path, so...
+                               tempBase = "/";
+                               continue;
+                       }
+                       //erase a trailing slash if there is one
+                       if (suffixIs(tempBase, "/"))
+                               tempBase.erase(tempBase.length() - 1, string::npos);
+
+                       string::size_type i = tempBase.length() - 1;
                        while (i > 0 && tempBase[i] != '/')
                                --i;
                        if (i > 0)
                                tempBase.erase(i, string::npos);
                        else
-                               tempBase += '/';
+                               tempBase = '/';
                } else if (temp.empty() && !rTemp.empty()) {
                                tempBase = os::current_root() + rTemp;
                                rTemp.erase();
@@ -485,7 +448,7 @@ FileName const makeAbsPath(string const & relPath, string const & basePath)
        }
 
        // returns absolute path
-       return FileName(os::internal_path(tempBase));
+       return FileName(tempBase);
 }
 
 
@@ -522,20 +485,13 @@ string const onlyFilename(string const & fname)
 }
 
 
-/// Returns true is path is absolute
-bool absolutePath(string const & path)
-{
-       return os::is_absolute_path(path);
-}
-
-
 // Create absolute path. If impossible, don't do anything
 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
 string const expandPath(string const & path)
 {
        // checks for already absolute path
        string rTemp = replaceEnvironmentPath(path);
-       if (os::is_absolute_path(rTemp))
+       if (FileName::isAbsolute(rTemp))
                return rTemp;
 
        string temp;
@@ -545,7 +501,7 @@ string const expandPath(string const & path)
        rTemp = split(rTemp, temp, '/');
 
        if (temp == ".")
-               return getcwd().absFilename() + '/' + rTemp;
+               return FileName::getcwd().absFilename() + '/' + rTemp;
 
        if (temp == "~")
                return package().home_dir().absFilename() + '/' + rTemp;
@@ -558,24 +514,6 @@ string const expandPath(string const & path)
 }
 
 
-// Normalize a path. Constracts path/../path
-// Can't handle "../../" or "/../" (Asger)
-// Also converts paths like /foo//bar ==> /foo/bar
-string const normalizePath(string const & path)
-{
-       // Normalize paths like /foo//bar ==> /foo/bar
-       static boost::regex regex("/{2,}");
-       string const tmppath = boost::regex_merge(path, regex, "/");
-
-       fs::path const npath = fs::path(tmppath, fs::no_check).normalize();
-
-       if (!npath.is_complete())
-               return "./" + npath.string() + '/';
-
-       return npath.string() + '/';
-}
-
-
 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
 string const replaceEnvironmentPath(string const & path)
 {
@@ -590,16 +528,23 @@ string const replaceEnvironmentPath(string const & path)
        static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
        static boost::regex envvar_re("(.*)" + envvar + "(.*)");
        boost::smatch what;
-
-       string result = path;
+       string result;
+       string remaining = path;
        while (1) {
-               regex_match(result, what, envvar_br_re);
+               regex_match(remaining, what, envvar_br_re);
                if (!what[0].matched) {
-                       regex_match(result, what, envvar_re);
-                       if (!what[0].matched)
+                       regex_match(remaining, what, envvar_re);
+                       if (!what[0].matched) {
+                               result += remaining;
                                break;
+                       }
                }
-               result = what.str(1) + getEnv(what.str(2)) + what.str(3);
+               string env_var = getEnv(what.str(2));
+               if (!env_var.empty())
+                       result += what.str(1) + env_var;
+               else
+                       result += what.str(1) + "$" + what.str(2);
+               remaining = what.str(3);
        }
        return result;
 }
@@ -723,7 +668,7 @@ string const unzippedFileName(string const & zipped_file)
        string const ext = getExtension(zipped_file);
        if (ext == "gz" || ext == "z" || ext == "Z")
                return changeExtension(zipped_file, string());
-       return "unzipped_" + zipped_file;
+       return onlyPath(zipped_file) + "unzipped_" + onlyFilename(zipped_file);
 }
 
 
@@ -868,7 +813,7 @@ FileName const findtexfile(string const & fil, string const & /*format*/)
        if (absfile.exists())
                return absfile;
 
-       // No we try to find it using kpsewhich.
+       // Now we try to find it using kpsewhich.
        // 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
@@ -892,37 +837,22 @@ FileName const findtexfile(string const & fil, string const & /*format*/)
 
        cmd_ret const c = runCommand(kpsecmd);
 
-       LYXERR(Debug::LATEX) << "kpse status = " << c.first << '\n'
-                << "kpse result = `" << rtrim(c.second, "\n\r")
-                << '\'' << endl;
+       LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
+                << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
        if (c.first != -1)
-               return FileName(os::internal_path(rtrim(to_utf8(from_filesystem8bit(c.second)),
-                                                       "\n\r")));
+               return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
        else
                return FileName();
 }
 
 
-void removeAutosaveFile(string const & filename)
-{
-       string a = onlyPath(filename);
-       a += '#';
-       a += onlyFilename(filename);
-       a += '#';
-       FileName const autosave(a);
-       if (autosave.exists())
-               unlink(autosave);
-}
-
-
 void readBB_lyxerrMessage(FileName const & file, bool & zipped,
        string const & message)
 {
-       LYXERR(Debug::GRAPHICS) << "[readBB_from_PSFile] "
-               << message << std::endl;
+       LYXERR(Debug::GRAPHICS, "[readBB_from_PSFile] " << message);
        // FIXME: Why is this func deleting a file? (Lgb)
        if (zipped)
-               unlink(file);
+               file.removeFile();
 }
 
 
@@ -946,7 +876,7 @@ string const readBB_from_PSFile(FileName const & file)
 
        static boost::regex bbox_re(
                "^%%BoundingBox:\\s*([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)");
-       std::ifstream is(file_.toFilesystemEncoding().c_str());
+       ifstream is(file_.toFilesystemEncoding().c_str());
        while (is) {
                string s;
                getline(is,s);
@@ -989,5 +919,6 @@ int compare_timestamps(FileName const & file1, FileName const & file2)
        return cmp;
 }
 
+
 } //namespace support
 } // namespace lyx