# ------------------
# Plugin Setup
# ------------------

# IMORTANT NOTE:
# I needed to open kakoune and type ':plug-install' to actually
# install the plugins listed in this file. I did not see this 
# mentioned in wikis or anything, so make sure to do this to
# avoid searching github wikis and reddit needlessly.

# Creates the /plugins folder if it doesnt exist each startup
evaluate-commands %sh{
    plugins="$kak_config/plugins"
    mkdir -p "$plugins"
    [ ! -e "$plugins/plug.kak" ] && \
        git clone -q https://github.com/andreyorst/plug.kak.git "$plugins/plug.kak"
    printf "%s\n" "source '$plugins/plug.kak/rc/plug.kak'"
}
plug "andreyorst/plug.kak" noload

# ------------------
# Editor Settings
# ------------------

# Disables startup message showing
set-option global startup_info_version 30000000

set-option global tabstop 4
set-option global indentwidth 4
set-option global scrolloff 5,3
declare-option str kakrc_path "~/system/nate/dotfiles/kak/kakrc"
declare-option str sway_conf_path "~/system/nate/dotfiles/sway/config.d/default"
declare-option str shell_config "~/system/nate/modules/home-manager/home.nix"

# plug "catppuccin/kakoune" theme config %{
#     colorscheme catppuccin_macchiato
# }
colorscheme catppuccin_macchiato
# relative line numbers
hook global BufCreate .* %{
    add-highlighter buffer/ number-lines -hlcursor
}

# Git Gutters
hook global WinCreate .* %{ evaluate-commands %sh{
  if [ $kak_buffile != $kak_bufname ] && git ls-files --error-unmatch "$kak_buffile" > /dev/null 2>&1; then
    echo "git show-diff"
  fi
}}

# Write on unfocus
hook global FocusOut .* %{ try %{
    write
}}

hook global BufWritePost .* %{ evaluate-commands 'git update-diff' }
hook global BufReload .* %{ evaluate-commands 'git update-diff' }

# Color Render in Echo Area
hook global WinSetOption filetype=kak %{ hook global NormalIdle .* %{
    evaluate-commands -save-regs 'a' %{ try %{
        execute-keys -draft <a-i>w"ay
        evaluate-commands %sh{ (
            color="${kak_reg_a}"
            inverted_color=$(echo "${color}" | perl -pe 'tr/0123456789abcdefABCDEF/fedcba9876543210543210/')
            printf "%s\n" "evaluate-commands -client $kak_client %{ try %{
                               echo -markup %{{rgb:${inverted_color},rgb:${color}+b}   #${color}   }
                           }}" | kak -p $kak_session
        ) >/dev/null 2>&1 </dev/null & }
    }}
}}

# Add default,red and bold style to these regex matches
add-highlighter global/ regex \b(TODO|FIXME|XXX|NOTE)\b 0:default,red+rb

# ------------------
# Key bindings
# ------------------

# Remap hjkl navigation to colemak-dh layout
map global normal n h
map global normal e k
map global normal i j
map global normal o l

map global normal N H
map global normal E K
map global normal I J
map global normal O L

# Remap insert command
map global normal h i

# Insert line above or below
map global normal l o
map global normal L O

# No alt, remap
map global normal <c-f> <a-f>  -docstring 'same as [f] but in the other direction'
map global normal <c-t> <a-t>  -docstring 'same as [t] but in the other direction'
map global normal <c-n> <a-h>  -docstring 'select to beginning of line'
map global normal <c-o> <a-l>  -docstring 'select to end of line'
map global normal <c-s> <a-s>  -docstring 'split selections on line boundaries'
map global normal <c-S> <a-S>  -docstring 'select first and last character of each selection'
map global normal '<c-;>' '<a-;>'  -docstring 'flip direction of each selection'
map global normal <c-:> <a-:>  -docstring 'ensure selections are in forward direction (cursor then anchor)'
map global normal <c-,> <a-,>  -docstring 'clear the main selection'
map global normal <c-.> <a-.>  -docstring 'Repeat last object or f/t selection'

# Scrolling remap
map global normal <c-e> <pageup> -docstring 'Scroll screen up'
map global normal <c-i> <pagedown> -docstring 'Scroll screen down'

map global normal <c-/> ':comment-line<ret>' -docstring 'comment selected lines'

# Ctrl-s to save
map global normal <c-s> ':w<ret>' -docstring 'write buffer'
# Ctrl-x to save and exit
map global normal <c-x> ':w<ret>:db<ret>' -docstring 'write close buffer'

# Colemak goto remappings
map global goto n h -docstring 'line start'
map global goto o l -docstring 'line end'
map global goto e k -docstring 'buffer top'
map global goto i j -docstring 'buffer bottom'

map global goto h n
map global goto l o
map global goto k e
map global goto j i

# Remap view keys
map global view n h
map global view o l
map global view e k
map global view i j

map global normal ( ': buffer-previous<ret>' -docstring 'prev buffer'
map global normal ) ': buffer-next<ret>' -docstring 'next buffer'

# map global normal [ ( -docstring 'rotate main selection'
    
# map global normal ] ) -docstring 'rotate main selection backwards'
# Make x select <param> lines up and down
def -params 1 extend-line-down %{
  exec "<a-:>%arg{1}J"
}

