2

Let's say I have an UltiSnips snippet that shall replace all special characters with an underscore.

I have this:

snippet us "replace specials with underscores" w
${1:${VISUAL}}
`!p
import re
snip.rv = re.sub("[^0-9a-zA-Z]", "_", t[1])
`
endsnippet

Now something like Hello world! becomes:

Hello world!
Hello_World_

However, at the end, I would like to keep only the second line and discard what I typed initially. Is that possible? Maybe using post_expand?

Xiphias
  • 4,468
  • 4
  • 28
  • 51

1 Answers1

2

You dont need to write any python code. Your snippet is as simple as the following:

snippet us "replace specials with underscores" w
${1:${VISUAL/[^0-9a-zA-Z]/_/g}}
endsnippet

In a more general manner we are able to retrieve the text that was selected in visual mode through snip.v.text property. so just change t[1] to that and also remove ${1:${VISUAL}}:

snippet us "replace specials with underscores" w
`!p
import re
snip.rv = re.sub("[^0-9a-zA-Z]", "_", snip.v.text)
`
endsnippet
dNitro
  • 5,145
  • 2
  • 20
  • 45
  • Okay, okay. Thank you. However, my problem was a simplified one which you now solved, but for my real one, I need python. Do you know how to solve that as well? – Xiphias May 31 '16 at 17:09