Vim - Add a file to the staging area
This is a mapping that adds the current file to the git staging area.
nnoremap <leader>ga :silent !git add %<CR>This won't work if the file is not located within your current working directory.
How can you determine the current working directory?
:pwdTo change to the directory of the current file:
:cd %:hChange to the parent directory.
:cd ../Change to the home directory.
:cd ~Or simply.
:cdBut let's get back to the mapping.
nnoremap <leader>ga :silent !git add %<CR>How does it work?
The shell command - !{cmd}
The shell command lets you execute a {cmd} with the shell.
The shell is defined by the 'shell' option. The default is $SHELL or "sh" or on Win32 it's "cmd.exe".
Example: List directory contents
:!lsIf {cmd} contains "%" it is expanded to the current file name.
Example: Add current file contents to git index
:!git add %The last is part to understand is :silent.
The silent command - :silent {cmd}
The silent command lets you execute a {cmd} silently.
Example: Show the working tree git status
:!git statusExample: Show the working tree git status, silently
:silent !git statusThis is useful for commands that have output we don't care about.
Let's go back to the mapping again.
nnoremap <leader>ga :silent !git add %<CR>We don't care about the output of this command.
I hope this has been helpful. Take it easy, my friends.