Skip to content

Instantly share code, notes, and snippets.

@avdgaag
Created October 6, 2009 07:39
Show Gist options
  • Save avdgaag/202835 to your computer and use it in GitHub Desktop.
Save avdgaag/202835 to your computer and use it in GitHub Desktop.
Simple ruby function to prevent widows in a piece of HTML
# Simple widow prevention in ruby
# given a piece of HTML (not just text) this will look for ending
# tags to common block-level elements that should not have widows
#
# This can be used as a TextMate command -- I've got it mapped
# to option-w. Simply put this in there, working on selected text or entire
# document.
def widont(text)
tags = %w{li p div dt dd legend label h1 h2 h3 h4 h5 h6}.join('|')
text.gsub(/(<(?:#{tags}).*?>.*?)([^\s]+)\s+([^\s]+)\s*(?=<\/(?:#{tags})>|<br ?\/?>)/, '\1\2&nbsp;\3')
end
# In a texmate command:
# print widont(STDIN.read)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment