0

I have this in my .vimrc, which is a key mapping to open my hosts file in a new tab:

nnoremap <Leader>hs :tabe /etc/hosts<cr>:set noreadonly<cr>

So now Vim won't bother me about readonly, which is great. However, when I save, I might compulsively hit s or :w. I would like to overwrite both (are they the same?) calls to call our normal NVW (nasty Vim way) to write as sudo:

:w !sudo tee % >/dev/null<cr>

But I would only like to do this for this current buffer, as in the hosts file. Some setlocal magic?

Andy Ray
  • 26,451
  • 11
  • 86
  • 123

1 Answers1

0

I'm assuming macvim since you are using command. I don't believe <D-S> does the same thing as :w but I don't know this for sure. You might be able to map to use a buffer local mapping if you wanted.

autocmd BufRead /etc/hosts nnoremap <buffer> <D-s> :w !sudo tee % >/dev/null<cr>

But you would first need to unmap it from the menu. Using something along the lines of this in your gvimrc.

macmenu File.Save key=<nop>

And add back the default behavior of save. The buffer local mapping will take precedence.

nnoremap <D-s> :w<CR>

You can override :w by using the technique found in Zyx's Answer on Aliasing a command in Vim. Which will replace :w with :w !sudo tee % >/dev/null if it is the only thing on line.

autocmd BufRead /etc/hosts cnoreabbrev <buffer> <expr> w ((getcmdtype() is# ':' && getcmdline() is# 'w')?('w !sudo tee % >/dev/null'):('w'))
Community
  • 1
  • 1
FDinoff
  • 28,493
  • 5
  • 67
  • 88