paolooo
paolooo

Reputation: 4153

VIM: How to get the current function name

In my vim configuration, I mapped ,pt to run a phpunit test.

map <leader>pt :!clear && vendor/bin/phpunit % --testdox<cr>

But sometimes I want to run a specific test by using phpunit --filter

map <leader>pt :!clear && vendor/bin/phpunit --filter {FUNCTION_NAME_HERE} % --testdox<cr>

Is there anyway we can fill the function name automatically in vim?

Upvotes: 0

Views: 984

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172768

As a text editor, Vim only has a limited understanding of the structure of the underlying source code.

Potential sources for the current method name could be:

  • the jump to the previous start of a method: :help [m
  • syntax highlighting
  • the tags database; plugins like taglist and tagbar highlight the current definition automatically

Alternatively, you could attempt to resolve the function name via pattern extraction (as @Matt has suggested in the comments; via something like matchstr(getline(search('function', 'bcnW')), 'function\s\+\zs\w\+')) - but this would be limited to the current language and hard to get correct 100% of the time.

In summary, this is not straightforward and would involve advanced Vimscript to do right.

Alternative

Instead of a mapping that automates this fully, I would go for the 80% solution, a custom :command that you can pass the function name:

command -nargs=1 Phpunit !clear && vendor/bin/phpunit --filter <args> % --testdox

Like the mapping, it will still save considerable typing. You can yank the function name to paste it in, or if the cursor currently is on top of it, just insert it into the :Phpunit command-line via <C-R><C-W>.

As a next step, you could make :Phpunit handle zero arguments and then drop the --filter argument, so your mapping would become :nnoremap <Leader>pt :Phpunit<CR>

Upvotes: 1

Related Questions