Skip to content

Instantly share code, notes, and snippets.

@fracai
Last active August 29, 2015 14:04
Show Gist options
  • Save fracai/50d52bc2eaad719d7137 to your computer and use it in GitHub Desktop.
Save fracai/50d52bc2eaad719d7137 to your computer and use it in GitHub Desktop.
A nanoc filter for stripping blank lines and extraneous whitespace.
module Nanoc::Filters
class Compact < Nanoc::Filter
identifier :compact
def run(content, params={})
count_pre = 0
content.split("\n").each do |line|
line << "\n"
line.match('<pre>') { |m| count_pre +=1 }
line.match('</pre>') { |m| count_pre -=1 }
line.match('<code>') { |m| count_pre +=1 }
line.match('</code>') { |m| count_pre -=1 }
line.match('<script') { |m| count_pre +=1 }
line.match('</script>') { |m| count_pre -=1 }
# if we're inside any number of <pre> blocks, skip the reduction
if 0 == count_pre
line.gsub!(/[\r\n]/,' ') # turn line endings into spaces
line.gsub!(/\s+/,' ') # reduce serial whitespace to 1 character
line.gsub!(/>\s+</,'><') # zap whitespace between tags
line.gsub!(/>\s+$/,'>') # zap whitespace after tags
line.gsub!(/^\s+</,'<') # zap whitespace before tags
line.gsub!(/^\s*$/,'') # zap empty lines
else
line.gsub!(/^\s+<pre>/ , '<pre>')
line.gsub!(/^\s+<code>/ , '<code>')
line.gsub!(/^\s+<script/, '<script')
end
end.join('')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment