Skip to content
This repository has been archived by the owner on May 30, 2024. It is now read-only.

Add on type formatting with snippet support #193

Merged
merged 1 commit into from
Aug 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@
"type": "boolean",
"default": true
},
"onTypeFormatting": {
"description": "Enable on type formatting",
"type": "boolean",
"default": true
},
"diagnostics": {
"description": "Enable diagnostics, like RuboCop violations",
"type": "boolean",
Expand All @@ -99,7 +104,8 @@
"semanticHighlighting": true,
"formatting": true,
"diagnostics": true,
"codeActions": true
"codeActions": true,
"onTypeFormatting": true
}
}
}
Expand Down
56 changes: 56 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,62 @@ export default class Client {
initializationOptions: {
enabledFeatures: this.listOfEnabledFeatures(),
},
middleware: {
provideOnTypeFormattingEdits: async (
document,
position,
ch,
options,
token,
_next
) => {
if (this.client) {
const response: vscode.TextEdit[] | null =
await this.client.sendRequest(
"textDocument/onTypeFormatting",
{
textDocument: { uri: document.uri.toString() },
position,
ch,
options,
},
token
);

if (!response) {
return null;
}

// Find the $0 anchor to move the cursor
const cursorPosition = response.find(
(edit) => edit.newText === "$0"
);

if (!cursorPosition) {
return response;
}

// Remove the edit including the $0 anchor
response.splice(response.indexOf(cursorPosition), 1);

const workspaceEdit = new vscode.WorkspaceEdit();
workspaceEdit.set(document.uri, response);
await vscode.workspace.applyEdit(workspaceEdit);

await vscode.window.activeTextEditor!.insertSnippet(
new vscode.SnippetString(cursorPosition.newText),
new vscode.Selection(
cursorPosition.range.start,
cursorPosition.range.end
)
);

return null;
}

return undefined;
},
},
};

this.context = context;
Expand Down