1

I'm trying to automate cleaning up old vim undo files that are for files that have since been deleted.

So far I've created a new vim script at ~/.vim/autoload/cleanupUndos.vim:

function cleanupUndos#clean()
    let undofiles = systemlist('ls /Users/me/.vim/undodir/')

    for undofile in undofiles
        let filepath = substitute(undofile, "%", "/", "g")
        if empty(glob(filepath))
            echo "File doesn't exist, deleting undofile for " filepath
            let deleteresult = delete(undofile)
            echo deleteresult == 0 ? 'SUCCEEDED' : 'FAILED'
        endif
    endfor
endfunction

And in my ~/.vimrc I've set the undofile and undodir and added the autocmd for running the cleanup:

set undofile
set undodir=/Users/me/.vim/undodir
autocmd VimEnter * :call cleanupUndos#clean()

The problem is that when I open vim, it immediately prints FAILED and none of the files ever get deleted. I can run the delete(filename) command in a vim session and it works, but it doesn't seem to work when run from the script. I've tried different ways of deleting files with no success.

How can I delete files from within a vimscript?

(I'm running Vim version 7.4.8056 on MacOS Sierra 10.12.6.)

migrated from unix.stackexchange.com Apr 26 '18 at 13:27

This question came from our site for users of Linux, FreeBSD and other Un*x-like operating systems.

  • Can you try using full(absolute) path of ls binary , you can find it with which command – rɑːdʒɑ Apr 24 '18 at 3:15
  • @Ten-Coin Thanks for the suggestion, but the ls command is working fine. I can see the full file paths being printed in the echo line. It's finding the right files, it just isn't deleting them. – Logan Apr 24 '18 at 16:12
  • Just checking, are you sure about permissions? – rɑːdʒɑ Apr 25 '18 at 6:49
  • @Ten-Coin what permissions exactly? I have rw permissions on cleanupUndos.vim, rw on all the undofiles, and rwx on the undodir. – Logan Apr 25 '18 at 16:08
1

You will need to escape file name since it contains "/". Try using

delete(fnameescape(filepath))

Check :help fnameescape for more information.

Hope this helps.

  • 1
    Thanks for the answer Ankit, but even after adding fnameescape, it is still failing to delete. – Logan Apr 26 '18 at 16:56
  • @Logan could you show the output of the echo command that you mentioned in your earlier comment? – Ankit Jain Apr 26 '18 at 17:30
  • File doesn't exist, deleting undofile for /Users/me/tmp/tmp.txt Then I press Enter and it replaces that text with FAILED – Logan Apr 26 '18 at 21:58
1

I recommend tpope's vim-eunuch for executing all these kinds of UNIX shell commands, which includes Delete, Move, Rename, Chmod, to just name a few of them. To install it, visit this page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.