11

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.

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
Rajeshwar
  • 379
  • 1
  • 2
  • 9

2 Answers2

12

You can set the file to read only and not modifiable

:set readonly
:set nomodifiable

For more help see:

:h 'readonly'
:h 'modifiable'
Peter Rincker
  • 15,854
  • 1
  • 36
  • 45
9

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.

Wildcard
  • 4,409
  • 26
  • 49