Vim, Java: Open class under cursor and go to method
-
03-07-2021 - |
Question
Vim can open a file under cursor using gf
. For example, if I have the following under my cursor:
SensorManagementActivity.java
Hitting gf
will open SensorManagementActivity.java
.
The problem is that in Java, the references lack the java
suffix, and often appear as SomeClass
, SomeClass()
or SomeClass.method()
.
- How do I open
SomeClass.java
and jump tosomeMethod()
when the cursor is onSomeClass.someMethod()
in another file? - Is there a way to open a new file without saving the current one, and going back to the current one without losing changes?
Solution
The 'suffixesadd'
option allows gf
to handle Java file extensions; it is already set by the java filetype that ships with Vim, like this:
:setlocal suffixesadd=.java
To jump to methods, Vim can use a tags file that must be (re-)generated first (there are plugins that can automate that). For Java, you can use the exuberant ctags tool.
:! ctags -R
For more information and alternatives, read :help ctags
. Use the :tag
command or the Ctrl-] shortcut to jump.
You can jump to a split window via Ctrl-W ]. To be able to leave a modified file and return back to it later, :set hidden
in your ~/.vimrc
.
PS: Though here they're kind of related, it's best to avoid asking multiple questions at Stack Overflow