Save this as mdrelink.py in the Packages folder, and you can run it with
view.run_command('mdrelink');
from the command console.
I think that I understood the order correctly - you need to reverse it, because otherwise it would ruin the already cached indexes of the following items. It should also automatically skip already used link numbers. My first Python and my first Sublime plugin, so please be careful with me.
import sublime, sublime_plugin class mdrelinkCommand(sublime_plugin.TextCommand): def run(self, edit): oldlinks = [] self.view.find_all("^\s*(\[\d+\]):", sublime.IGNORECASE, "\\1", oldlinks) newlinkpos = self.view.find_all("\[.+?\](\(.+?\))") orgtext = [] self.view.find_all("(\[.+?\])\(.+?\)", sublime.IGNORECASE, "\\1", orgtext) orglink = [] self.view.find_all("\[.+?\]\((.+?)\)", sublime.IGNORECASE, "\\1", orglink) orglink.reverse() self.view.insert(edit, self.view.size(), '\n\n') counter = 1 newnumbers = [] for r in newlinkpos: while '['+str(counter)+']' in oldlinks: counter += 1 oldlinks.append('['+str(counter)+']') line = '[' + str(counter)+']: '+ orglink.pop() + '\n' newnumbers.append(' ['+str(counter)+']') self.view.insert(edit, self.view.size(), line) for r in reversed(newlinkpos): self.view.replace(edit, r, orgtext.pop()+newnumbers.pop())
source share