Vim: Navigation inside a file
Here are a few tips that I've recently picked up to help traverse files quicker.
Search for the text you are navigating to
If there is a ruby method that you'd like to navigate to which is on a different line than you're currently on, you can type the following to help you reach that method faster
- Type / to get into search mode
- Type the prefix of the text you are searching for, e.g. "some_method"
- Press enter to navigate to that text
- If there are multiple search results, use 'n' and 'N' to go to next/previous occurs.
- TIP: if the target method is above where you are, use ? instead of / to search backwards
Traverse methods quickly
To traverse your code one method at a time, you have two options
- use the technique above to search for "def" (if you're using ruby), then use 'n' and 'N' to go forward and backward
- if you're methods are well formatted and have line breaks between them, use Control-{ or Control-} to go to the next line break.
Go to a particular position on the current line
The 'f' command can be used to find a character on your current line, and ';' and ',' are used to go forward and backwards if there are multiple occurrences.
This is best used if you are traversing to special characters like brackets, commas, etc, as there are usually fewer occurrences of these.
Use % to go to matching def/end
More recent vim versions have built in plugins that can help you traverse ruby code. You can use the % key to go to a particular matching bracket, or if working in ruby you can find matching def/class/end pairs.
Marking bookmarks using 'm'
Vim allows you to leave bookmarks so that you can jump to various locations of your document. To set a mark, do the following
- type m
- type a letter from a-z
- To traverse to this mark, press `[a-z]. This gives you 26 possible bookmarks to make in a vim document.
Use ` to jump around
The backquote character can be used to jump around the document to areas of previous interest. For example,
`` goes to the last jump locations
`. goes to previous change location
`^ goes to previous insertion location
For more tips, check out the book Practical Vim by Drew Neil where I have learnt these from.