My First Simple Sublime Text Plugin
Xiang Huang / 2023-03-22
I write my webpage content with Markdown. Each Markdown file start with the yaml head like this.
|
|
It is very annoying to enter the date: you have to look at the calendar if you are like me and you have to input “-” and numbers. So I want to insert the date automatically. How? There are solutions out there. But eventually you will need to bind the Python script you write with key strikes. However, there are key maps more than I can remember all ready. I don’t want to remember yet another key combination.
Here is what I want.
- Type
today. - Hit
Tab.
Can a snippet do this?
Unfortunately, it seems that snippet can just expand some text or do some regular expression. It does not execute commands. But the feature I want act exactly like a snippet.
Can I bind the command to Tab? Maybe, but Tab is very useful for a lot of other things, for example autocomplete, I don’t want to ruin that.
Let’s solve one problem at a time.
The Command/Script
I am not a programmer and I am not familiar with the Sublime Text API. With some googling, I manage to put up the following.
|
|
Testing the command by ctrl + ` and view.run_command(today_date), it works fine. Yes, you need to do today_date to execute a command name TodayDateComand. It is wired Sublime Text rule. I wrote it here in case I forgot it.
Tab magic
I still want the Tab magic. I need to detect when today appears in the text, and the I will call the today_date command. That is basically all the idea it takes. But I generalize it a bit. I wrote the following command MagicTab, to serve as a command menu: I can add whatever command I have later. What it does is to detect the words in the text just like a snippet and then call the command associate with those words.
It is like snippets, but more powerful! I tied the command menu to the Tab key, so I called it Magic Tab.
|
|
It is worth to note that in Line 35 of the above code, I do expand_snippet by default. There is no way I will give up all my snippets.
To build the key map, I add the following in the keymap file.
|
|
Now everything works as expected for me.
