I had some automatically code generated files that I wanted to mark as read-only. I knew it was possible to flag a file as read-only in both emacs and vim. However, I found it really hard to Google for the exact syntax.

In Vim, the flags go in the file's "modelines", which by default can go anywhere in the first or last five lines of the file:

// vim:set ro:

In emacs, there is the "local variable list". Sometimes known as the "magic first line" or the "file mode line". This is a list of variables to set when the file is opened. So for a read only file, set the buffer-read-only variable:

// -\*- buffer-read-only:t -\*-

This only works on the first line of the file. There's a different form for the end of the file, follow the link to see details.

Here is a first line that flags the file as read only in both emacs and vim:

// vim:set ro: -\*- buffer-read-only:t -\*-

The code generator now automatically adds this line to generated C++, Erlang and Java files, in order to prevent accidental edits.

Thoughts on “Marking a file read-only in emacs and vim