Is there anyway I could make sure a file is locked so that I cant make any changes to it. Is there a command for locking / unlocking a file in vim. Some times i would like a file to be in readonly mode.
You can set the file to read only and not modifiable
:set readonly
:set nomodifiable
For more help see:
:h 'readonly'
:h 'modifiable'
-
1You can also use
vim -R
orview
to automatically open a file withreadonly
set (see:help -R
). – Martin Tournoij Apr 1 '16 at 1:18
The easiest way is to open the file using the -R
flag when opening the file to set the readonly
option.
vim -R filename.txt
vi -R filename.txt
For Vim, you can use the command view
when opening a file, which is equivalent to vim -R
:
view filename.txt
Note that the readonly option doesn't prevent a forced write. If you use :w!
the file will be written regardless. However, as a safety measure for "look don't touch", -R
can be very helpful in preventing accidental writes.
Another workaround you could use is to open an empty file buffer, and read in the file you want to look at:
vim
# Then, from inside vim:
:r filename.txt
This is fairly safe since you have an unnamed buffer—you can't accidentally overwrite the file you read in (although you could do so deliberately if you typed out the filename again). However you may not get automatic syntax highlighting this way, depending on your settings.
-
On many Unices, the
view
binary is often a hard-link of thevi
binary, and on those systems, even regularvi
, when it sees it has been invoked asview
, will open the file in read-only mode. So it's not vim-only – Olivier Dulac Apr 1 '16 at 12:18 -
-