Skip to content

Instantly share code, notes, and snippets.

@ap
Created October 12, 2010 20:58
Show Gist options
  • Save ap/622909 to your computer and use it in GitHub Desktop.
Save ap/622909 to your computer and use it in GitHub Desktop.
:Sudo command that saves files using sudo(1)
" defines a :Sudo command that works largely like :w
" but uses `sudo` to the file using root permissions
function! SudoWrite(file,line1,line2)
" intercept the external file change reload prompt event
autocmd FileChangedShell <buffer> :
" shazzam
exe 'silent' a:line1 . ',' . a:line2 . 'write !sudo tee 1>/dev/null' strlen(a:file) ? a:file : '%'
" force-trigger vim's file modification check, then undo the intercept
checktime | autocmd! FileChangedShell <buffer>
" if it was a whole-file write, tell vim to consider the buffer saved
if a:line1 == 1 && a:line2 == line('$') | set nomodified | endif
endfunction
command! -range=% -nargs=? -complete=file Sudo call SudoWrite(<q-args>,<q-line1>,<q-line2>)
@rtomayko
Copy link

You know about :w sudo:% or :saveas sudo:%? I think it's built in. Could be a plugin I don't remember installing.

@ap
Copy link
Author

ap commented Oct 13, 2010

That’s not built in. It could be either sudo.vim or SudoEdit.vim.

I used to use the former, but it does not seem to cope well with changing directories after opening a file – or something along those lines. In any case I ditched it after I wound up with files in the wrong place of my file system a couple of times.

I had not seen the latter until now, though. Might be worth giving a shot.

Then again, I have the above now, which does all I want…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment