In vim, is it possible to use regular expressions in abbreviations? For example, something like
:iab \([0-9]\{-}\)nm \\SI{\1}{\\nano\\meter}
would would expand every instance of, say, '50nm' to '\SI{50}{\nano\meter}'.
In vim, is it possible to use regular expressions in abbreviations? For example, something like
:iab \([0-9]\{-}\)nm \\SI{\1}{\\nano\\meter}
would would expand every instance of, say, '50nm' to '\SI{50}{\nano\meter}'.
Your best bet is to write a little helper function to yourself. Tapping into omni completion or the user defined completion (C-x C-u
, see :help 'cfu'
) is a good choice. I sketched a regular function to imap on a key:
function! ExpandNanometers()
let items = matchlist(expand('<cword>'), '\v(\d+)nm')
if len(items) == 0
return
endif
let modified = '\SI{' . items[1] . '}{\nano\meter}'
exec "normal! ciw" . modified
endf
imap <C-l> <C-o>:call ExpandNanometers()<CR>
Not the best code, perhaps. Bound on insert-mode C-l
, it will replace words such as 50nm
to the desired if the cursor is on the word or directly after it.
I wanted to add this as a comment to the previous answer, but apparently I can't until 50 rep. I also know this is wayyy too late, but for reference purposes:
If key mappings are acceptable (going by the prev. answer), surely something like
imap <silent> <leader>obscure-key-of-choice <Esc>:%s/\v(\d+)nm/\\SI{\1}{\\nano\\meter}/g<CR>``i
(i.e. global substitute on the whole file with the desired patterns)
would be easier to maintain? I like to avoid vimscript for readability/maintenance of the .vimrc! Obviously you replace obscure-key-of-choice
by your obscure key of choice. You only have to do it once after having typed all the text anyway, so better save the other keys for more conventionally useful bindings!
The shortcut replaces something like
50nm blabla 73nm your-interesting-science-here 89nm
... some new lines...
we love nanometers nm! 34nm and finally 18nm
with something like
\SI{50}{\nano\meter} blabla \SI{73}{\nano\meter} your-interesting-science-here \SI{89}{\nano\meter}
... some new lines...
we love nanometers nm! \SI{34}{\nano\meter} and finally \SI{18}{\nano\meter}