I sometimes open a read-only file in vi, forgetting to do chmod +w before opening it. Is there way to change the file from within vi?
Something like !
As David pointed out, setfperm() is the way to do this within vim.
Here are the mappings I use to add write or execute permissions to the current file:
function! ChmodPlus(expr, pat)
let file = expand('%')
let oldperms = getfperm(file)
let newperms = substitute(oldperms, a:expr, a:pat, '')
if (oldperms != newperms)
call setfperm(file, newperms)
endif
echom(printf('Permissions: %s', newperms))
endfunction
function! ChmodPlusX()
call ChmodPlus('^\(..\).', '\1x')
endfunction
function! ChmodPlusW()
call ChmodPlus('^\(.\).', '\1w')
endfunction
" Make current file writeable
noremap W :call ChmodPlusW()
" Make current file executable
noremap X :call ChmodPlusX()