diff --git a/src/buffer_manager.cc b/src/buffer_manager.cc index 45a50c3c5..447b47c19 100644 --- a/src/buffer_manager.cc +++ b/src/buffer_manager.cc @@ -7,6 +7,7 @@ #include "file.hh" #include "ranges.hh" #include "string.hh" +#include "regex.hh" namespace Kakoune { @@ -79,6 +80,24 @@ Buffer& BufferManager::get_buffer(StringView name) return *res; } +Buffer* BufferManager::get_buffer_matching_ifp(const Regex& regex) +{ + for (auto& buf : m_buffers | reverse()) + { + if (StringView name = buf->name(); regex_match(name.begin(), name.end(), regex)) + return buf.get(); + } + return nullptr; +} + +Buffer& BufferManager::get_buffer_matching(const Regex& regex) +{ + Buffer* res = get_buffer_matching_ifp(regex); + if (not res) + throw runtime_error{format("no buffer matching '{}'", regex.str())}; + return *res; +} + Buffer& BufferManager::get_first_buffer() { if (all_of(m_buffers, [](auto& b) { return (b->flags() & Buffer::Flags::Debug); })) diff --git a/src/buffer_manager.hh b/src/buffer_manager.hh index 75066bd94..78fb4c891 100644 --- a/src/buffer_manager.hh +++ b/src/buffer_manager.hh @@ -28,6 +28,9 @@ public: Buffer* get_buffer_ifp(StringView name); Buffer& get_buffer(StringView name); + Buffer* get_buffer_matching_ifp(const Regex& regex); + Buffer& get_buffer_matching(const Regex& regex); + void arrange_buffers(ConstArrayView first_ones); Buffer& get_first_buffer(); diff --git a/src/commands.cc b/src/commands.cc index 6cd091e26..d83356643 100644 --- a/src/commands.cc +++ b/src/commands.cc @@ -847,13 +847,17 @@ const CommandDesc buffer_cmd = { "buffer", "b", "buffer : set buffer to edit in current client", - single_param, + { + { { "matching", { {}, "treat the argument as a regex" } } }, + ParameterDesc::Flags::None, 1, 1 + }, CommandFlags::None, CommandHelper{}, make_completer(menu(complete_buffer_name)), [](const ParametersParser& parser, Context& context, const ShellContext&) { - Buffer& buffer = BufferManager::instance().get_buffer(parser[0]); + Buffer& buffer = parser.get_switch("matching") ? BufferManager::instance().get_buffer_matching(Regex{parser[0]}) + : BufferManager::instance().get_buffer(parser[0]); if (&buffer != &context.buffer()) { context.push_jump();