Last active
January 25, 2024 15:47
-
-
Save rafpaf/fb03020781e01a197a5c3f5329221b87 to your computer and use it in GitHub Desktop.
Vim function: toggle ".only" on the current jest test
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
" This function adds ".only" to the nearest "it(..." block above the cursor, or | |
" removes ".only" if that is already present. If a "describe..." block is | |
" nearer above the cursor than any "it..." block, ".only" is toggled on it. | |
function! ToggleJestOnlyGlobal() | |
let cursor_position = getpos('.') | |
let current_line = getline('.') | |
" Search backwards from the current line for the nearest occurrence of it( or describe( | |
let match_pos_it = search('\v(it|it\.only)\(', 'bcnW') | |
let match_pos_describe = search('\v(describe|describe\.only)\(', 'bcnW') | |
" If no match was found in backward search, reset cursor position and echo a message | |
if match_pos_it == 0 && match_pos_describe == 0 | |
call setpos('.', cursor_position) | |
echo "No 'it' or 'describe' block found." | |
return | |
endif | |
" Determine the nearest block to toggle .only | |
let nearest_match_pos = match_pos_it == 0 ? match_pos_describe : (match_pos_describe == 0 ? match_pos_it : (match_pos_it > match_pos_describe ? match_pos_it : match_pos_describe)) | |
let target_line = getline(nearest_match_pos) | |
let statement = target_line =~ '^\s*it\(\.only\)\?' ? 'it' : (target_line =~ '^\s*describe\(\.only\)\?' ? 'describe' : '') | |
if statement == '' | |
call setpos('.', cursor_position) | |
echo "No toggleable 'it' or 'describe' block found." | |
return | |
endif | |
" Perform the toggle on the identified line | |
if target_line =~ '\<'. statement . '\.only' | |
let modified_line = substitute(target_line, '\<'. statement . '\.only', statement, '') | |
else | |
let modified_line = substitute(target_line, '\<'. statement . '\>', statement . '.only', '') | |
endif | |
" Update the line with the modified content | |
call setline(nearest_match_pos, modified_line) | |
" Reset the cursor to its original position | |
call setpos('.', cursor_position) | |
endfunction | |
nnoremap <leader>jo :call ToggleJestOnlyGlobal()<CR> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment