Vim - Working with files and buffers
Buffers
:ls
to show list of buffers. These are just the in-memory representations of the files.
:bnext
, :bprevious
, :bfirst
, :blast
can be used to go between buffers
:bdelete
can be used to delete buffers. Ranges can be passed in to delete multiple buffers at once.
The argument list
:args
lists out the files passed as command line arguments on startup. However this can also be changed at runtime by passing in some values
:args <file1> <file2>
adds the files to the argument list and also opens them up (closing any existing open files).
:args `{cmd}`
runs {cmd}
in the shell and uses the result to fill in the argument list. This could for example be cat
ing a file to get the list of files to open.
:argdo {cmd}
executes an Ex command on all the files in the list.
:next
and :prev
traverses the files in the arg list
Changes to the files/buffers
Suffix !
to ignore changes when switchign buffers or exiting
:edit!
discards changes by re-reading file from disk
:qall!
quits vim discarding all changes in all buffers
:wall
writes all modified buffers to disk
Hidden setting
This is used when we want to disable the “nags” from vim when we try to switch from a modified buffer. This is useful when applying batches of commands to the arg list or buffers using :argdo
or :bufdo
.
Use :set hidden
or :set hid
to enable this.
Use :set nohidden
or :set nohid
to disable this.
Relative paths in commandline
%
represents the full path to the current file.
%:h
gets expanded to the path of the directory of the current file when used in the vim command line. For example: mkdir -p %:h
creates the directory for the current file’s path in cases where it does not exist.
Pressing <Tab>
after typing %:h also auto-completes the text with the directory of the current file.
Save file as super-user
When we forget to start vim as super-user:
:w !sudo tee % > /dev/null
This apparently fails in NeoVim as of now. There is a “suda” plugin or there is the sudo_exec function: here
See Also