Skip to content

Instantly share code, notes, and snippets.

@persquare
Created September 3, 2014 20:30
Show Gist options
  • Save persquare/c493ac4e45af817cc977 to your computer and use it in GitHub Desktop.
Save persquare/c493ac4e45af817cc977 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python -S
"""Open a link (or Markdown style reference link) in TextMate's companion window."""
import os
import sys
import re
envvars = ['TM_BUNDLE_SUPPORT', 'TM_SUPPORT_PATH']
sys.path[:0] = [os.environ[v]+'/lib' for v in envvars if os.environ[v] not in sys.path]
import exit_codes as exit
MATCH_URL = r'.*?((?:https?://|file://|mailto:|message://)\S+)'
MATCH_REF_URL = r'.*?\[.+?\]\[(.+?)\]'
MATCH_REF_TEMPLATE = r'^.*?\[%s\]:(.+)'
MATCH_SCHEME = r'(.+?):'
def expand_reference(ref):
MATCH_REF = MATCH_REF_TEMPLATE % (ref,)
with sys.stdin as f:
for line in f:
line = line.rstrip()
match = re.match(MATCH_REF, line)
if match:
return match.group(1)
return None
def scan_line(line):
"""Scan line for URL or reference, return (URL or reference key, type)"""
URL = None
type = None
# Check for direct URL first
match = re.match(MATCH_URL, line)
if match:
return match.group(1)
# Check for reference URL
match = re.match(MATCH_REF_URL, line)
if not match:
return None
# So, it's a reference, scan doc for corresponding URL
return expand_reference(match.group(1))
def open_in_browser(url):
print "open in browser: %s" % (url)
exit.discard()
def open_in_textmate(url):
print """
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
window.location.href = "%s"
</script>
</head>
<body>
</body>
</html>
""" % (url)
# Main script
if os.environ.get('TM_SELECTED_TEXT', None):
print "handle selection"
# TM_SCOPE
# TM_SELECTION
else:
line = os.environ['TM_CURRENT_LINE']
line_number = os.environ['TM_LINE_NUMBER']
url = scan_line(line)
if not url:
exit.discard()
# Check scheme
# FIXME: Make this a setting?
# Will always match
match = re.match(MATCH_SCHEME, url)
scheme = match.group(1)
if scheme in ['http', 'https']:
open_in_textmate(url)
else:
os.system("open %s" % (url,))
@persquare
Copy link
Author

ToDo: Make this smarter, general, and extensible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment