From 5fd9bb59e35ceeeb0d6661ff5fad950a85c7612a Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Fri, 19 Apr 2024 16:37:21 +1000 Subject: [PATCH] Add buffer -matching switch --- src/buffer_manager.cc | 19 +++++++++++++++++++ src/buffer_manager.hh | 3 +++ src/commands.cc | 8 ++++++-- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/buffer_manager.cc b/src/buffer_manager.cc index 45a50c3c..447b47c1 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 75066bd9..78fb4c89 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 6cd091e2..d8335664 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();