Last active
August 1, 2017 21:22
-
-
Save nelsonuhan/ec1f1cac4cae224634c584fb9a6fdb1c to your computer and use it in GitHub Desktop.
A quick-and-dirty QuickCursor replacement in Hammerspoon
This file contains hidden or 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
-- Quick-and-dirty QuickCursor replacement | |
-- Inspired by https://github.com/tjluoma/edit-anywhere | |
function quickcursor() | |
-- Get active application and window | |
local window = hs.window.focusedWindow() | |
local app = window:application() | |
-- Check to see if we're in a valid text field | |
-- (1) App is not invalid, (2) Paste is enabled | |
-- If not, stop | |
invalid_app = { | |
['Sublime Text'] = true, | |
} | |
paste = app:findMenuItem('Paste') | |
if (invalid_app[app:name()]) or (not paste['enabled']) then | |
hs.alert.show('Not a valid text field!') | |
return | |
end | |
-- Check to see if Cut is enabled | |
-- If so, use current selection; otherwise, select all | |
cut = app:findMenuItem('Cut') | |
if not cut['enabled'] then | |
hs.eventtap.keyStroke('cmd', 'a') | |
end | |
-- Copy selection | |
hs.eventtap.keyStroke('cmd', 'c') | |
-- Get copied text | |
copied_text = hs.pasteboard.getContents() | |
-- Write copied text to temp file | |
local tempfilepath = os.getenv('HOME') .. '/.quick_cursor.txt' | |
local tempfile = assert(io.open(tempfilepath, 'w')) | |
tempfile:write(copied_text) | |
tempfile:close() | |
-- Open temp file in Sublime Text | |
os.execute('open -a "Sublime Text" ' .. tempfilepath) | |
-- Get new Sublime Text window | |
-- Need to pause briefly to capture Sublime Text window | |
os.execute('sleep 1') | |
local subl_window = hs.window.focusedWindow() | |
-- Wait until Sublime Text window is destroyed | |
local watcher = subl_window:newWatcher( | |
function(win, event, watcher) | |
-- Switch back to original window | |
app:activate() | |
window:focus() | |
-- Put temp file into pasteboard | |
local tempfile = assert(io.open(tempfilepath, 'r')) | |
tempfilestr = tempfile:read('*all') | |
tempfile:close() | |
hs.pasteboard.setContents(tempfilestr) | |
-- Paste temp file | |
hs.eventtap.keyStroke('cmd', 'v') | |
-- Stop subscription | |
watcher:stop() | |
end | |
) | |
watcher:start({hs.window.watcher.elementDestroyed}) | |
end | |
hs.hotkey.bind('ctrl', '.', quickcursor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment