Skip to content

Commit 3b662a9

Browse files
committed
Allow formatting code with a different base level of indentation
Being able to override the base level of indentation allows us to format parts of a document that may be nested.
1 parent 8fbcd1b commit 3b662a9

File tree

3 files changed

+40
-3
lines changed

3 files changed

+40
-3
lines changed

Diff for: lib/syntax_tree.rb

+6-1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ module SyntaxTree
4444
# It shouldn't really be changed except in very niche circumstances.
4545
DEFAULT_RUBY_VERSION = Formatter::SemanticVersion.new(RUBY_VERSION).freeze
4646

47+
# The default indentation level for formatting. We allow changing this so
48+
# that Syntax Tree can format arbitrary parts of a document.
49+
DEFAULT_INDENTATION = 0
50+
4751
# This is a hook provided so that plugins can register themselves as the
4852
# handler for a particular file type.
4953
def self.register_handler(extension, handler)
@@ -61,12 +65,13 @@ def self.parse(source)
6165
def self.format(
6266
source,
6367
maxwidth = DEFAULT_PRINT_WIDTH,
68+
base_indentation = DEFAULT_INDENTATION,
6469
options: Formatter::Options.new
6570
)
6671
formatter = Formatter.new(source, [], maxwidth, options: options)
6772
parse(source).format(formatter)
6873

69-
formatter.flush
74+
formatter.flush(base_indentation)
7075
formatter.output.join
7176
end
7277

Diff for: lib/syntax_tree/formatter.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,10 @@ def initialize(source, *args, options: Options.new)
8484
@target_ruby_version = options.target_ruby_version
8585
end
8686

87-
def self.format(source, node)
87+
def self.format(source, node, base_indentation = 0)
8888
q = new(source, [])
8989
q.format(node)
90-
q.flush
90+
q.flush(base_indentation)
9191
q.output.join
9292
end
9393

Diff for: test/formatting_test.rb

+32
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,37 @@ def test_stree_ignore
2727

2828
assert_equal(source, SyntaxTree.format(source))
2929
end
30+
31+
def test_formatting_with_different_indentation_level
32+
source = <<~SOURCE
33+
def foo
34+
puts "a"
35+
end
36+
SOURCE
37+
38+
# Default indentation
39+
assert_equal(source, SyntaxTree.format(source))
40+
41+
# Level 2
42+
assert_equal(<<-EXPECTED.chomp, SyntaxTree.format(source, 80, 2).rstrip)
43+
def foo
44+
puts "a"
45+
end
46+
EXPECTED
47+
48+
# Level 4
49+
assert_equal(<<-EXPECTED.chomp, SyntaxTree.format(source, 80, 4).rstrip)
50+
def foo
51+
puts "a"
52+
end
53+
EXPECTED
54+
55+
# Level 6
56+
assert_equal(<<-EXPECTED.chomp, SyntaxTree.format(source, 80, 6).rstrip)
57+
def foo
58+
puts "a"
59+
end
60+
EXPECTED
61+
end
3062
end
3163
end

0 commit comments

Comments
 (0)