Skip to content

lsp: tracking issue for code actions features #445

@llllvvuu

Description

@llllvvuu

There are a couple of LSP features that I found harder than I expected to implement (and I am not a heavy user of these features), but if anyone happens to read this and enjoy the challenge, they are:

  1. Quickfix: Fix only the selected lint. Here's a template for how one might edit lsp.py (the TODO is the hard part):
def diagnostic_generator(
    self, uri: str, autofix: bool = False
) -> Optional[Generator[Result, bool, Optional[FileContent]]]:
    # ... existing code ...
    for result in generator:
        violation = result.violation
        if not violation:
            continue
        diagnostic = Diagnostic(
            # ... existing fields ...
            code=violation.rule_name,
            source="fixit",
            data={
                "fix": # TODO: convert violation.replacement, a CSTNode, to a replacement string
            },
        )
        diagnostics.append(diagnostic)
    # ... existing code ...

def code_action(self, params: CodeActionParams) -> List[CodeAction]:
    uri = params.text_document.uri
    diagnostics = params.context.diagnostics
    actions = []

    for diagnostic in diagnostics:
        if "fix" in diagnostic.data:
            fix = diagnostic.data["fix"]

            action = CodeAction(
                title=f"Fix: {diagnostic.code}",
                kind=CodeActionKind.QuickFix,
                edit=WorkspaceEdit(
                    changes={
                        uri: [
                            TextEdit(
                                range=diagnostic.range,
                                new_text=fix,
                            )
                        ]
                    }
                ),
            )
            actions.append(action)

    return actions
  1. Insert ignore comment: The hard part here is figuring out where to insert the comment.

For context, the code actions menu is the menu that comes from a light bulb next to the yellow squiggly under a lint issue. A good example of an extension that has this is the ESLint extension (built-in to VSCode I believe). Ruff also has these features, although I'm sure their model is very different so I'm not sure how easy it is to take inspiration.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions