From ec15ab59131778ffccabd9c820a37559cf6e6b0e Mon Sep 17 00:00:00 2001 From: Barak Michener Date: Fri, 14 Jan 2022 16:48:12 -0800 Subject: [PATCH] add custom genericizer function --- .vim/filetype.vim | 6 +++++- .vim/nvim.lua | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/.vim/filetype.vim b/.vim/filetype.vim index 652ed69..a02e290 100644 --- a/.vim/filetype.vim +++ b/.vim/filetype.vim @@ -118,4 +118,8 @@ autocmd FileType java let b:auto_trim_whitespace=1 augroup templates autocmd BufNewFile *.vue 0r ~/.vim/skeletons/skeleton.vue -augroup END +augroup end + +augroup rust + autocmd FileType rust nnoremap lg lua rust_where_at_line() +augroup end diff --git a/.vim/nvim.lua b/.vim/nvim.lua index 15c5a4b..6d6f7ae 100644 --- a/.vim/nvim.lua +++ b/.vim/nvim.lua @@ -273,3 +273,55 @@ git_grep_word = function(conf) for k,v in pairs(conf) do opt[k] = v end builtin.grep_string(opt) end + + +function string.insert(str1, str2, pos) + return str1:sub(1,pos)..str2..str1:sub(pos+1) +end + +function string.split(s, delimiter) + result = {}; + for match in (s..delimiter):gmatch("(.-)"..delimiter) do + table.insert(result, match); + end + return result; +end + +local function rust_whereify_line(line, var_name) + if string.find(line, "fn") == nil then + return nil + end + + local paren = string.find(line, "%(") + if paren == nil then return nil end + + local open_generic = string.find(line, "<") + if open_generic ~= nil then + if open_generic < paren then + -- TODO(barakmich): it's already generic, we need to do something for that + -- probably a different function + return nil + end + -- just continue otherwise + end + + local whitespace = string.match(line, "^(%s*)") + + local generic = "<"..var_name..">" + local out = string.insert(line, generic, paren - 1) + + local brace = string.find(out, "%{") + if brace == nil then brace = string.len(out) end + + out = string.insert(out, "\n"..whitespace.."where\n"..whitespace.." "..var_name..": ,\n"..whitespace, brace - 1) + + return string.split(out, "\n") +end + +function rust_where_at_line() + local var_name = vim.fn.input("Variable: ") + local lineNum, col = unpack(vim.api.nvim_win_get_cursor(0)) + local replacements = rust_whereify_line(vim.api.nvim_get_current_line(), var_name) + vim.api.nvim_buf_set_lines(0, lineNum-1, lineNum, false, replacements) + vim.api.nvim_win_set_cursor(0, {lineNum + 2, 4}) +end