1

I'm using the UltiSnips plugin. When selecting text, you can press the trigger key to enter Insert mode, and the deleted text can then be used in a subsequent snippet. The snippet I'm using is as following:

snippet # "Put in brackets" i
\\${1:emph}{${VISUAL}$2}$0
endsnippet

So the way I use it is I select some text, press my trigger key (<TAB>), enter #, and press tab again. That works fine, but I want to map it a key (<C-S-E>), such that I can simply select the text and press that key to do the same thing.

I've tried different ways, but none of them work:
vnoremap <buffer> <C-S-E> #
vnoremap <buffer> <C-S-E> :call UltiSnips#ExpandSnippet()#(<C-O>):call UltiSnips#ExpandSnippet()

function! WrapBrack()
    call UltiSnips#ExpandSnippet()
    normal i#
    call UltiSnips#ExpandSnippet()
    return ''
endfunction

vnoremap <buffer><expr> <C-S-E> WrapBrack()

This last one says that it won't allow autocommand to write because it's not safe, and I don't want to overrule that.

I don't know what to try next, and I can't find helpful documentation. Also I'm not very good with VimScript.

Here's the plugin settings I have:

Plug 'sirver/ultisnips'
let g:UltiSnipsExpandTrigger = '<tab>'
let g:UltiSnipsJumpForwardTrigger = '<tab>'
let g:UltiSnipsJumpBackwardTrigger = '<s-tab>'
let g:UltiSnipsSnippetDirectories=["UltiSnips", "my_snippets"]

1 Answer 1

1

The function to call would be UltiSnips#SaveLastVisualSelection(), as can be seen here, or by inspecting the output of :xnoremap <tab>.

Modifying from your mapping, this would be

vnoremap <buffer> <C-S-E> :call UltiSnips#SaveLastVisualSelection()<CR>gvs#(<C-O>):call UltiSnips#ExpandSnippet()<CR>

(remember to add a <CR> after a function is :called)

Note that, from my testing, the snippet expansion only occurs when the cursor is placed one character after the snippet trigger (# in your case). This means that using and expanding in insert-normal mode may not work as expected (since the cursor would be on #, instead of after it). A more robust solution would be to use the expression register <C-R>=, that is

xnoremap <buffer> <C-S-E> :<C-U>call UltiSnips#SaveLastVisualSelection()<CR>gvs#<C-R>=UltiSnips#ExpandSnippet()<CR>
2
  • 1
    I just saw your answer after finding myself the reference you linked and finally making it work... To make sure there is no unexpected behavior, I also copied the use of <C-R>=, resulting in vnoremap <buffer> <C-S-E> :call UltiSnips#SaveLastVisualSelection()<CR>gvs#<C-R>=UltiSnips#ExpandSnippet()
    – Alex867
    Sep 20, 2022 at 15:45
  • 1
    Good point... using <C-R>= in place of what I proposed (<space><Esc>) is a better solution.. Let me update my answer to use <C-R>=.
    – husB
    Sep 21, 2022 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.