1

With the following command, I'd like to glob for all .cpp files so that I can compile and run simple programs:

autocmd FileType cpp nnoremap <buffer><silent><localleader>cr :execute '!clear; g++ ' . expand(glob('*.cpp')) . '; ./a.out<CR>

Right now, the expand function outputs extra characters after each file:

E492: Not an editor command: Account.cpp^@CreditCard.cpp^@w3_in_lab.cpp

What am I doing wrong?

1 Answer 1

2

I'm not sure but you could try this autocmd:

autocmd FileType cpp nnoremap <buffer><silent><localleader>cr :execute '!clear; g++ ' . join(map(glob('*.cpp', 0, 1), 'shellescape(v:val, 1)')) . '; ./a.out'<CR>

If you don't pass a third argument to glob(), which evaluates to TRUE, the output is a string where the matches are separated by newline characters.

To avoid this, you could pass 1 as a third argument, so that the output is a list. Then, call join() to concatenate all the matches found by glob().

The second argument passed to glob() is 0. It means that your 'suffixes' and 'wildignore' options will apply during the expansion.

Also, since there could be characters inside your filenames, which have a special meaning to the shell or to Vim, you could call map() and shellescape() to protect them (passing 1, as a 2nd argument, to the latter).


It's not linked to your issue, but you could move this autocmd inside a filetype plugin, for example inside ~/.vim/after/ftplugin/cpp.vim, you would write something like:

nnoremap <buffer><silent> <key> :execute '!clear; g++ ' . join(map(glob('*.cpp', 0, 1), 'shellescape(v:val, 1)')) . '; ./a.out'<CR>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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