Jay Ocean
Jay Ocean

Reputation: 273

Sublime Text Key Binding - app space between parentheses when press the space bar

I added a key binding that puts the selector in-between parenthesis when I press "(" in SublimeText.

{ "keys": ["("], "command": "insert_snippet", "args": {"contents": "(${0:$SELECTION})"}, "context":
  [
    { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
    { "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true }
  ]
},

However, I would like to create a key binding that turns (|) into ( | ) when I press the space bar and I am in-between the parenthesis.

Any ideas?

Upvotes: 0

Views: 42

Answers (1)

OdatNurd
OdatNurd

Reputation: 22831

For something like this you want a key binding such as the following:

{
    "keys": [" "],
    "command": "insert_snippet",
    "args": {
        "contents": " $0 "
    },
    "context": [
        // { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
        { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
        { "key": "preceding_text", "operator": "regex_contains", "operand": "\\($", "match_all": true },
        { "key": "following_text", "operator": "regex_contains", "operand": "^\\)", "match_all": true }
    ],
}

The insert_snippet command inserts a snippet containing two space characters with the cursor centered between them, while the context entries make the binding active only when there is no selection, the text prior to the cursor ends in a ( and the text following the cursor begins with a ).

As written this will always be active in this situation, but if desired you can also uncomment the first context entry here, which further restricts this binding to only be active when the auto_match_enabled setting is turned on. That would make it only active in cases where entering a single ( character would auto-insert the pairing character.

Upvotes: 1

Related Questions