A Markdown hyperlink TextExpander snippet that works in Ulysses

I write a lot of Markdown, and I’ve long had a few simple TextExpander snippets that easily let me insert a markdown link to the front-most window in either Safari or Chrome. They are very simple, for example:

tell application "Safari"
	set t to name of current tab of window 1
	set U to URL of current tab of window 1
end tell
"[" & t & "](" & U & ")"

But… I’ve been recently using Ulysses for writing, which is a Markdown editor, mostly and sort of. It turns out that you cannot simply cut and paste a markdown link into Ulysses and expect it to work. You have to use a special menu command “Paste from Markdown” instead, which will convert Markdown into its internal format.

This breaks TextExpander snippet expansion as well. The way snippet expansion usually works is that it places the expanded text in the clipboard, pastes, and then restores the old content. It’s that second step—pasting—that breaks in Ulysses:

Broken snippet expansion

I worked around this with the below:

-- Insert a markdown link for the active safari window

-- Get the info we need from Safari
tell application "Safari"
	set t to name of current tab of window 1
	set U to URL of current tab of window 1
end tell

set mLink to  "[" & t & "](" & U & ")"

-- Get the name of the fontmost active app
tell application "System Events"
	set appName to name of first application process whose frontmost is true
end tell

if appName is not equal to "UlyssesMac" then
	-- For most apps, just do the normal TextExpander thing and return the text to insert
	return mLink
else
	-- Ulysses doesn't like pasting in Markdown directly, and needs a special Ulysses command
	-- So instead, need to manipulate the clipboard and paste using that command
	set the clipboard to mLink

	delay .5 -- Delay is necessary for this to work
	tell application "System Events"
		-- Use the "Paste from Markdown" command
		keystroke "v" using {command down, option down}
	end tell
end if

The way this works is:

  1. It grabs the necessary information from the browser.
  2. Determines which application is active.
  3. If the current application is not Ulysses, do the normal thing and return the expanded link from the script. TextExpander takes it and pastes it in.
  4. If this is Ulysses, then we have to get creative and short-circuit the usual expansion process:
    1. Place the link text into the system clipboard
    2. Pause for half a second.
    3. Trigger the “Paste from Markdown” command in the menu.
    4. Return an empty string from the snippet itself.

So essentially, for Ulysses, the TextExpander snippet itself expands into nothing, but instead directly manipulates the clipboard and keyboard. It’s hacky but it works:

Working snippet expansion

I’ve shared my Markdown Links TextExpander group, which has a few more examples.