Skip to content

Commit

Permalink
The code action needs to fix up the line numbers
Browse files Browse the repository at this point in the history
Code mods deal with snippets of code that need to have their line
numbers fixed up by the code actions.
  • Loading branch information
scohen committed Dec 2, 2022
1 parent a0c7fd9 commit fd89980
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ defmodule ElixirLS.LanguageServer.Experimental.Provider.CodeAction.ReplaceWithUn
@moduledoc """
A code action that prefixes unused variables with an underscore
"""

alias ElixirLS.LanguageServer.Experimental.CodeMod
alias ElixirLS.LanguageServer.Experimental.CodeMod.Ast
alias ElixirLS.LanguageServer.Experimental.Protocol.Requests.CodeAction
alias ElixirLS.LanguageServer.Experimental.Protocol.Types.CodeAction, as: CodeActionResult
alias ElixirLS.LanguageServer.Experimental.Protocol.Types.Diagnostic
alias ElixirLS.LanguageServer.Experimental.Protocol.Types.TextEdit
alias ElixirLS.LanguageServer.Experimental.Protocol.Types.WorkspaceEdit
alias ElixirLS.LanguageServer.Experimental.SourceFile

Expand Down Expand Up @@ -37,6 +39,8 @@ defmodule ElixirLS.LanguageServer.Experimental.Provider.CodeAction.ReplaceWithUn
:error

[_ | _] ->
text_edits = Enum.map(text_edits, &update_line(&1, one_based_line))

reply =
CodeActionResult.new(
title: "Rename to _#{variable_name}",
Expand All @@ -49,6 +53,13 @@ defmodule ElixirLS.LanguageServer.Experimental.Provider.CodeAction.ReplaceWithUn
end
end

defp update_line(%TextEdit{} = text_edit, line_number) do
text_edit =
text_edit
|> put_in([:range, :start, :line], line_number - 1)
|> put_in([:range, :end, :line], line_number - 1)
end

defp extract_variable_and_line(%Diagnostic{} = diagnostic) do
with {:ok, variable_name} <- extract_variable_name(diagnostic.message),
{:ok, line} <- extract_line(diagnostic) do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,18 @@ defmodule ElixirLS.LanguageServer.Experimental.Provider.CodeAction.ReplaceWithUn
assert [%CodeActionReply{edit: %{changes: %{^file_uri => [edit]}}}] = apply(code_action)
assert edit.new_text == "_"
end

test "works with multiple lines" do
{file_uri, code_action} = ~S[
defmodule MyModule do
def my_func(a) do
end
end
] |> code_action("/project/file.ex", 1, "a")

assert [%CodeActionReply{edit: %{changes: %{^file_uri => [edit]}}}] = apply(code_action)
assert edit.new_text == "_"
assert edit.range.start.line == 1
assert edit.range.end.line == 1
end
end

0 comments on commit fd89980

Please sign in to comment.