LuaSnip icon indicating copy to clipboard operation
LuaSnip copied to clipboard

Regex to trigger on range of characters

Open kristiansordal opened this issue 3 years ago • 5 comments

In regex, i can use \w{1,4} to search for any word characcter with length of 1-4. I want to use this functionality in LuaSnip, but it seems the {1,4} part doesnt work. I have the following snippet I want to get working:

s({ trig = "(\\%w{1,4}/(%d), regTrig = true}, {
    f(function(_, snip)
        return "\\frac{" .. snip.captures[1] .. "}{" .. snip.captures[2] .. "}"
    end, {})
}, {condition = tex.in_mathzone }),

How can I change this to get it working? it works fine without the {1,4} part.

kristiansordal avatar May 21 '22 19:05 kristiansordal

The triggers in luasnip are lua patterns not regexes, so the only way to avoid the expansion is to use a condition and check the captures by hand.

leiserfg avatar May 21 '22 19:05 leiserfg

The triggers in luasnip are lua patterns not regexes, so the only way to avoid the expansion is to use a condition and check the captures by hand.

This is an autosnippet btw. I got it working by changing the \\%w{1,4} to \\%w+. Though now it triggers on a word of any length. Id still like to limit the wordlength of the trigger condition.

What condition would you recommend?

kristiansordal avatar May 21 '22 20:05 kristiansordal

I think the best way to fix this is allowing vim-regex as well, although they might be a bit, so condition is your best bet now. Take a look here (condition), you can just check the length of matched_trigger and reject/accept.

L3MON4D3 avatar May 21 '22 21:05 L3MON4D3

I think the best way to fix this is allowing vim-regex as well, although they might be a bit, so condition is your best bet now.

Take a look here (condition), you can just check the length of matched_trigger and reject/accept.

Thanks! I got it working now

kristiansordal avatar May 23 '22 12:05 kristiansordal

Lua patterns don't support range quantifiers (like others said) but in this simple case you can get away with just using one required %w and three optional %w?s in the first capture group which accomplishes the same thing as regex \w{1,4}

function trig(s) return {s:match'^\\(%w%w?%w?%w?)/(%d)$'} end
trig'\\/0'      --> {}
trig'\\a/1'     --> {'a', '1'}
trig'\\ab/2'    --> {'ab', '2'}
trig'\\abc/3'   --> {'abc', '3'}
trig'\\abcd/4'  --> {'abcd', '4'}
trig'\\abcde/5' --> {}

harrygallagher4 avatar May 24 '22 03:05 harrygallagher4

I left this open for reminding me to add regex-trigger, but we have #547 now, so I'll close this.

L3MON4D3 avatar Aug 30 '22 19:08 L3MON4D3