Sublime Forum

Sublime-syntax multiline regex variables

#1

Is it possible to use multiline regex in variables?

Maybe I’m doing it wrong.
Below I have two versions of each variable, one on a single line and one listed on multiple lines.

If the list variable is used after another variable, I get an error.
Comment/Uncomment the match to see:

Demo.sublime-syntax
%YAML 1.2

name: Demo
scope: source.demo

variables:
  lineIdentifier: '[a-zA-Z_][a-zA-Z_0-9]*'
  listIdentifier: |-
    (?x) # Ignore Comments and Newlines
    [a-zA-Z_] # May not start with a number
    [a-zA-Z_0-9]* # Subsequent characters

  lineWords: for|loop|until|while
  listWords: |-
    (?x) # Ignore Comments and Newlines
    for|
    loop|
    until|
    while

contexts:
  main:
    - match: '^\s*({{lineWords}})\s+({{lineIdentifier}})' # OK
    # - match: '^\s*({{listWords}})\s+({{lineIdentifier}})' # OK
    # - match: '^\s*({{lineWords}})\s+({{listIdentifier}})' # Error
    # - match: '^\s*({{listWords}})\s+({{listIdentifier}})' # Error
      captures:
        1: keyword
        2: storage

Test file:

loop var
for each
until true
while true

I get similar problems if the match itself is multiline

0 Likes

#2

Instead of (?x)stuff. use (?x:stuff).

Variables work by simple text replacement — the text of the variable is inserted verbatim into the including expression. For this reason, it’s always a good idea to make sure that every variable is a single, self-contained group. The (?x:stuff) syntax applies the x extended form option to the contents of the group.

Also, I don’t recall offhand the precedence rules, but is it possible that (?x)foo|bar is interpreted as (?x:foo)|bar rather than (?x:foo|bar)?

1 Like

#3

Perfect, thanks!

0 Likes