From bdbe60e230b0c35a81320239dfe8725848bcb11a Mon Sep 17 00:00:00 2001 From: Fredrik Ekre Date: Sun, 21 Jul 2024 00:10:28 +0200 Subject: [PATCH] Replace tabs with spaces --- src/Runic.jl | 6 ++++-- src/runestone.jl | 17 +++++++++++++++++ test/runtests.jl | 5 +++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/Runic.jl b/src/Runic.jl index a371a46..9df1c94 100644 --- a/src/Runic.jl +++ b/src/Runic.jl @@ -39,8 +39,8 @@ struct Node tags::TagType end -function Node(head::JuliaSyntax.SyntaxHead, span::Integer) - return Node(head, span % UInt32, (), 0 % TagType) +function Node(head::JuliaSyntax.SyntaxHead, span::Integer, tags::Integer = 0) + return Node(head, span % UInt32, (), tags % TagType) end function Node(head::JuliaSyntax.SyntaxHead, kids::Vector{Node}) @@ -78,6 +78,7 @@ JuliaSyntax.span(node::Node) = span(node) # Matching JuliaSyntax.(head|span|flags|kind) head(node::Node) = node.head span(node::Node) = node.span +tags(node::Node) = node.tags flags(node::Node) = JuliaSyntax.flags(node) kind(node::Node) = JuliaSyntax.kind(node) @@ -298,6 +299,7 @@ function format_node!(ctx::Context, node::Node)::Union{Node, Nothing, NullNode} # Go through the runestone and apply transformations. ctx.call_depth += 1 + @return_something replace_tabs_with_four_spaces(ctx, node) @return_something no_leading_and_single_trailing_newline(ctx, node) @return_something max_three_consecutive_newlines(ctx, node) @return_something insert_delete_mark_newlines(ctx, node) diff --git a/src/runestone.jl b/src/runestone.jl index 2ed175e..067dde1 100644 --- a/src/runestone.jl +++ b/src/runestone.jl @@ -25,6 +25,23 @@ function trim_trailing_whitespace(ctx::Context, node::Node) return node′ end +function replace_tabs_with_four_spaces(ctx::Context, node::Node) + kind(node) in KSet"Whitespace NewlineWs" || return nothing + @assert is_leaf(node) + bytes = read_bytes(ctx, node) + tabidx = findfirst(x -> x == UInt8('\t'), bytes) + tabidx === nothing && return nothing + while tabidx !== nothing + bytes[tabidx] = UInt8(' ') + for _ in 1:3 + insert!(bytes, tabidx, UInt8(' ')) + end + tabidx = findnext(x -> x == UInt8('\t'), bytes, tabidx + 4) + end + nb = replace_bytes!(ctx, bytes, span(node)) + return Node(head(node), nb, tags(node)) +end + function format_hex_literals(ctx::Context, node::Node) kind(node) === K"HexInt" || return nothing @assert flags(node) == 0 diff --git a/test/runtests.jl b/test/runtests.jl index 406d8cc..a08647a 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -769,3 +769,8 @@ end @test format_string("$(nl)"; filemode = true) == "\n" end end + +@testset "https://youtu.be/SsoOG6ZeyUI?si=xpKpnczuqsOThtFP" begin + @test format_string("f(a,\tb)") == "f(a, b)" + @test format_string("begin\n\tx = 1\nend") == "begin\n x = 1\nend" +end