Skip to content

Instantly share code, notes, and snippets.

@kclem
Last active November 16, 2023 19:43
Show Gist options
  • Save kclem/8653488467f5a05f8fdd0a9b67d82eb7 to your computer and use it in GitHub Desktop.
Save kclem/8653488467f5a05f8fdd0a9b67d82eb7 to your computer and use it in GitHub Desktop.
" Put this in your ~/.vimrc
" Define the function to reverse complement a DNA sequence
" Run by calling <Leader>rc from normal mode. By default <Leader> is "\" so press \rc (you only have 1 second after \ to press rc)
function! ReverseComplement()
" Save the current cursor position
let save_cursor = getpos('.')
" Get the word under the cursor
let word = expand('<cword>')
" Define a dictionary for DNA base pairs
let base_pairs = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'a': 't', 't': 'a', 'c': 'g', 'g': 'c' }
" Create a variable for the reverse complement sequence
let rev_comp_seq = ''
" Iterate over each character in the word and get its complement
for i in range(len(word) - 1, -1, -1)
let char = word[i]
let rev_comp_seq .= get(base_pairs, char, char)
endfor
" Replace only the instance under the cursor with its reverse complement
execute 's/\%#' . word . '/' . rev_comp_seq . '/g'
" Restore the cursor position
call setpos('.', save_cursor)
endfunction
" Map a key sequence to call the ReverseComplement function
nnoremap <Leader>rc :call ReverseComplement()<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment