June 19, 2017

Vim & PHP: extract visual selection to variable

Simple snippet for extracting the visual selection in Vim to a PHP variable.

vnoremap <leader>e :call PHPExtractVariable()<cr>

function! PHPExtractVariable()
    let l:name = input("Name of new variable: $")
    normal! gvx
    execute "normal! i$".l:name
    execute "normal! O$".l:name." = "
    normal! pa;

Let’s see an example:


if (empty($this->userRepository->findAllByStatus('a_really_cool_status', $someUselessParameter))) {
// some cool code because we didn't find anything

The condition is really long, you want to extract it. Just for readability, or because you’re accessing the value later in the code again.

  1. Select everything in the if’s parenthesis visualy (manually with v or quickly with vib).
  2. Hit <leader>e
  3. Enter a variable name, for example noUserExists
  4. Press <enter>



$noUserExists = empty($this->userRepository->findAllByStatus('a_really_cool_status', $someUselessParameter));
if ($noUserExists) {
// some cool code because we didn't find anything

Known issues

  • doesn’t search for multiple occurences for selected portion