Wikia

Vim Tips Wiki

List lines with keyword and prompt for jump

Talk0
1,612pages on
this wiki
Revision as of 05:36, July 13, 2012 by JohnBot (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Tip 563 Printable Monobook Previous Next

created 2003 · complexity basic · author lechee · version 6.0


Press [I to display all lines that contain the keyword under the cursor. Lines from the current file, and from included files, are listed. Another command (see the references below) allows you to jump to one of the displayed occurrences.

Here are two functions to simplify the process. With the mappings shown (and the default backspace Leader key) you can press \j to list occurrences of the keyword under the cursor. You are then prompted to enter the number of an item, in order to jump to that occurrence. Alternatively, press \p for a prompt allowing you to enter the keyword.

" List occurrences of keyword under cursor, and
" jump to selected occurrence.
function! s:JumpOccurrence()
  let v:errmsg = ""
  exe "normal [I"
  if strlen(v:errmsg) == 0
    let nr = input("Which one: ")
    if nr =~ '\d\+'
      exe "normal! " . nr . "[\t"
    endif
  endif
endfunction

" List occurrences of keyword entered at prompt, and
" jump to selected occurrence.
function! s:JumpPrompt()
  let keyword = input("Keyword to find: ")
  if strlen(keyword) > 0
    let v:errmsg = ""
    exe "ilist! " . keyword
    if strlen(v:errmsg) == 0
      let nr = input("Which one: ")
      if nr =~ '\d\+'
        exe "ijump! " . nr . keyword
      endif
    endif
  endif
endfunction

nnoremap <Leader>j :call <SID>JumpOccurrence()<CR>
nnoremap <Leader>p :call <SID>JumpPrompt()<CR>

Paste the code above into a file, save the file, then enter the command :so % (source current file). Then put the cursor on a word in any file and press \j to list occurrences, and jump to the selected occurrence.

ReferencesEdit

CommentsEdit

If you would prefer to modify [I to prompt for a number to jump to the following map does so:

nnoremap [I [I:let nr = input("Which one: ")<Bar>if nr != ""<Bar>exe "silent! normal " . nr ."[\t"<Bar>endif<CR>

and again for ]I

nnoremap ]I ]I:let nr = input("Which one: ")<Bar>if nr != ""<Bar>exe "silent! normal " . nr ."]\t"<Bar>endif<CR>

BenArmston 12:16, 15 May 2008 (UTC)


Around Wikia's network

Random Wiki