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'
  • 1
    You can also use vim -R or view to automatically open a file with readonly 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:

# 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 the vi binary, and on those systems, even regular vi, when it sees it has been invoked as view, will open the file in read-only mode. So it's not vim-only – Olivier Dulac Apr 1 '16 at 12:18
  • @OlivierDulac, perhaps not, but I don't see it specified in POSIX—either for ex or for vi. vi -R is specified. – Wildcard Apr 1 '16 at 16:22
  • Good point. Upvoted. – Olivier Dulac Apr 1 '16 at 17:38

Your Answer

