Git Related Tips

Intro

To learn how to do the things described here using the git command line only, check Git Undo Stuff document.

Unstage or discard changes

When changes are unstaged, they still remain in the working tree and no code/text is actually lost. Those changes can be further edited or simply staged again. Unstaging is associated with idea of resetting.

When changes are discarded, they are lost and not available any longer in the working tree. If this was done by accident, the code would have to be rewritten again. Sometimes the editor still have the text on the buffer though, so it could just be saved again. Discarding is associated with the idea of checking out.

Fugitive

Vim fugitive (which also works on nvim) comes we a set of default keybindings which are being used in these examples.

Run :Git or :vert Git, then move to the staged files with gs. To unstage an entire file, type u when the cursor is on the line listing that file. Internally, this uses something like git reset ./path/to/file.

To unstage hunks (pieces of change), first move the cursor to the file in question, expand the changes with Tab, then navigate to the changes with [c, and finally unstage that specific hunk with u.

To discard (completely wipe the changes out), follow to same steps but instead of u to unstage, type X. It can be done on the line listing the file with changes, or on each individual change just like discussed above for unstaging changes.

Gitsigns

Gitsigns does have default keybindings unless you configure some yourself, even if the suggested ones in the README/docs. The keybindings shown here are from my config but largely based on the ones suggested by the docs.

To unstage the entire buffer, run :Gitsigns reset_buffer, or <Leader>hR. Think of “hR” as “hunk RESET” in the sense that it is strong en resets the entire file.

To unstage a hunk, :Gitsigns undo_stage_hunk, or <Leader>\hr. Thing of “hr” as “hunk reset” in the sense that it is weaker and resets the current hunk only.

Looks like Gitsigns stays on the safe side and does not provide commands to completely discard changes (like Fugitive does).