Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript refactoring in Vim

I don't need anything super fancy, but some scope aware refactoring would be nice.

Refactoring something in function scope is one of the most common scenarios for me:

var funyfun = function(arg1, arg2) {

    arg1 = ...arg2;
    arg2....();
}

Is there a vim plugin that would allow me to refactor arg1, for ex, in the scope of that function or do I have to invent my own "select block, find, replace" shortcut.

For extra kudos, something that would "refactor on the fly" as I type, so I can see where changes are being made. Netbeans does an excellent job of this.

like image 578
Nick Zalutskiy Avatar asked Aug 30 '11 14:08

Nick Zalutskiy


People also ask

Can I use Vim for JavaScript?

Vim supports basic syntax highlighting for JavaScript but I found it suboptimal especially when it comes to modern ES2015+ syntax, and it doesn't support JSX when working with React. I found that vim-javascript and vim-jsx solved my problems in both instances.

What is JavaScript refactoring?

Refactoring JavaScript Last modified: 06 September 2022. Refactoring means updating the source code without changing the behaviour of the application. Refactoring helps you keep your code solid, dry, and easy to maintain.

What is Vim JavaScript?

Save. Set up Vim for JavaScript. Vim is an open source text editor created in 1988 to improve the Unix text editor, 'vi'.


2 Answers

This is not limited to a certain block, but this how I would do it with plain Vim:

  1. Move cursor on top of arg1 and type *N
  2. Type ciw and insert replacement.
  3. Now you can use n and N to navigate the occurrences and by pressing . Vim will redo the replacement on the current match

Here's a shortcut for it:

" Simple word refactoring shortcut. Hit <Leader>r<new word> on a word to
" refactor it. Navigate to more matches with `n` and `N` and redo refactoring
" by hitting the dot key.
map <Leader>r *Nciw
like image 152
Epeli Avatar answered Sep 30 '22 17:09

Epeli


Sound a bit like you only want renaming instead of refactoring. Full refactoring is tricky for Javascript, though some IDEs provide approximations. Since the question is about Vim specifically, and hacks aren't excluded, I'll just jump on the scope-aware aspect:

I've got a modified DoctorJS to generate scope-aware tags, with a Vim plugin for scope-aware navigation based on those tags (see blog post/screencast).

The hacky part comes in how navigation is implemented for Vim: I generate a search pattern that includes the scope of the variable and excludes all nested scopes for the same name. So, you could use that search pattern (function scoped_tags#FindTagInScope) to implement renaming (only if all uses are in the same file, and it doesn't exclude comments and the like..). Or you could use the scoped navigation to jump through variable occurrences manually and use '.' to rename them..

like image 45
claus Avatar answered Sep 30 '22 17:09

claus