mirror of
https://github.com/mawww/kakoune.git
synced 2024-12-18 17:02:06 +03:00
File: parse_filename function which handle ~ and environment variable in filenames
This commit is contained in:
parent
589b8e68bb
commit
73a8950e73
34
src/file.cc
34
src/file.cc
@ -13,6 +13,40 @@
|
||||
namespace Kakoune
|
||||
{
|
||||
|
||||
bool isidentifier(char c)
|
||||
{
|
||||
return std::isalnum(c) or c == '_';
|
||||
}
|
||||
|
||||
std::string parse_filename(const std::string& filename)
|
||||
{
|
||||
if (filename.length() > 2 and filename[0] == '~' and filename[1] == '/')
|
||||
return parse_filename("$HOME/" + filename.substr(2));
|
||||
|
||||
size_t pos = 0;
|
||||
std::string result;
|
||||
for (size_t i = 0; i < filename.length(); ++i)
|
||||
{
|
||||
if (filename[i] == '$' and (i == 0 or filename[i-1] != '\\'))
|
||||
{
|
||||
result += filename.substr(pos, i - pos);
|
||||
size_t end = i+1;
|
||||
while (end != filename.length() and isidentifier(filename[end]))
|
||||
++end;
|
||||
std::string var_name = filename.substr(i+1, end - i - 1);
|
||||
const char* var_value = getenv(var_name.c_str());
|
||||
if (var_value)
|
||||
result += var_value;
|
||||
|
||||
pos = end;
|
||||
}
|
||||
}
|
||||
if (pos != filename.length())
|
||||
result += filename.substr(pos);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string read_file(const std::string& filename)
|
||||
{
|
||||
int fd = open(filename.c_str(), O_RDONLY);
|
||||
|
@ -23,6 +23,10 @@ struct file_not_found : file_access_error
|
||||
};
|
||||
|
||||
class Buffer;
|
||||
|
||||
// parse ~/ and $env values in filename and returns the translated filename
|
||||
std::string parse_filename(const std::string& filename);
|
||||
|
||||
std::string read_file(const std::string& filename);
|
||||
Buffer* create_buffer_from_file(const std::string& filename);
|
||||
void write_buffer_to_file(const Buffer& buffer, const std::string& filename);
|
||||
|
@ -535,7 +535,8 @@ void write_buffer(const CommandParameters& params, const Context& context)
|
||||
throw wrong_argument_count();
|
||||
|
||||
Buffer& buffer = context.window().buffer();
|
||||
std::string filename = params.empty() ? buffer.name() : params[0];
|
||||
std::string filename = params.empty() ? buffer.name()
|
||||
: parse_filename(params[0]);
|
||||
|
||||
write_buffer_to_file(buffer, filename);
|
||||
buffer.notify_saved();
|
||||
@ -695,7 +696,7 @@ void exec_commands_in_file(const CommandParameters& params,
|
||||
if (params.size() != 1)
|
||||
throw wrong_argument_count();
|
||||
|
||||
std::string file_content = read_file(params[0]);
|
||||
std::string file_content = read_file(parse_filename(params[0]));
|
||||
CommandManager& cmd_manager = CommandManager::instance();
|
||||
|
||||
size_t pos = 0;
|
||||
|
Loading…
Reference in New Issue
Block a user