Last active
June 1, 2021 02:58
-
-
Save UltraInstinct05/53acd9f84bb06e5a0d0ff37dead10c58 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sublime, sublime_plugin | |
class ReferenceLinkInputHandler(sublime_plugin.TextInputHandler): | |
def placeholder(self): | |
return "Type a link" | |
class ReferenceLinkCommand(sublime_plugin.TextCommand): | |
def run(self, edit, reference_link): | |
link_number = 1 | |
ref_links = self.view.find_by_selector("meta.link.reference.def.markdown") | |
pos = self.view.sel()[0] | |
entered_link = "https://" + reference_link | |
selected_text = self.view.substr(self.view.sel()[0]) | |
# If there is no reference link. | |
if len(ref_links) == 0: | |
self.view.replace(edit, pos, self.link_template(selected_text, link_number)) | |
self.view.insert(edit, self.view.size(), "\n\n" + self.reference_template(link_number, entered_link)) | |
return | |
# Find the largest reference link number. | |
max_link_num = 0 | |
for i in ref_links: | |
region = sublime.Region(i.begin(), i.end()) | |
link_num = self.view.substr(region).split(":", 1)[0][1] | |
if int(link_num) > int(max_link_num): | |
max_link_num = int(link_num) | |
# If the reference link is same as one already present. | |
for i in ref_links: | |
region = sublime.Region(i.begin(), i.end()) | |
actual_link = self.view.substr(region).split(":", 1)[1].strip() | |
link_num = self.view.substr(region).split(":", 1)[0][1] | |
if actual_link == entered_link: | |
self.view.replace(edit, pos, self.link_template(selected_text, link_num)) | |
return | |
self.view.replace(edit, pos, self.link_template(selected_text, max_link_num + 1)) | |
self.view.insert(edit, self.view.size(), "\n" + self.reference_template(max_link_num + 1, entered_link)) | |
def input(self, args): | |
if args is not None: | |
return ReferenceLinkInputHandler() | |
def input_description(self): | |
return "https://" | |
@staticmethod | |
def reference_template(link_number, link): | |
return "[{}]: {}".format(link_number, link) | |
@staticmethod | |
def link_template(text, link_number): | |
if text == "": | |
return "[Enter description here][{}]".format(link_number) | |
return "[{}][{}]".format(text, link_number) |
My code can format existing list to have a proper order and style. It can also add a new link.
That's great to see ! 🙂 My example plugin was mainly to give a starting point (since I don't work with reference links in Markdown all that much).
Yep, Your code was a great starting point for me. Thank You.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OK, I tried to learn how to write a plug in and this is what I came up with: