Hammerspoon Clipboard Autosuggest

Reading time: about 2 minutes

I don’t like URLs with embedded tracking strings. As a result, I find myself editing lots of URLs to remove unnecessary data. Pasting a 300 character Amazon link into IRC dumps me with a bunch of guilt. Any attempt to navigate between Amazon pages produces these monstrosities:

When all you really need to get to the product is: https://www.amazon.com/gp/product/B0196I9O3A. From over 300 characters down to less than 50. About an 85% reduction in characters, and much less likely to wrap around a terminal window.

I’ve had hammerspoon installed for years and don’t do much with it, partially because I’m just frustrated with Lua for being so minimalistic that I have to scour a score of string.split implementations to perform simple tasks.

Recently I added a Spoon to my Hammerspoon config which is a library designed to make clipboard autosuggestions useful and practical to write.

This autosuggestor will trim an Amazon URL, removing both the querystring tracking parameters as well as any unnecessary URL segments.

hs.loadSpoon('ClipboardWatcher')

spoon.ClipboardWatcher:watch(
  -- matcher function. when it returns true, a correction will be suggested via notification
  function(data)
    return string.match(data, "https?://www%.amazon%.com")
  end,

  -- suggestion function. returned value will be applied if the notification is clicked
  function(original)
    local parsed_url = url.parse(original)
    -- Remove Amazon referral links
    parsed_url:setQuery({})

    local path_parts = split(parsed_url.path, "/")
    local new_path_parts = {}

    -- Remove extra url segments. Need to keep:
    -- ASIN length = 10
    -- weird url prefix length = 2 (dp, gp, etc)
    for i, part in pairs(path_parts) do
      local length = string.len(part)
      if length == 10 or length == 2 or part == "product" then
        table.insert(new_path_parts, part)
      end
    end

    parsed_url.path = table.concat(new_path_parts, "/")
    return parsed_url:build()
  end
)

spoon.ClipboardWatcher:start()

You can find the Clipboard Autosuggest Spoon in my dotfiles.

I found a Rock to parse and manipulate a URL, and manually copied it into my .hammerspoon directory.


Date: 2018-Apr-27
Tags: clipboard hammerspoon automation macos productivity
Previous: Secret secrets
Next: Desktop notifications after long running terminal commands finish