Sublime Text Ctrl+P Like Fuzzy Matching In Few Lines of Python

There were a few people curious in the ST forums on how Sublime Text’s fuzzy matching works.

In reality, I don’t know either. There were some interesting solutions given, but I haven’t researched their methods and workability.

I needed to implement this for a small project I’m working on. I went with a solution that worked decently (I think I saw this within a JS fuzzy searching library). I’m not claiming it to be the best or the fastest (far from it, actually).

However, just in case you need to implement something like this, this might come in handy.

We first convert the string into a character array using list(pattern), and then map re.escape to the characters. Some characters have special meaning in regex, but we want the user’s input to be treated as a literal.

Then, we join the escaped characters using .*?. This would turn something like aad into a.*?a.*?d.

Comments

Nice post. I have a couple small notes. What’s the purpose of the call to “list”? “map” should iterate over a string just as well, I don’t think there is a need to convert it. I would rewrite “setPattern” as: