From: Thibaut Cuvelier Date: Tue, 19 Oct 2021 00:30:47 +0000 (+0200) Subject: Refactor file-name sanitisation. X-Git-Url: https://git.lyx.org/gitweb/?a=commitdiff_plain;h=0b5e94072313045b1adf53dd88d45a78e460bfbe;p=features.git Refactor file-name sanitisation. For now, this is only used in FileName, because it does not change the semantics of DocFileName::mangledFileName. --- diff --git a/src/support/FileName.cpp b/src/support/FileName.cpp index 5d70dd2b6c..8ad7e00fa0 100644 --- a/src/support/FileName.cpp +++ b/src/support/FileName.cpp @@ -977,18 +977,7 @@ string DocFileName::mangledFileName(string const & dir, bool use_counter, bool e mname = "export_" + onlyFileName() + "_" + toHexHash(mname); // The mangled name must be a valid LaTeX name. - // The list of characters to keep is probably over-restrictive, - // but it is not really a problem. - // Apart from non-ASCII characters, at least the following characters - // are forbidden: '/', '.', ' ', and ':'. - // On windows it is not possible to create files with '<', '>' or '?' - // in the name. - static string const keep = "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "+-0123456789;="; - string::size_type pos = 0; - while ((pos = mname.find_first_not_of(keep, pos)) != string::npos) - mname[pos++] = '_'; + mname = sanitizeFileName(mname); // Add the extension back on mname = support::changeExtension(mname, getExtension(name)); diff --git a/src/support/filetools.cpp b/src/support/filetools.cpp index d022115179..cfb245cd54 100644 --- a/src/support/filetools.cpp +++ b/src/support/filetools.cpp @@ -1325,5 +1325,26 @@ std::string toHexHash(const std::string & str) return fromqstr(QString(hash.toHex())); } + +std::string sanitizeFileName(const std::string & str) +{ + // The list of characters to keep is probably over-restrictive, + // but it is not really a problem. + // Apart from non-ASCII characters, at least the following characters + // are forbidden: '/', '.', ' ', and ':'. + // On windows it is not possible to create files with '<', '>' or '?' + // in the name. + static std::string const keep = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "+-0123456789;="; + + std::string name = str; + string::size_type pos = 0; + while ((pos = name.find_first_not_of(keep, pos)) != string::npos) + name[pos++] = '_'; + + return name; +} + } // namespace support } // namespace lyx diff --git a/src/support/filetools.h b/src/support/filetools.h index 84b2378572..404dec210f 100644 --- a/src/support/filetools.h +++ b/src/support/filetools.h @@ -354,6 +354,10 @@ void fileUnlock(int fd, const char * lock_file); */ std::string toHexHash(const std::string & str); +/// Replace non-ASCII characters to ensure that the string can be used as a +/// file name on all platforms and as a LaTeX name. +std::string sanitizeFileName(const std::string & str); + } // namespace support } // namespace lyx