Would buffer
scope be more appropriate?
The conventional approach is to hook BufSetOption filetype=go
, and set your hooks and options at buffer-scope within that hook. That way, you get Go-like behaviour whenever you edit a file that is Go-like, not just specifically .go
files.
Should I use evaluate-commands
? I’m not sure what it’s doing that the %sh
isn’t.
Probably not. What’s going on here is:
- when the hook fires, its body is evaluated
- when the body is evaluated, Kakoune sees a
%sh{}
block, runs the content of that block as a shell-script, and replaces the %sh{}
block with the output of that script
- apparently, that command prints
src/main.go
possibly followed by some other text
-
evaluate-commands
tries to evaluate its arguments (src/main.go ...
) as a Kakoune command, but that isn’t a valid Kakoune command, it’s a filename, so it prints an error
A better choice here might be nop %sh{ go fmt $kak_buffile }
since nop
is a command that ignores its arguments and does nothing - you don’t want it to do anything, you just want the side-effect of running a shell-script.
Should I use $kak_buffile
or %val{buffile}
?
Generally, you use $kak_buffile
inside a %sh{}
block, and %val{buffile}
outside one. There’s more specific rules (for example, if you’re using a shell-script to build up a command that will be evaluated outside the shell-script, such as by evaluate-commands
or kak -p
) but those don’t apply here.
Also, when you use $kak_buffile
(or any other shell variable) it’s a good idea to wrap it in double-quotes so that unexpected space characters don’t make things go haywire.
There’s one more problem with your solution: you’re running go fmt
on the file on disk, before Kakoune writes out the content of the buffer. So whatever work go fmt
does, will be immediately overwritten.
All that aside, though, Kakoune comes with a format plugin that can be used to run a formatter on the current buffer.
Gluing together my personal configuration for Python files, and the wiki’s suggestion for formatting Go, I’d recommend something like:
# When we edit a Go-like file,
# either auto-detected
# or because the user overrode the filetype manually....
hook global BufSetOption filetype=go %{
# Tell the format plugin
# to use "gofmt" to format this buffer
set-option buffer formatcmd "gofmt"
# Automatically format the buffer
# before writing it to disk
hook buffer -group go-auto-format BufWritePre .* format
# If, after we've set these options and hooks,
# the user overrides the filetype to something else...
hook buffer BufSetOption filetype=.* %{
# remove the auto-format hook,
# since it probably won't be
# appropriate for the new filetype
remove-hooks buffer go-auto-format
# We leave the formatcmd option alone,
# since the user might have manually overridden it
# and we don't have anything better to set it to.
}
}