def -params 1 extend-line-up %{
  exec "<a-:><a-;>%arg{1}K<a-;>"
  try %{
    exec -draft ';<a-K>\n<ret>'
    exec X
  }
  exec '<a-;><a-X>'
}


map global normal x ':extend-line-down %val{count}<ret>'
map global normal X ':extend-line-up %val{count}<ret>'

map global normal k n -docstring 'next result'
map global normal K N -docstring 'next result add selection'

map global normal <a-k> <c-n> -docstring 'prev result'
map global normal <a-K> <c-N> -docstring 'prev result add selection'

map global insert <down> <c-n> -docstring 'next completion'
map global insert <up> <c-p> -docstring 'prev completion'

# User Mode Bindings
# Accessed with <space>
declare-user-mode git
map global user g ': enter-user-mode git<ret>' -docstring "Git mode"
map global user p '<a-!>wl-paste -n<ret>' -docstring 'paste from system clip board'
hook global RegisterModified '"' %{ nop %sh{
  printf %s "$kak_main_reg_dquote" | wl-copy > /dev/null 2>&1 &
}}

# Open kakrc, double quotes needed to ecsape the kakrc_path option
map global user o ":edit %opt{kakrc_path}<ret>" -docstring 'open kakrc'
map global user z ":edit %opt{shell_config}<ret>" -docstring 'open shell config'
map global user S ":edit %opt{sway_conf_path}<ret>" -docstring 'open wm config'
# Git Mode Bindings
map global git d '<esc>:git show-diff<ret>' -docstring "Show diff"

# -----------------
# LSP Configuration
# -----------------

plug "kak-lsp/kak-lsp" do %{
  cargo install --locked --force --path .
  mkdir -p ~/.config/kak-lsp
  cp -n kak-lsp.toml ~/.config/kak-lsp/
} config %{

  # enable inlay hints
  lsp-inlay-hints-enable global
  lsp-inlay-diagnostics-enable global

  # set global lsp_diagnostic_line_error_sign '║'
  # set global lsp_diagnostic_line_warning_sign '┊'

  define-command lsp-restart -docstring 'restart lsp server' %{ lsp-stop; lsp-start }

  map global insert <tab> '<a-;>:try lsp-snippets-select-next-placeholders catch %{ execute-keys -with-hooks <lt>tab> }<ret>' -docstring 'Select next snippet placeholder'
  map global object a '<a-semicolon>lsp-object<ret>' -docstring 'LSP any symbol'
  map global object <a-a> '<a-semicolon>lsp-object<ret>' -docstring 'LSP any symbol'
  map global object e '<a-semicolon>lsp-object Function Method<ret>' -docstring 'LSP function or method'
  map global object k '<a-semicolon>lsp-object Class Interface Struct<ret>' -docstring 'LSP class interface or struct'
  map global object d '<a-semicolon>lsp-diagnostic-object --include-warnings<ret>' -docstring 'LSP errors and warnings'
  map global object D '<a-semicolon>lsp-diagnostic-object<ret>' -docstring 'LSP errors'

  # load lsp for supported filetypes
  set-option global lsp_cmd "kak-lsp -s %val{session} -vvv --log /tmp/kak-lsp.log"
  hook global WinSetOption filetype=(rust|python|go|javascript|typescript|c|cpp|zig|dart|ruby) %{
    lsp-enable-window
    # lsp-auto-hover-enable
    map global user l ': enter-user-mode lsp<ret>' -docstring 'lsp mode'
    map global user h ': enter-user-mode lsp<ret>h' -docstring 'lsp help'
    map global user a ': enter-user-mode lsp<ret>a' -docstring 'lsp code action'
    set-option global lsp_hover_anchor false
  }

  hook global KakEnd .* lsp-exit
}


# -----------------
# Other Plugins
# -----------------

map global goto f '<esc>:prompt -shell-script-candidates %{ fd --type f --hidden } file: %{ edit %val{text} }<ret>' -docstring "file"
map global goto b '<esc>:prompt -buffer-completion buffer: %{ buffer %val{text} }<ret>' -docstring "buffer"

# Fzf Plugin 
plug "andreyorst/fzf.kak" config %{
    # map global user f ':fzf-mode<ret>v' -docstring 'fzf file in project'
    map global user b ':fzf-mode<ret>b' -docstring 'fzf current buffers'

    map global user / ':fzf-mode<ret>g' -docstring 'fzf search in project'

    # def fzf_file %{
    #     evaluate-commands %sh{
    #        printf "%s\n" ":fzf-mode<ret><esc>:fzf -items-cmd fd<ret>"
    #    }
    # }

# Change FZF colors
# FZF_DEFAULT_OPTS=" \
# --color=bg+:#313244,bg:#1e1e2e,spinner:#f5e0dc,hl:#f38ba8 \
# --color=fg:#cdd6f4,header:#f38ba8,info:#cba6f7,pointer:#f5e0dc \
# --color=marker:#f5e0dc,fg+:#cdd6f4,prompt:#cba6f7,hl+:#f38ba8"
}



plug "alexherbo2/auto-pairs.kak" %{
    enable-auto-pairs
}


plug "https://github.com/h-youhei/kakoune-surround"

map global normal <c-m> ':surround<ret>'

# Custom scripts

# evaluate-commands %sh{
#     for file in ~/.config/kak/rc/*.kak; do
#         printf "source %s\n" $file
#     done
# }

# source "~/.config/kak/rc/"