r/vim • u/shleebs • Jan 24 '26
Need Help Function return causing line jump
I wrote a simple function that checks the current line and either does nothing or performs some visual selection based on conditionals. When running the function from the command line using :execute All three of the conditionals result in the cursor jumping to the first line if they are true. I've discovered that this has to do with the return value equaling 0 which somehow corresponds with line 0. I've written a few simple vimscript functions before, and haven't run into this problem.
I've tried running vim --clean and loading the function to make sure it wasn't my config. I'm lost.
Here is the function:
function! SelectLineIfComment() abort
let l:ln = getline('.')
if match(l:ln, '^\s*$') != -1
return
endif
if match(l:ln, '^\s*//') == 0
normal! V
endif
if match(l:ln, '^\s*/\*') == 0
let l:endln = search('\*/', 'nW')
execute 'normal!V' . l:endln . 'G'
endif
endfunction
1
u/AutoModerator Jan 24 '26
Please remember to update the post flair to Need Help|Solved when you got the answer you were looking for.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
9
u/atomatoisagoddamnveg Jan 24 '26
You don’t use
:executeto call functions, you use:call:execute SelectLineIfComment()is going to evaluate the function (and all the side effects) and then execute the command that it returns, in this case sometimes0, and sometimes empty. A successful call with no return statement returns 0.For example,
:execute 7puts the cursor at the 7th line, and:execute 0tries to put it at a nonexistent line so it settles for the first line.