8

I have a lot of files that have spaces in their names, and this is giving me problems. If I try to do command line completion for the find command, and one of these files come up, Vim will find it, but it won't load because the spaces aren't escaped.

Example: I'm in vim already, and I type

:find fo<Tab>

To complete foo bar.txt, Vim then finds it and throws an error because it expects only one filename. Meaning it now reads

:find foo bar.txt

Which doesn't load.

Is there any way to work around this, and have Vim automatically escape the spaces?

I am using VimTouch, which runs Vim 7.3

Edit: I recently realized that Vim will escape path names for me, but mysteriously won't do so for filenames.

A Gold Man
  • 221
  • 1
  • 6
  • 1
    This seems to be a command-line rather than a vim issue (at least, it sounds like you're talking about opening a vim session rather than performing something in vim); but, anyway, would placing a leading " work? That is, if you want to tab-complete file a b, type vim "a and then tab, rather than vim a and then tab? (I'm not sure, because, in both my vim and my shell, the space is automatically escaped when tab completing.) – LSpice Dec 07 '16 at 20:04
  • 1
    Can you elaborate what exactly you're doing? What does your buffer look like? What commands did you use? What exactly happened? – Martin Tournoij Dec 07 '16 at 20:13
  • I edited the question to clarify it. – A Gold Man Dec 08 '16 at 06:39

1 Answers1

2

:find foo bar.txt

This command will search for 2 files at once which is not possible in vim. This is the cause of your error.

When dealing with files that have space in them, you can append \ after every word

like so :find foo\ bar.txt

But this method is a bit awkward since you have a lot of files

so I have modified a command to suit your needs

Hope it works

Add it to your .vimrc

and use :Find to search and open files with spaces

" :Find will escape a file name and open it
command! -bang -nargs=* Find :call Find(<q-bang>, <q-args>) 
function! Find(bang, filename) 
    :exe "find".a:bang." ". fnameescape(a:filename) 
endfu

Not related to the asked question but might be of some help

This problem is also faced when saving files with space in them

like :w foo bar.txt gives error

To solve that

" :W and :Save will escape a file name and write it
command! -bang -nargs=* W :call W(<q-bang>, <q-args>) 
command! -bang -nargs=* Save :call Save(<q-bang>, <q-args>)

function! W(bang, filename) 
    :exe "w".a:bang." ". fnameescape(a:filename) 
endfu

function! Save(bang, filename) 
    :exe "save".a:bang." ". fnameescape(a:filename) 
endfu

Add this to .vimrc to use :W or :Save for saving files with spaces.

Ashok Arora
  • 859
  • 1
  • 7
  • 13