Last active
June 27, 2024 09:16
-
-
Save akirk/0e28d7906151307263c2c0a79b5ee515 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
# Assign to a shortcut, for example: | |
# { "keys": ["ctrl+shift+a"], "command": "paste_as_link" }, | |
# If you have a text selected and a link in the clipboard, this will make a HTML or Markdown link out of it. | |
import sublime | |
import sublime_plugin | |
import re | |
class PasteAsLinkCommand(sublime_plugin.TextCommand): | |
def run(self, edit): | |
clipboard_text = sublime.get_clipboard() | |
if not self.is_valid_url(clipboard_text): | |
sublime.status_message("The clipboard does not contain a valid URL.") | |
return | |
if self.view.match_selector(0, "text.html.basic"): | |
for region in self.view.sel(): | |
if not region.empty(): | |
selected_text = self.view.substr(region) | |
self.view.insert(edit, region.end(), '</a>') | |
self.view.insert(edit, region.begin(), '">') | |
self.view.insert(edit, region.begin(), clipboard_text) | |
self.view.insert(edit, region.begin(), '<a href="') | |
elif self.view.match_selector(0, "text.html.markdown"): | |
for region in self.view.sel(): | |
if not region.empty(): | |
selected_text = self.view.substr(region) | |
self.view.insert(edit, region.end(), ')') | |
self.view.insert(edit, region.end(), clipboard_text) | |
self.view.insert(edit, region.end(), '](') | |
self.view.insert(edit, region.begin(), '[') | |
def is_valid_url(self, text): | |
# A simple URL validation regex pattern | |
url_pattern = re.compile(r'^(https?|ftp)://[^\s/$.?#].[^\s]*$') | |
return bool(re.match(url_pattern, text)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment