#
# Kakoune LSP and tree-sitter configuration.
#
{ ... }:
{
  # General LSP configuration.
  xdg.configFile."kak-lsp/kak-lsp.toml".source = ../../../kak/kak-lsp.toml;
  xdg.configFile."kak-tree-sitter/config.toml".source = ../../../kak/kak-tree-sitter.toml;
  xdg.configFile."kak/colors".source = ../../../kak/colors;

  programs.kakoune.config = {

    # LSP keybinds
    keyMappings = [
      {
        mode = "user";
        key = "l";
        effect = ":enter-user-mode lsp<ret>";
        docstring = "LSP commands";
      }
      {
        mode = "user";
        key = "A";
        effect = ":lsp-code-actions<ret>";
        docstring = "bring up the code actions menu";
      }
      {
        mode = "user";
        key = "F";
        effect = ":lsp-code-actions<ret><ret>";
        docstring = "automatically execute first code action";
      }
      {
        mode = "object";
        key = "<a-a>";
        effect = "<a-semicolon>-lsp-object<ret>";
        docstring = "LSP commands";
      }
      {
        mode = "object";
        key = "f";
        effect = "<a-semicolon>lsp-object";
        docstring = "LSP any symbol";
      }
      {
        mode = "object";
        key = "t";
        effect = "<a-semicolon>lsp-object";
        docstring = "LSP any symbol";
      }
      {
        mode = "object";
        key = "d";
        effect = "<a-semicolon>lsp-diagnostic-object --include-warnings<ret>";
        docstring = "LSP commands";
      }
      {
        mode = "object";
        key = "D";
        effect = "<a-semicolon>lsp-diagnostic-object<ret>";
        docstring = "LSP commands";
      }
    ];

    hooks = [
      # Allow tab to move through completions.
      {
        name = "InsertCompletionShow";
        option = ".*";
        commands = ''
          try %{
              # this command temporarily removes cursors preceded by whitespace;
              # if there are no cursors left, it raises an error, does not
              # continue to execute the mapping commands, and the error is eaten
              # by the `try` command so no warning appears.
              execute-keys -draft 'h<a-K>\h<ret>'
              map window insert <tab> <c-n>
              map window insert <s-tab> <c-p>
              hook -once -always window InsertCompletionHide .* %{
                  unmap window insert <tab> <c-n>
                  unmap window insert <s-tab> <c-p>
              }
          }
        '';
      }
    ];
  };
}
