Skip to content

Instantly share code, notes, and snippets.

@codebje
Created August 31, 2016 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codebje/5b66b318a65797196b4a4beabbf86d02 to your computer and use it in GitHub Desktop.
Save codebje/5b66b318a65797196b4a4beabbf86d02 to your computer and use it in GitHub Desktop.
command! -buffer -nargs=0 -bang GhcModImport call Autoimport(<bang>0)
function! Autoimport(force) "{{{
let l:identifier = ghcmod#getHaskellIdentifier()
let l:parts = split(l:identifier, '\.')
" `ghc-mod sig` is available since v5.0.0.
let l:cmd = ghcmod#build_command(['find', l:parts[-1]])
let l:lines = split(ghcmod#system(l:cmd), '\n')
if len(l:lines) >= 1
let l:module = l:lines[0]
let l:view = winsaveview()
normal! G
let l:loc = search('^import\s', 'bceW')
if l:loc == 0
" no existing imports, find a module declaration
if search('^module\s', 'bceW') == 0
" no module, put it in what's almost certainly the wrong place
call cursor(1)
normal! }
else
" find the matching "where", and add a blank line
normal! /where<CR>o<esc>
endif
endif
let l:modrex = '\V\^import\s\+'.escape(l:module, '\').'\s\*\(\n\|\s\+(\)'
if len(l:parts) > 1
let l:qual = join(l:parts[:-2], '.')
let l:modrex = '\V\^import\s\+qualified\s\+'.escape(l:module, '\').'\s\+as\s\+'.escape(l:qual, '\').'\s\*\(\n\|\s\+(\)'
endif
if search(l:modrex, 'bcW') != 0
throw "trying to update existing import"
else
let l:import = "import " . l:module . l:qual . ' (' . l:parts[-1] . ')'
execute "normal! o" . l:import . "\<esc>"
endif
call winrestview(l:view)
execute "normal! j"
echom 'Added statement ' . l:import
else
echo 'Symbol not found'
endif
endfunction "}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment