Skip to content

Instantly share code, notes, and snippets.

@AndrewRadev
Created December 8, 2012 10:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewRadev/4239736 to your computer and use it in GitHub Desktop.
Save AndrewRadev/4239736 to your computer and use it in GitHub Desktop.
Star ("*") mapping that tries to be a bit smarter
" Using "g*" does two things differently from the normal "*":
"
" - Doesn't move the cursor, simply sets the match
" - When moving the cursor with "n" and "N", positions it where it was on the original word.
"
" Note: g* is ordinarily taken, see :help g*
"
nnoremap g* :call <SID>SmartStar()<cr>
function! s:SmartStar()
let cword = expand('<cword>')
if cword == ''
echo "No word under the cursor"
return
endif
let current_col = col('.')
call search('\<'.cword.'\>', 'bWc', line('.'))
let cword_start_col = col('.')
let cword_start = strpart(cword, 0, current_col - cword_start_col)
let cword_end = strpart(cword, current_col - cword_start_col)
let search_pattern = '\<\%('.cword_start.'\zs'.cword_end.'\)\>'
call histadd('search', search_pattern)
let @/ = search_pattern
normal! n
echo 'Search for: '.cword
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment