The real power of Emacs lies in its extensibility. To be able to quickly hack some Elisp together to fix a specific problem right in your development environment is something quite unique to Emacs, and it makes it stand apart from other text editors.
What do we already have?
Let’s see what building blocks are already available.
All in all, what I want to achieve shouldn’t be too hard to implement!
I’m calling my small package
js2-unused, so all functions and variables will
have that prefix.
We’ll need some packages along the way, so let’s require them:
The first step is to find all function definitions within the current buffer.
JS2-mode has a function
js2-visit-ast that makes it really easy to traverse
the entire AST tree.
We can first define a variable that will hold all function definition names that we find:
Now let’s traverse the AST and find all function definitions. We want to find:
- all assignments that assign to a function;
- all function declarations that are named (skipping anonymous functions).
Finding references using xref-js2
Now that we can find and store all function names in a list, let’s use
xref-js2 to filter the ones that are never referenced. If we find
unreferenced functions, we simply display a message listing them.
That’s it! In ~30 lines we can now find unreferenced functions in any JS file. Sure, the code is not perfect, far from it, but it was hacked together in 10 minutes and gets the job done.
Quickly writing some lisp code to fix a specific problem is something I do very
often. Most of the time, it’s code I throw away as soon as the task is
completed, but from time to time it’s something generic enough to be reused
later, in which case I save it in my
emacs.d, or make a proper package out of
If you find this feature useful, you can grab it from my emacs.d.