Cleanup io calls and add cd function.

This commit is contained in:
2026-08-31 10:11:29 +01:00
parent a996beb4aa
commit e44267a6fe
11 changed files with 157 additions and 118 deletions
+40
View File
@@ -0,0 +1,40 @@
#include "bed.h"
#include "internal/functions/functions.h"
#include "internal/functions/suffixes.h"
namespace bed::internal::functions {
void Function::register_extented(BEd &ctx) {
ctx.functions.insert(
"cd",
Function{
.address_kind = Function::AddressKind::None,
.argument_kind = Function::ArgumentKind::Any,
.input_mode = Function::InputMode::None,
.desc = "Change directory.",
.default_address = "",
.accept_zero = false,
.pre_text_mode = nullptr,
.handle = [](BEd &ctx, const buffer::Address &, vase::Shard *, const Argument &arg_, std::vector<buffer::Line> *) {
auto path = std::get<std::string>(arg_);
const auto first = path.find_first_not_of(" \t");
const auto last = path.find_last_not_of(" \t");
path = path.substr(first, last - first + 1);
if (path == "~")
path = std::getenv("HOME");
if (path.starts_with("~/")) {
const char *home = getenv("HOME");
if (home)
path = std::string(home) + path.substr(1);
}
if (first != std::string::npos)
if (chdir(path.c_str()) == -1)
throw ed_error("Can't change directory.");
char cwd[PATH_MAX];
if (!getcwd(cwd, sizeof(cwd)))
throw ed_error("Directory changed, but couldn't determine current directory.");
ctx.io.write_line(cwd);
},
}
);
}
} // namespace bed::internal::functions