“Lazy” Markdown reference links

Inspired by a workflow used at TidBits, here’s a script that allows you to use [*] reference links as lazy markers. The first [*]: http://... definition found after a [link][*] will be used as the definition for it. It’s easier to show:

This is my text and [this is my link][*]. I'll define
the url for that link under the paragraph.

[*]: http://brettterpstra.com

I can use [multiple][*] lazy links in [a paragraph][*],
and then just define them in order below it.

[*]: https://gist.github.com/ttscoff/7059952
[*]: http://blog.bignerdranch.com/4044-rock-heads/

This allows you to not bother naming or numbering links while writing, and easily move links along with their paragraphs without breaking numbering sequences or naming conventions.

It requires a little scripting to work, though, as you have to process the lazy links before running it through your normal processor. This script works as a Custom Preprocessor in Marked 2, as well as a standalone script as part of a chained workflow:

lazylink.rbraw
#!/usr/bin/env ruby
# encoding: utf-8
# Marked 2 preprocessor
# Allows use of `*` link references where the next [*]: href defines the link
# Inspired by [tidbits][*]
# [*]: http://tidbits.com
if RUBY_VERSION.to_f > 1.8
	input = STDIN.read.force_encoding('UTF-8')
else
	input = STDIN.read
end

counter = 0

while input =~ /(\[[^\]]+\]\s*\[)\*(\].*?^\[)\*\]\:/m
	input.sub!(/(\[[^\]]+\]\s*\[)\*(\].*?^\[)\*\]\:/m) {
		counter += 1
		$1 + counter.to_s + $2 + counter.to_s + "]:"
	}
end

print input

If this fits with the way you typically write, it’s a neat trick. Credit goes to Glenn Fleishman at TidBits for the idea and original implementation.

Brett Terpstra

Brett is a writer and developer living in Minnesota, USA. You can follow him as ttscoff on Twitter, GitHub, and Mastodon. Keep up with this blog by subscribing in your favorite news reader.

This content is supported by readers like you.

Join the conversation