Vim language: send current word to CtrlP

1.7k Views Asked by At

I know how to use CtrlP. I type ctrl+p, then I start to write file name, ... and so on. But, ... I am very lazy developer. I want to directly send to CtrlP current word. I know how to get current word:

let l:currentWord = expand('<cword>')

In Vim Language, ... I How can I send l:currentWord to CtrlP?

map <F6>  :call ComposerKnowWhereCurrentFileIs()<CR>
function! ComposerKnowWhereCurrentFileIs()
    let l:currentWord = expand('<cword>')
    let l:command = "grep " . l:currentWord . " ../path/to/composer -R | awk '{print $6}' | awk -F\\' '{print $2}'"
    let l:commandFileFound = l:command . ' | wc -l'
    let l:numberOfResults = system(l:commandFileFound)
    if l:numberOfResults == 1
        let l:fileName = system(l:command)
        let l:openFileCommand = 'tabe /path/to/project' . l:fileName
        exec l:openFileCommand
    else
        echo "Too many files :-( - use CtrlP ;-) "
    endif
endfunction
4

There are 4 best solutions below

1
On BEST ANSWER
<C-P><C-\>w

See :h ctrlp-mappings. You may map this combination:

map <F6> <C-P><C-\>w

In a function:

exe "normal \<C-P>" . expand('<cword>')
0
On

For that, you wouldn't use the <C-P> mapping, but the :CtrlP command, as that one takes parameters.

To build a mapping that passes the current word to the command, there are two approaches. Either directly insert the current word into the command-line (via :help c_CTRL-R_CTRL-W):

:nnoremap <Leader>p :CtrlP <C-r><C-p><CR>

Or, in order to use expand(), build the Ex command via :execute:

:nnoremap <Leader>p :execute 'CtrlP' expand('<cword>')<CR>
2
On
function! LazyP()
  let g:ctrlp_default_input = expand('<cword>')
  CtrlP
  let g:ctrlp_default_input = ''
endfunction
command! LazyP call LazyP()
nnoremap <C-P> :LazyP<CR>

(this could probably be simplified but I suck at vim syntax)

6
On

The whole point of CtrlP and similar plugins is to provide an alternative command-line where you can refine your search as you type.

If you don't need fuzzy search and you already have the filename under the cursor… why not simply use the built-in gf?

-- edit --

In the gif below:

  • I jump to /path/not/knowable/BlaBlaClassName.php with gf,
  • I jump back to the previous buffer with <C-^> (unrelated to your question),
  • I jump to the declaration of BlaBlaClassName in /path/not/knowable/BlaBlaClassName.php again with <C-]> thanks to a tagsfile generated with ctags.

gf