InsertChar for a specific filetype

I’d like to make it impossible to type a TAB character in Elm files. I have found the snippet for InsertChar to insert spaces rather than a tab, but how do I run this hook only for Elm files?

You can copy this pattern from crystal.kak:

hook global WinSetOption filetype=elm %{
  map window insert <tab> ''
  hook -always -once window WinSetOption filetype=.* %{
    unmap window insert <tab>
  }
}

Thanks. Why is it so complicated? :slight_smile:

I feel like you should be able to just do

hook global BufSetOption filetype=elm %{
  map buffer insert <tab> ''
}

Thanks for this. It’s more along the lines that I was expecting.

What about “magic indent” when I press TAB? By that I mean inserting spaces up to the appropriate indentation level for the code. How would I figure that out?

Thanks.

So, there’s a few things to pull out here. The original question was “…how do I run this hook only for Elm files?” and the answer is that anything you can do globally, you can also do for a specific file-type by wrapping it in a WinSetOption hook:

hook global WinSetOption filetype=elm %{
    # ...your code here...
}

You may need to adjust your global snippet to be window-specific; for example, if your snippet says map global ... you should change it to say map window ... so it only affects the window where the file-type changed.

@alexherbo2’s example was a bit more complex, adding an additional hook. Translated into English, the basic structure is:

  • When a window’s filetype option is set to “elm”
    • Add a special mapping for <tab>
    • When this window’s filetype option is set to anything but “elm”
      • Remove the special mapping for <tab>

The idea is that if something sets filetype=elm accidentally, and the anti-<tab> mapping gets added, it’ll get cleaned up again when the filetype gets reset, instead of lingering and causing confusion. It’s a bit more complex, and 90% of the time is unnecessary, but in that last 10% it can save a lot of frustration.

4 Likes