Skip to content

Producing well-formatted code during editsΒ #923

Open
@matklad

Description

@matklad

Currently, we assists and fixes produced poorly formatted code: it uses exactly the same whitespace as specified during building of an edit, and it ignores indentation completely.

We need to figure out an API which will give us well-formatted edits.

I don't know how to handle this in a nice way, but I think something like this would work. Say, we want to handle add impl for a nested struct:

fn foo() {
    struct S {
        field: u32
    }
}

The assist initially produces some impl, and inserts it into the file "randomly". Note that insertion into the file is cheap, because trees are immutable. This will give us the following temporary file:

fn foo() {
    struct S {
        field: u32
    }impl S {}
}

We than find a freshly inserted node and reformat only this node, whihc gives use

fn foo() {
    struct S {
        field: u32
    }
    
    impl S {
    }
}

We using this reformatted node, we compute the final edit.

The code and tests for add impl example live in this file: https://github.com/rust-analyzer/rust-analyzer/blob/17aaece6b39c2fb525be0eccce4626fc622e8236/crates/ra_assists/src/add_impl.rs

There's a nascent formatting crate here: https://github.com/rust-analyzer/rust-analyzer/blob/17aaece6b39c2fb525be0eccce4626fc622e8236/crates/ra_fmt/src/lib.rs

I think, as a first step, we should only handle auto-indent.

Here's a Zulip stream to discuss the issue: https://rust-lang.zulipchat.com/#narrow/stream/185405-t-compiler.2Fwg-rls-2.2E0/topic/rust-analyzer.23923.3A.20producing.20nice.20code.20for.20refactorings

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-formattingformatting of r-a output/formatting on saveC-featureCategory: feature requestE-hardE-has-instructionsIssue has some instructions and pointers to code to get startedS-actionableSomeone could pick this issue up and work on it right nowfunA technically challenging issue with high impact

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions