Sublime Forum

How to match string and autofill in Sublime Text snippet?

#1

I have a scenario when using Sublime Text 4, In my markdown document, there is a single line string like this:

abbrlink: f5eb228d

I want to implement the following autofill function when I used Sublime Text snippet, When I input ‘pic’, hope a string like this is generated:

![](f5eb228d/)

Now, I created a snippet like this:

<snippet>
    	<content><![CDATA[
    ![]()
    ]]></content>
    	<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    	<tabTrigger>pic</tabTrigger>
    	<!-- Optional: Set a scope to limit where the snippet will trigger -->
    	<!-- <scope>source.python</scope> -->
    </snippet>

But I don’t know how to match f5eb228d in current opened file? Please help me how to complete this function, or have other solutions?

Thanks :slight_smile:

0 Likes

#2

A snippet alone can’t do something like this because a snippet is not programmable; it’s just a set of text that can be inserted.

For this you would need something like a small custom plugin that adds a completion which looks for that particular text and uses it in the snippet replacement.

Presumably you want this to work for multiple different types of link codes and not just specifically abbrLink: though, yes?

1 Like

#3

Following your idea,
I wrote a simple plug-in, which can well meet my usage scenarios.
Thanks a lot :slight_smile:

plugin code here:

import sublime
import sublime_plugin
import re

class autoinsertpictagCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # get all text
        all_text_region = self.view.substr(sublime.Region(0, self.view.size()))
        try:
            # match str with 'abbrlink: '
            match = re.findall(r'abbrlink: \w+', all_text_region)
            if match:
                # split
                target_abbrlink = match[0].split(" ")[1]
                selections = self.view.sel()
                self.view.insert(edit, selections[0].b, "![](" + target_abbrlink + "/)")
                sublime.status_message("auto insert successfully!")
            else:
                print("Can't find any abbrlink str!!")
        except Exception as e:
            print("Error auto insert: " + str(e))
0 Likes