Monday, 13 June 2016

SMILES depiction in Vim

I spend a lot of time scrolling through files of SMILES in Vim, and copying and pasting SMILES into viewers. This is now a thing of the past. I bring you (from the depths of time) molecule depiction within Vim.

Using the script below (paste it into your .vimrc), I just hit "\s" with the cursor on a SMILES string, and up pops its ASCII depiction (":q" to close). Need a bigger image? "\S" is your friend. This is my first Vim script ("and I hope it's your last" sez you) so if you have any improvements, let me know.

[Update 16/06/2014]: Script updated to handle quoted SMILES strings and those with escaped backslashes.
noremap <silent> <leader>s :call SmiToAscii(79)<CR>
noremap <silent> <leader>S :call SmiToAscii(189)<CR>
function! SmiToAscii(width)
  let smiles = expand("<cWORD>")
  " Strip quotation marks and commas
  let smiles = substitute(smiles, "[\"',]", "", "g")
  " Handle escaped backslashes, e.g. in C++ strings
  let smiles = substitute(smiles, "\\\\", "\\", "g")
  botright new
  setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap
  execute '$read ! obabel -:'.shellescape(smiles, 1). ' -o ascii -d -xa 2.0 -xw '. a:width
  setlocal nomodifiable
  1
endfunction

5 comments:

Geoff Hutchison said...

I think we need a "crazy chemistry hacks" blog. I nominate this as the first entry.

Noel O'Boyle said...

If you mean "crazy useful" and I know you did, count me in. :-)

Dave said...

You're my student's hero (I'm not a vimmer myself).

Noel O'Boyle said...

Crazy to some, hero to others. History will decide.

Kiran K Telukunta said...

Excellent snippet