How to change file permission from within vi

Viewed 44647

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 !r chmod +w [filename]?

Is there a shortcut to refer to the currently open file without spelling it's long name?

8 Answers

After editing your file with vim, press "esc" and then ":". Then type the following command:

w !sudo tee %

Then press "Enter". Then type

:q!

to successfully exit from the editor.

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 <silent> <Leader>W :call ChmodPlusW()<CR>

" Make current file executable
noremap <silent> <Leader>X :call ChmodPlusX()<CR>

You can also do this with the netrw module that comes with vim if your lazy, example :Texplore followed by scrolling to the file in normal mode and entering gp. Octal or symbolic at least work.

It's a little more intuitive with multiple files but per buffer-window without, use your colon command history to repeat commands.

Related