Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to fold/collapse Rust documentation comments in Visual Studio Code?

In VSCode, is there any way to fold/collapse Rust documentation comments (i.e., newline comments which start with: //! and ///)? Swift has similar comments, so any answers pertaining to Swift may also be relevant to Rust.

If this is not supported in VSCode proper, are there any extensions that can accomplish the same?

like image 665
Centril Avatar asked Nov 07 '22 16:11

Centril


1 Answers

I was concerned by this as well, so I looked around. The good surprise is that since March 2018, it is possible to implement this thanks to a new folding provider API.

I did a little POC (the code is horrible and not secure, it is not intended to be used as is):

class CommentProvider implements vscode.FoldingRangeProvider {
    // This method must return a list of the foldable ranges
    provideFoldingRanges(document: vscode.TextDocument, context: vscode.FoldingContext, token: vscode.CancellationToken): vscode.ProviderResult<vscode.FoldingRange[]> {
        let ret: vscode.FoldingRange[] = [];
        for (let i = 0; i < document.lineCount; ++i) {
            let line = document.lineAt(i).text.trim();
            if (line.startsWith("//!")) {
                let from = i;
                do {
                    ++i;
                } while (document.lineAt(i).text.trim().startsWith("//!"));
                ret.push(new vscode.FoldingRange(from, i - 1));
            }
        }
        return ret;
    }
}

export function activate(context: vscode.ExtensionContext) {
    let sel: vscode.DocumentSelector = { scheme: 'file', language: 'rust' };
    let pro = new CommentProvider();
    vscode.languages.registerFoldingRangeProvider(sel, pro);
}

and it must be registered correctly in the package.json:

"activationEvents": [
    "onLanguage:rust"
],
"contributes": {
    "languages": [
        {
            "id": "rust",
            "aliases": [
                "rs"
            ],
            "extensions": [
                "rs"
            ],
            "configuration": "./language-configuration.json"
        }
    ]
},

I am not sure about the values, though.

The best would be to ask to the team doing the official rust extension to integrate this.

like image 160
Boiethios Avatar answered Nov 28 '22 07:11

Boiethios