0

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?

paolooo
  • 4,133
  • 2
  • 18
  • 33
  • Let me try it @phd – paolooo Nov 02 '19 at 11:24
  • @phd, I'm sorry but I can't make it work. I've updated my .vimrc with `map pg :!clear && vendor/bin/phpunit --filter expand('') % --testdox`, tested it, and the result is `E498: no :source file name to substitute for ""` – paolooo Nov 02 '19 at 11:37
  • `` is for VimScript only. I guess you need `shellescape(matchstr(getline(search('function', 'bcnW')), 'function\s\+\zs\w\+'))` or something like that. – Matt Nov 02 '19 at 13:01
  • Thanks @Matt, I'm sorry but didn't worked too... `map pg :!clear && vendor/bin/phpunit --filter shellescape(matchstr(getline(search('function', 'bcnW')), 'function\s\+\zs\w\+')) % --testdox` – paolooo Nov 02 '19 at 15:22
  • Surely, it does not, as the whole VimScript statement gets transferred literally to the shell, which knows nothing about VimScript. I'd be very amused if that worked. Read `:h :execute` for a starter. – Matt Nov 02 '19 at 15:26

1 Answers1

1

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>

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324