Search code examples
regexemacsyasnippet

Regular expression as a trigger


One of the code conventions at work is to include a padding of one space inside square brackets and parenthesis. So list[ index ], not list[index]. Adding those spaces can be annoying, so I tried writing a snippet:

# name: Bracket
# key: [
# --
[ ${1:exp} ]

This works when the opening square bracket is preceded by a space or beginning of a line, but not when its preceded by an identifier. I think one way to do this would be to have the trigger be a regular expression:

# key: "[:ascii:]"[

Or something like that. Is this even possible? Or is there some other clever way to make this work? I'm writing this for python, but I think that shouldn't matter.

Thanks!


Solution

  • Minor mode solution

    I too have had to deal with such a coding standard. My initial solution was identical to @Francesco's based on autopair.

    However, I actually wanted to remove this padding in some cases, so made this minor-mode to be more flexible. I definitely recommend using it along with some kind of paired delimiter insertion tool (my favorite is autopair).

    See: delim-pad

    Using yasnippet

    Going down your original track of using yasnippet ... ( BTW autopair and yasnippet are both written by João Távora, both are very powerful and flexible. kudos to that guy! )

    Even if you got "[" recognized as a key, you would still have to keep pressing the trigger key to expand the snippet. That can get tired pretty quickly.

    Yasnippet also allows you to bind snippets to keys directly, so this will work:

    # -*- mode: snippet -*-
    # name: beginsquare
    # binding: [
    # --
    [ $0 ]