Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on May 29th, 2013  |  syntax: VIM  |  size: 1.41 KB  |  views: 40  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. function! AtomicSave()
  2.   if (getftype(expand('<afile>')) == "file")|
  3.   if (writefile(getline(1, '$'), expand('<afile>').'.tmp') == 0)|
  4.     let l:filename = shellescape(expand('<afile>'))|
  5.     let l:tempfile = l:filename . '.tmp'|
  6.     " it's hard to grab the perms to make this portable. see http://mywiki.wooledge.org/BashFAQ/087
  7.     call system('! test -e ' . l:filename . ' || chmod --reference=' . l:filename . ' ' . l:tempfile)|
  8.     if v:shell_error|
  9.       echo "error setting permissions on temporary file: chmod returned " . v:shell_error|
  10.       return|
  11.     endif|
  12.     " NOTE: vim's "rename" erroneously calls "unlink" on its target!
  13.     " THIS DOES NOT WORK: if (rename(expand('<afile>').'.tmp', expand('<afile>')) == 0) | set nomodified | echo "error" | endif
  14.     call system('mv ' . l:tempfile . ' ' . l:filename)|
  15.     if v:shell_error|
  16.       echo "error renaming file: mv returned " . v:shell_error|
  17.     else|
  18.       echomsg l:filename . ' written (atomically)'|
  19.       set nomodified|
  20.     endif|
  21.   else|
  22.     echo "error writing file"|
  23.   endif|
  24.   else|
  25.     if (writefile(getline(1, '$'), expand('<afile>')) == 0)|
  26.       echomsg expand('<afile>') . ' written normally (file is a ' . getftype(expand('<afile>')) . ')'|
  27.       set nomodified|
  28.     else|
  29.       echo "error writing file"|
  30.     endif|
  31.   endif|
  32. endfunction
  33.  
  34. augroup atomicwrite
  35.         autocmd BufWriteCmd * call AtomicSave()
  36. augroup END
clone this paste RAW Paste Data