Brendan Dawes
The Art of Form and Code

Ultisnips snippet to quickly create Markdown formatted links using content from the clipboard

When I'm writing a blog post or putting together some other article on my site, I often need to create links to content on the web. I do this using Markdown syntax — wrapping the words that will be the link with square brackets, creating open brackets then copy and pasting the link into the correct place. This all got a bit laborious so I thought there must be a way to use Ultisnips snippets to automate this process, maybe using it to grab a copied URL from the system clipboard.

My idea was to copy the needed URL from the browser, select the text that would be the link in visual mode and then use Ultisnips visual mode selection to auto insert a link in the correct format.

First I needed to find out how to get the copied text from the system clipboard. Vimscript has a function called getreg() which can get the contents of any register, including the system clipboard which is stored in the * register. Using getreg("*") would give me the contents of the system clipboard.

Handily, Ultisnips can use Vimscript inside a snippet, so after some trial and error I was able to create a snippet that would automatically create the link by selecting the words that would make up the link in visual mode, pressing CTRL-j (my Ultisnips trigger), typing the word link and then pressing CTRL-j again. My snippet would wrap the selected words correctly AND paste in the URL from the clipboard. Here's the final snippet:

snippet link