Time to time we want to save a location and jump back to that location. A lot of IDE does not have this feature, but it can be very useful. In vim we have marks to do that.

Overview

I’ll refer to marks as 'a where a is the name of the mark. There are some predefined marks, for example numbers or '[ and ']. There is one we already used and it’s '< and '> which is the beginning and end of the last visual selection.

We can refer to a mark two ways: ` and '. They have different meaning.

  • `: Exact position.
  • ': Line without position within the line. It will be the beginning of the line

Using a lowercase letter marks are local mark, while uppercase letters are global. Based on this, we can have multiple 'a marks in different files, but we can have only one 'A that marks a position in a specific file.

We can list marks with :marks

Special marks

  • '.: Position where last change occurred in current buffer.
  • `": Position where last exited current buffer.
  • `0: Position in last file edited (when exited Vim).
  • `1: Like '0 but the previous file (also '2 etc).
  • '': Line in current buffer where jumped from.
  • `[ and `]: Beginning/end of previously changed or yanked text.
  • '[ and ']: Beginning/end line of previously changed or yanked text.
  • `< and `>: Beginning/end of last visual selection
  • '< and '>: Beginning/end line of last visual selection

Create a mark

We can create a mark with m, for example ma will save the cursor position in mark a. Marks are always saved with exact position and we can decide if we want to refer to the beginning of the line or exact position when we are using a mark.

Jump to mark

We can jump to a mark with '[mark] or `[mark], for example we saved our position with ma and we want to jump back, we can jump back with `a.

Operation with marks

We can mark two lines in a document with mf and mt as “mark from” and “mark to” and just delete everything between them. It does not have to be whole line. If we want to delete them “linewise” we can jump back to 'f and delete with d't.

We can refer to them as range in commands. For example we don’t wan to delete everything between 'f and 't, but we want to do a substitution:

:'f,'t s/old/new/g

Or we can save to a new file with:

:'f,'t w!newfile

I know it can be done with visual select too, but if you learn marks, you can do a all things without visual select which is good because visual select is limited, for example you start visual selection, move 30 lines down but while you are moving you spot a typo, now you have to exit visual select mode, fix it and start visual select again. With marks you can mark the beginning, move down and save to a new file.

We don’t even need 't because with ranged we can refer to the current line with ., so we can do the same with one mark:

:'f,. w!newfile