Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/syntax_tree.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ module SyntaxTree
# It shouldn't really be changed except in very niche circumstances.
DEFAULT_RUBY_VERSION = Formatter::SemanticVersion.new(RUBY_VERSION).freeze

# The default indentation level for formatting. We allow changing this so
# that Syntax Tree can format arbitrary parts of a document.
DEFAULT_INDENTATION = 0

# This is a hook provided so that plugins can register themselves as the
# handler for a particular file type.
def self.register_handler(extension, handler)
Expand All @@ -61,12 +65,13 @@ def self.parse(source)
def self.format(
source,
maxwidth = DEFAULT_PRINT_WIDTH,
base_indentation = DEFAULT_INDENTATION,
options: Formatter::Options.new
)
formatter = Formatter.new(source, [], maxwidth, options: options)
parse(source).format(formatter)

formatter.flush
formatter.flush(base_indentation)
formatter.output.join
end

Expand Down
4 changes: 2 additions & 2 deletions lib/syntax_tree/formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,10 @@ def initialize(source, *args, options: Options.new)
@target_ruby_version = options.target_ruby_version
end

def self.format(source, node)
def self.format(source, node, base_indentation = 0)
q = new(source, [])
q.format(node)
q.flush
q.flush(base_indentation)
q.output.join
end

Expand Down
32 changes: 32 additions & 0 deletions test/formatting_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,37 @@ def test_stree_ignore

assert_equal(source, SyntaxTree.format(source))
end

def test_formatting_with_different_indentation_level
source = <<~SOURCE
def foo
puts "a"
end
SOURCE

# Default indentation
assert_equal(source, SyntaxTree.format(source))

# Level 2
assert_equal(<<-EXPECTED.chomp, SyntaxTree.format(source, 80, 2).rstrip)
def foo
puts "a"
end
EXPECTED

# Level 4
assert_equal(<<-EXPECTED.chomp, SyntaxTree.format(source, 80, 4).rstrip)
def foo
puts "a"
end
EXPECTED

# Level 6
assert_equal(<<-EXPECTED.chomp, SyntaxTree.format(source, 80, 6).rstrip)
def foo
puts "a"
end
EXPECTED
end
end
end