Filetype Detection

Background

I recently ran into an issue where bash (shell) scripts included in a project were not being detected as the sh filetype in Kakoune, and therefore were rendered in plain, white text.

After digging around on this forum and through some issues on GitHub, I was able to figure out the nice, simple (and I assume correct) solution I was looking for. As far as I can tell, how Kakoune detects file types–and what to do if it doesn’t detect a filetype correctly (or at all)–isn’t plainly documented anywhere, so I thought I’d jot down the gist of my findings here…

  • Kakoune detects filetypes using the file.kak script bundled with the standard rc scripts that ship with Kakoune.
  • This uses the assigned mime-type of a given file, using the unix file command. See man file.
  • If the mime-type obtained via the file command isn’t giving you the right file type, you can add custom rules for it to use to a magic file. See man magic (this will provide the info you will probably need to define a custom file detection rule).

Example

Now here’s a mini-guide/example based on what I needed to do…

My problem was that the bash scripts I was looking at had the following shebang, with no file extension:

#!/usr/bin/env -S bash

To add a custom rule for this, I created a .magic file in my home directory:

0	string	#!/usr/bin/env\ -S\ bash	Alternative bash shebang
!:mime text/x-shellscript

The template for this rule is:

<offset> <type> <test> <message>
!:mime <mime-type>

Some additional notes on this example:

  • I simply copied the shebang rule and escaped the spaces for the test.
  • See the file.kak rc script for a list of mime-types that Kakoune recognizes.
    • For a default installation use: kak /usr/local/share/kak/rc/detection/file.kak
  • man magic provides the in-depth details on how to define “magic files”

Related links

6 Likes

yeah by default file recognizes shebangs like #!/usr/bin/env bash but not #!/usr/bin/env -S bash.
We should fix this upstream by including the relevant variations.