require 'coderay' class Pry ## # Pry::Indent is a class that can be used to indent a number of lines # containing Ruby code similar as to how IRB does it (but better). The class # works by tokenizing a string using CodeRay and then looping over those # tokens. Based on the tokens in a line of code that line (or the next one) # will be indented or un-indented by 2 spaces. # # @author Yorick Peterse # @since 04-10-2011 # class Indent # Array containing all the indentation levels. attr_reader :stack # The amount of spaces to insert for each indent level. Spaces = ' ' # Hash containing all the tokens that should increase the indentation # level. The keys of this hash are open tokens, the values the matching # tokens that should prevent a line from being indented if they appear on # the same line. OpenTokens = { 'def' => 'end', 'class' => 'end', 'module' => 'end', 'do' => 'end', 'if' => 'end', 'while' => 'end', 'for' => 'end', '[' => ']', '{' => '}', } # Collection of tokens that decrease the indentation level. ClosingTokens = ['end', ']', '}'] # Collection of token types that should be ignored. Without this list # keywords such as "class" inside strings would cause the code to be # indented incorrectly. IgnoreTokens = [:space, :content, :string, :delimiter] # Collection of tokens that should only increase the indentation level of # the next line. OpenTokensNext = ['else', 'elsif'] ## # Creates a new instance of the class and starts with a fresh stack. The # stack is used to keep track of the indentation level for each line of # code. # # @author Yorick Peterse # @since 05-10-2011 # def initialize @stack = [] end ## # Get rid of all indentation def reset @stack.clear end ## # The current indentation level (number of spaces deep) def indent_level @stack.last end ## # Indents a string and returns it. This string can either be a single line # or multiple ones. # # @example # str = <