Hagai Naveh
Hagai Naveh

Reputation: 63

VIM autocommand on executable files

I want to run a VIM command only on loading of executable files (specifically, what I want, is to add a button to the menu bar, that will run the script, aka call :!%)

The question, of course is for non-windows based systems (like linux), where I cannot tell if a file is executable by its name (but by running ls -l)

Is there a way to do it with autocmd? Or any other way?

Upvotes: -1

Views: 52

Answers (2)

Friedrich
Friedrich

Reputation: 4667

When writing scripts, you would usually put a shebang on the first line to specify the interpreter to use. This is generally considered good practice and will remove any ambiguity on which program will run the script. While a script may work without a shebang in a specific environment, it won't be portable. Also see this answer to What is the default shebang if none is specified in a python script?.

Let's assume you're doing the right thing and start your script with a shebang.

You can make use of it by checking if the first two characters of the buffer equal #!. The following autocommand that will print either "executable" or "not executable" depending on the presence of a shebang:

augroup executable_script
    autocmd!
    autocmd BufEnter * echo getline(1)[:1]=='#!'?'executable':'not executable'
augroup END

It uses the getline() function to get the first line of the buffer. Its first two characters (yes, ranges are inclusive) are compared to the string '#!' and a ternary will return the resulting string to :echo.

For reference, see :help getline(), :help sublist, and :help ternary.

Upvotes: 1

phd
phd

Reputation: 94483

You cannot do that on Unix/Linux without first recognizing if the file is executable. So the way to implement what you want is: run an autocommand (BufReadPost, I think) on opening every file, check if it's executable. To check: use builtin function executable() with the full path of the current file. Try:

:echo executable(expand('%:p'))

Upvotes: 2

Related Questions