Skip to content

Instantly share code, notes, and snippets.

@avdgaag
Created October 6, 2009 08:41
Show Gist options
  • Save avdgaag/202868 to your computer and use it in GitHub Desktop.
Save avdgaag/202868 to your computer and use it in GitHub Desktop.
Convert plain text lists to HTML lists
# Simple function that takes a text list and creates an HTML list
# from it. This is useful as a textmate command when marking up
# plain text.
#
# This will take the following text:
#
# 1. line 1
# 2. line 2
#
# And output:
#
# <ol>
# <li>line 1</li>
# <li>line 2</li>
# </ol>
#
# When the lines start with a number, a <ol> is used. If not, a
# <ul> is used.
#
def to_list(text)
ol_prefix = /^\d+\.?\s*/
ul_prefix = /^[^\s]+\s*/
lines = text.split("\n").map { |line| line.strip }
if lines.any?
tag, pattern = lines.first =~ ol_prefix ? ['ol', ol_prefix] : ['ul', ul_prefix]
"<#{tag}>\n%s</#{tag}>" % lines.inject('') { |output, line| output += "\t<li>%s</li>\n" % line.gsub(pattern, '') }
else
text
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment