Skip to content

Instantly share code, notes, and snippets.

@zmpeg
Last active December 15, 2015 20:29
Show Gist options
  • Save zmpeg/5319298 to your computer and use it in GitHub Desktop.
Save zmpeg/5319298 to your computer and use it in GitHub Desktop.
Indent markup, removing cruft and matching indent lines.
#!/usr/bin/env ruby
IGNORE = ['BR', 'META', '!DOCTYPE', '!--']
def tab_change(tag)
tagname = tag.upcase.split(/[\s|>]/).first[1..-1]
is_open = tag[1] != '/'
return 0 if IGNORE.include? tagname
return 0 if is_open && tag.include?("/#{tagname}")
is_open ? 1 : -1
end
ARGV.each do |file|
file = File.open(file, 'rb').read
# Remove Repeated Spaces
file = file.gsub /\s+/, ' '
# Remove Line Breaks
file = file.gsub /\n/, ''
# Remove spaces between Tags
file = file.gsub />\s</, '><'
# Remove Spaces After Tags
file = file.gsub />\s/, '><'
# Put one tag per line.
file = file.gsub /></, ">\n<"
tabcount = 0
file = file.split("\n").map do |line|
change = tab_change line
tabcount += change if change < 0
tabs = " " * tabcount
tabcount += change if change > 0
# "#{change == -1 ? '-' : '+'}: #{tabcount}: #{tabs} #{line}"
"#{tabs}#{line}"
end.join("\n")
puts file
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment