Skip to content

Instantly share code, notes, and snippets.

@janlelis
Created January 12, 2012 22:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janlelis/1603460 to your computer and use it in GitHub Desktop.
Save janlelis/1603460 to your computer and use it in GitHub Desktop.
gem install ruby_indentation
require 'coderay'
require 'set'
module RubyIndentation
VERSION = '0.2.0'
def self.[](buffer)
opening_and_modifier_tokens = %w[if unless until while].to_set
opening_tokens = %w[begin case class def for module do {].to_set
closing_tokens = %w[end }].to_set
separator = [';', :operator]
indent = 0
# parse each token
buffer_tokens = [separator] + CodeRay.scan(buffer, :ruby).each_slice(2).select{|_, kind|
kind != :space
}
buffer_tokens.each_cons(2){ |(*old_pair), (token, kind)|
if kind == :keyword || kind == :operator
# modifiers cause trouble, so
# fix it in 9/10 cases
if opening_tokens.include?(token) ||
opening_and_modifier_tokens.include?(token) &&
( old_pair == separator || old_pair == ['=', :operator ] )
indent += 1
elsif closing_tokens.include?(token)
indent -= 1
end
end
}
# return a good value
indent < 0 ? 0 : indent
end
end
# J-_-L
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment