Skip to content

Instantly share code, notes, and snippets.

@43081j
Created April 22, 2025 16:22
Show Gist options
  • Save 43081j/2c31a1c5d583c8c6afd0ded1e409975d to your computer and use it in GitHub Desktop.
Save 43081j/2c31a1c5d583c8c6afd0ded1e409975d to your computer and use it in GitHub Desktop.
ast-grep on current vim buffer
function! RunAstGrepOnBuffer()
let l:input = input('sg/')
if l:input == ''
echo "No input provided"
return
endif
let l:parts = split(l:input, '/')
if len(l:parts) != 2
echoerr "Invalid input format. Expected 'searchPattern/replacePattern'"
return
endif
let l:searchPattern = l:parts[0]
let l:replacePattern = l:parts[1]
let l:command = 'sg run --lang=typescript --heading=never --color=never --stdin -U -p ' . shellescape(l:searchPattern) . ' -r ' . shellescape(l:replacePattern) . ''
let l:output = system(l:command, join(getbufline('%', 1, '$'), "\n"))
if v:shell_error
echoerr "Error running ast-grep: " . l:output
return
endif
let l:output_lines = split(l:output, "\n")[0:-3]
call setline(1, output_lines)
endfunction
nnoremap <leader>bsg :call RunAstGrepOnBuffer()<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment