How to change file permission from within vi

前端 未结 7 1946
庸人自扰
庸人自扰 2021-02-02 09:58

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 !

7条回答
  •  情书的邮戳
    2021-02-02 10:51

    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()
    

提交回复
热议问题