Vim Tips Wiki

Setting file attributes without reloading a buffer

Revision as of 05:18, July 13, 2012 by JohnBot (Talk | contribs)

1,619pages on
this wiki
Tip 212 Printable Monobook Previous Next

created 2002 · complexity intermediate · author Max Ischenko · version 6.0

While creating scripts and other executable files with Vim you need to set the Unix executable bit on the file.

You can do this from inside Vim with :!chmod a+x %. The % represents the current buffer's file name.

The problem is that Vim will notice attribute changes and prompt you to reload the file. If you do this, your undo history for the file will be lost.

The following function facilitates changing executable attributes without reloading a buffer. It accomplishes this feat by setting up a FileChangedShell autocmd that does nothing before running the external command, which means Vim will take no action when it detects the changed attributes. After making sure that Vim has detected the new file attributes using :checktime, the script removes the FileChangedShell autocmd again so that Vim acts normally for future file attribute changes.

function! SetExecutableBit()
  let fname = expand("%:p")
  execute "au FileChangedShell " . fname . " :echo"
  silent !chmod a+x %
  execute "au! FileChangedShell " . fname
command! Xbit call SetExecutableBit()

Now you can type :Xbit to make the file executable.


Using Max's idea, I came up with this code to toggle the read-only state of a file on Windows.

function! ToggleReadOnlyBit()
  let fname = fnameescape(substitute(expand("%:p"), "\\", "/", "g"))
  execute "au FileChangedShell " . fname . " :echo"
  if &readonly
    silent !attrib -r %
    silent !attrib +r %
  set invreadonly
  execute "au! FileChangedShell " . fname
command! XRU call ToggleReadOnlyBit()

Note that a simple let fname = expand("%:p") doesn't work on Windows since autocmd patterns need /'s instead on \'s. It also seemed prudent to escape the filename in case it had embedded spaces. 21:08, 7 November 2008 (UTC)


  • Does this command interfere with other FileChangedShell autocmds?

Around Wikia's network

Random Wiki