Extract variable in JavaScript

4 Points

Aleksandar Goševski Aleksandar Goševski

6 years ago

Extract variable feature for JavaScript.

function! ExtractLocalVariable()
    let name = input("Variable name: ")

    if (visualmode() == "")
        normal! viw
    else
        normal! gv
    endif

    exec "normal! c" . name
    exec "normal! Ovar " . name . " = "
    exec "normal! pa;"
endfunction

vnoremap <Leader>var :call ExtractLocalVariable()<CR>

Benoît Zugmeyer

Benoît Zugmeyer 6 years ago

That's great! Does someone know how to execute an interactive search and replace like this after the extraction?

:%s/<previously selected text>/<name >/gc<br>

EDIT: Nevermind, with some googling, I managed to do what I wanted:

function! ExtractLocalVariable() let name = input("Variable name: ") if (visualmode() == "") normal! viw else normal! gv endif exec "normal! c" . name let selection = @" exec "normal! Ovar " . name . " = " exec "normal! pa;" call feedkeys(':.+1,$s/\V\C' . escape(selection, '/\') . '/' . escape(name, '/\') . "/gec\<cr>") endfunction vnoremap <Leader>var :call ExtractLocalVariable()<CR>