Selecting whole buffer immediately after a grep command

Hello fellow mouilleurs

I’m trying to create a command that greps a pattern in a buffer, selects the whole grep buffer and applies a few commands (aligns the matched patterns). I am getting an error/inconsistency.

My command to align the buffer is:

define-command grep-align %{ execute-keys '%s^([^:]+:){3}<ret>a <esc>;&<ret>,gg' }

Then, I create a map:

map global user 'c' ': grep "^(#)+" %val{bufname}<ret>:grep-align <ret>' -docstring "Table of Content"

When running the command, I get the error: " ‘grep-align’: 1:2: ‘execute-keys’: nothing selected"

However, if I change the keymap to:

map global user 'c' ': grep "^(#)+" %val{bufname}<ret>:grep-align' -docstring "Table of Content"

and type the return manually, it all works well.

Any advice on how I can fix this?

1 Like

When you run :grep, it launches a grep process, creates an empty buffer, and sets up Kakoune to add new lines to the buffer as output arrives.

Even though a simple command like grepping the current buffer appears instantaneous to a human, it takes a non-zero amount of time, and so when Kakoune goes to execute :grep-align the buffer is empty, and there’s no matches found.

Probably what you want is to trigger :grep-align after the grep process has finished, using a BufCloseFifo hook, like this:

map global user 'c' ': grep %{^(#)+} %val{bufname}<ret>:hook -once buffer BufCloseFifo .* grep-align<ret>' -docstring "Table of Content"

I might even wrap the “grep, grep-align” combo in a command, just to make the mapping declaration less overwhelming.

1 Like

Superb.

I had a hunch that this was happening, but I didn’t know how to fix it. You fix works wonderfully. And yes a single command for the grep/grep-align combo is a lot nicer and more flexible. Thanks.

2 Likes