Shebang filetype detection?

Does anyone got a BufOpenFile hook to detect filetype with shebang ?

Something that could match “#!/usr/bin/sh” and “#!/usr/bin/env sh”

I’m pretty sure this could be done with two or three line but I sucks so much :’/

3 Likes

I made my way with

hook global BufOpenFile .* %{ evaluate-commands %sh{
    if [ -z "${kak_opt_filetype}" ]; then
        first_line="$(head -n+1 "${kak_buffile}")"

        if [ 0 -eq "$(expr "$first_line" : "#!")" ]; then
            return
        fi

        exec="$(basename "$(echo "$first_line" | awk '{print $1}')")"
        if [ "env" != "$exec" ]; then
            filetype="$(echo "$exec" | sed "s/[0-9]\+$//g")"
        else
            filetype="$(echo "$first_line" | awk '{print $2}')"
        fi

        printf "set-option buffer filetype '%s'\n" "${filetype}"
    fi
} }
3 Likes

Some shebang as /bin/bash give this filetype “bash”. Is just added this to fallback correctly.

hook global WinSetOption filetype=bash %{
	set buffer filetype sh
}
1 Like

Awesome ! I though about the same, but never to the time to write anything, so I was very happy to see this post and copy pasted right away in my kakrc.

Any reason you used another hook instead of adding something like:

        if [ "$filetype"!="bash" ]; then
            filetype="sh"
        fi

?

Good job anyway ! I think you should try to PR it to master

1 Like

I’d like not to write any dedicated code here. This should just stay stupid

Good call

It’s really a life saver for all my executable script that don’t have filetype is their name, like all the one in ~/bin :slight_smile:

I maybe raged 10x per day and I only solved this problem today. Laziness will kill me :slight_smile:

2 Likes

I submited this to the main repo : https://github.com/mawww/kakoune/pull/3846

2 Likes

haha same for me :laughing:

Story of my unix life… I guess I just like raging

Nice! Thanks

Well, I had the problem, cause my Janet files were recognized as Clojure even with your script. When I looked in Kakoune code I have found, that it uses file command, which indeed marked the Janet file as Clojure. So I searched the Clojure magic file and found it can match against the file content.

So creating my own .magic file with the right Janet recognition was actually the easiest way.

Not that anything is wrong with your script, I still have it in my kakrc, but that sometimes, not everything should be solved by the Kakoune :-).