Last active
August 26, 2025 14:07
-
-
Save mtyurt/3529a999af675a0aff00eb14ab1fdde3 to your computer and use it in GitHub Desktop.
With pearofducs/ansible-vim plugin installed, following mapping behaves like `gf`, navigates to role under cursor's tasks/main.yml file. Ideal to be used in playbooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| " vim-plug example | |
| call plug#begin('~/.vim/plugged') | |
| Plug 'pearofducks/ansible-vim' | |
| call plug#end() | |
| let g:ansible_goto_role_paths = './roles,../_common/roles' | |
| function! FindAnsibleRoleUnderCursor() | |
| if exists("g:ansible_goto_role_paths") | |
| let l:role_paths = g:ansible_goto_role_paths | |
| else | |
| let l:role_paths = "./roles" | |
| endif | |
| let l:tasks_main = expand("<cfile>") . "/tasks/main.yml" | |
| let l:found_role_path = findfile(l:tasks_main, l:role_paths) | |
| if l:found_role_path == "" | |
| echo l:tasks_main . " not found" | |
| else | |
| execute "edit " . fnameescape(l:found_role_path) | |
| endif | |
| endfunction | |
| au BufRead,BufNewFile */ansible/*.yml nnoremap <leader>gr :call FindAnsibleRoleUnderCursor()<CR> | |
| au BufRead,BufNewFile */ansible/*.yml vnoremap <leader>gr :call FindAnsibleRoleUnderCursor()<CR> |
Author
@rjshrjndrn you are welcome!
But why are we having 2
aulines at the end.
First one is for normal mode, hence nnoremap; second one is for visual mode, hence vnoremap.
Thanks for the file extension addition :)
Stupid me.. Didn't notice the V in vnoremap haha.. Thanks though
While playing around with the function I noticed that findfile
- doesn't do tilde expansion and
- returns all files found in path (in a NULL-delimted string)
To fix this I changed the search portion to use globpath and return a list (the 1) and then edit the first file found.
I also search for .yaml as well as .yml:
...
let l:tasks_main = expand('<cfile>') . '/tasks/main.y*ml'
let l:found_role_path = globpath(l:role_paths, l:tasks_main, 0, 1)
if l:found_role_path == []
echo l:tasks_main . ' not found'
else
execute 'edit ' . fnameescape(l:found_role_path[0])
endif
...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the snippet. But why are we having 2
aulines at the end. And some people, atleast me, uses yaml as the extention.I think this will support both
ymlandyamlBufEnterwill be more efficient thanBufReadas we've to process only when we enter the butter.