Skip to content

Commit 4b495da

Browse files
committed
Transition OnEnter to WorkspaceSnippetEdit
This also changes our handiling of snippet edits on the client side. `editor.insertSnippet` unfortunately forces indentation, which we really don't want to have to deal with. So, let's just implement our manual hacky way of dealing with a simple subset of snippets we actually use in rust-analyzer
1 parent a4e6963 commit 4b495da

File tree

8 files changed

+97
-90
lines changed

8 files changed

+97
-90
lines changed

crates/ra_ide/src/typing/on_enter.rs

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,15 @@ pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<Sour
3838
}
3939

4040
let indent = node_indent(&file, comment.syntax())?;
41-
let inserted = format!("\n{}{} ", indent, prefix);
42-
let cursor_position = position.offset + TextSize::of(&inserted);
41+
let inserted = format!("\n{}{} $0", indent, prefix);
4342
let edit = TextEdit::insert(position.offset, inserted);
4443

45-
Some(
46-
SourceChange::source_file_edit(
47-
"On enter",
48-
SourceFileEdit { edit, file_id: position.file_id },
49-
)
50-
.with_cursor(FilePosition { offset: cursor_position, file_id: position.file_id }),
51-
)
44+
let mut res = SourceChange::source_file_edit(
45+
"On enter",
46+
SourceFileEdit { edit, file_id: position.file_id },
47+
);
48+
res.is_snippet = true;
49+
Some(res)
5250
}
5351

5452
fn followed_by_comment(comment: &ast::Comment) -> bool {
@@ -84,7 +82,7 @@ fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
8482

8583
#[cfg(test)]
8684
mod tests {
87-
use test_utils::{add_cursor, assert_eq_text, extract_offset};
85+
use test_utils::{assert_eq_text, extract_offset};
8886

8987
use crate::mock_analysis::single_file;
9088

@@ -98,7 +96,6 @@ mod tests {
9896
assert_eq!(result.source_file_edits.len(), 1);
9997
let mut actual = before.to_string();
10098
result.source_file_edits[0].edit.apply(&mut actual);
101-
let actual = add_cursor(&actual, result.cursor_position.unwrap().offset);
10299
Some(actual)
103100
}
104101

@@ -121,7 +118,7 @@ fn foo() {
121118
",
122119
r"
123120
/// Some docs
124-
/// <|>
121+
/// $0
125122
fn foo() {
126123
}
127124
",
@@ -137,7 +134,7 @@ impl S {
137134
r"
138135
impl S {
139136
/// Some
140-
/// <|> docs.
137+
/// $0 docs.
141138
fn foo() {}
142139
}
143140
",
@@ -151,7 +148,7 @@ fn foo() {
151148
",
152149
r"
153150
///
154-
/// <|> Some docs
151+
/// $0 Some docs
155152
fn foo() {
156153
}
157154
",
@@ -175,7 +172,7 @@ fn main() {
175172
r"
176173
fn main() {
177174
// Fix
178-
// <|> me
175+
// $0 me
179176
let x = 1 + 1;
180177
}
181178
",
@@ -195,7 +192,7 @@ fn main() {
195192
r"
196193
fn main() {
197194
// Fix
198-
// <|>
195+
// $0
199196
// me
200197
let x = 1 + 1;
201198
}

crates/rust-analyzer/src/lsp_ext.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ pub enum OnEnter {}
102102

103103
impl Request for OnEnter {
104104
type Params = lsp_types::TextDocumentPositionParams;
105-
type Result = Option<SourceChange>;
105+
type Result = Option<SnippetWorkspaceEdit>;
106106
const METHOD: &'static str = "rust-analyzer/onEnter";
107107
}
108108

crates/rust-analyzer/src/main_loop/handlers.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,12 +159,12 @@ pub fn handle_join_lines(
159159
pub fn handle_on_enter(
160160
world: WorldSnapshot,
161161
params: lsp_types::TextDocumentPositionParams,
162-
) -> Result<Option<lsp_ext::SourceChange>> {
162+
) -> Result<Option<lsp_ext::SnippetWorkspaceEdit>> {
163163
let _p = profile("handle_on_enter");
164164
let position = from_proto::file_position(&world, params)?;
165165
match world.analysis().on_enter(position)? {
166166
None => Ok(None),
167-
Some(source_change) => to_proto::source_change(&world, source_change).map(Some),
167+
Some(source_change) => to_proto::snippet_workspace_edit(&world, source_change).map(Some),
168168
}
169169
}
170170

crates/rust-analyzer/tests/heavy_tests/main.rs

Lines changed: 28 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -474,27 +474,21 @@ fn main() {{}}
474474
position: Position { line: 0, character: 5 },
475475
},
476476
json!({
477-
"cursorPosition": {
478-
"position": { "character": 4, "line": 1 },
479-
"textDocument": { "uri": "file:///[..]src/m0.rs" }
480-
},
481-
"label": "On enter",
482-
"workspaceEdit": {
483-
"documentChanges": [
484-
{
485-
"edits": [
486-
{
487-
"newText": "\n/// ",
488-
"range": {
489-
"end": { "character": 5, "line": 0 },
490-
"start": { "character": 5, "line": 0 }
491-
}
477+
"documentChanges": [
478+
{
479+
"edits": [
480+
{
481+
"insertTextFormat": 2,
482+
"newText": "\n/// $0",
483+
"range": {
484+
"end": { "character": 5, "line": 0 },
485+
"start": { "character": 5, "line": 0 }
492486
}
493-
],
494-
"textDocument": { "uri": "file:///[..]src/m0.rs", "version": null }
495-
}
496-
]
497-
}
487+
}
488+
],
489+
"textDocument": { "uri": "file:///[..]src/m0.rs", "version": null }
490+
}
491+
]
498492
}),
499493
);
500494
let elapsed = start.elapsed();
@@ -526,27 +520,21 @@ version = \"0.0.0\"
526520
position: Position { line: 0, character: 8 },
527521
},
528522
json!({
529-
"cursorPosition": {
530-
"position": { "line": 1, "character": 4 },
531-
"textDocument": { "uri": "file:///[..]src/main.rs" }
532-
},
533-
"label": "On enter",
534-
"workspaceEdit": {
535-
"documentChanges": [
536-
{
537-
"edits": [
538-
{
539-
"newText": "\r\n/// ",
540-
"range": {
541-
"end": { "line": 0, "character": 8 },
542-
"start": { "line": 0, "character": 8 }
543-
}
523+
"documentChanges": [
524+
{
525+
"edits": [
526+
{
527+
"insertTextFormat": 2,
528+
"newText": "\r\n/// $0",
529+
"range": {
530+
"end": { "line": 0, "character": 8 },
531+
"start": { "line": 0, "character": 8 }
544532
}
545-
],
546-
"textDocument": { "uri": "file:///[..]src/main.rs", "version": null }
547-
}
548-
]
549-
}
533+
}
534+
],
535+
"textDocument": { "uri": "file:///[..]src/main.rs", "version": null }
536+
}
537+
]
550538
}),
551539
);
552540
}

editors/code/src/commands/index.ts

Lines changed: 48 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -53,36 +53,57 @@ export function selectAndApplySourceChange(ctx: Ctx): Cmd {
5353
};
5454
}
5555

56-
export function applySnippetWorkspaceEdit(_ctx: Ctx): Cmd {
56+
export function applySnippetWorkspaceEditCommand(_ctx: Ctx): Cmd {
5757
return async (edit: vscode.WorkspaceEdit) => {
58-
assert(edit.entries().length === 1, `bad ws edit: ${JSON.stringify(edit)}`);
59-
const [uri, edits] = edit.entries()[0];
58+
await applySnippetWorkspaceEdit(edit);
59+
};
60+
}
61+
62+
export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) {
63+
assert(edit.entries().length === 1, `bad ws edit: ${JSON.stringify(edit)}`);
64+
const [uri, edits] = edit.entries()[0];
6065

61-
const editor = vscode.window.visibleTextEditors.find((it) => it.document.uri.toString() === uri.toString());
62-
if (!editor) return;
66+
const editor = vscode.window.visibleTextEditors.find((it) => it.document.uri.toString() === uri.toString());
67+
if (!editor) return;
6368

64-
let editWithSnippet: vscode.TextEdit | undefined = undefined;
65-
let lineDelta = 0;
66-
await editor.edit((builder) => {
67-
for (const indel of edits) {
68-
const isSnippet = indel.newText.indexOf('$0') !== -1 || indel.newText.indexOf('${') !== -1;
69-
if (isSnippet) {
70-
editWithSnippet = indel;
71-
} else {
72-
if (!editWithSnippet) {
73-
lineDelta = (indel.newText.match(/\n/g) || []).length - (indel.range.end.line - indel.range.start.line);
74-
}
75-
builder.replace(indel.range, indel.newText);
76-
}
69+
let selection: vscode.Selection | undefined = undefined;
70+
let lineDelta = 0;
71+
await editor.edit((builder) => {
72+
for (const indel of edits) {
73+
const parsed = parseSnippet(indel.newText);
74+
if (parsed) {
75+
const [newText, [placeholderStart, placeholderLength]] = parsed;
76+
const prefix = newText.substr(0, placeholderStart);
77+
const lastNewline = prefix.lastIndexOf('\n');
78+
79+
const startLine = indel.range.start.line + lineDelta + countLines(prefix);
80+
const startColumn = lastNewline === -1 ?
81+
indel.range.start.character + placeholderStart
82+
: prefix.length - lastNewline - 1;
83+
const endColumn = startColumn + placeholderLength;
84+
selection = new vscode.Selection(
85+
new vscode.Position(startLine, startColumn),
86+
new vscode.Position(startLine, endColumn),
87+
);
88+
builder.replace(indel.range, newText);
89+
} else {
90+
lineDelta = countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
91+
builder.replace(indel.range, indel.newText);
7792
}
78-
});
79-
if (editWithSnippet) {
80-
const snip = editWithSnippet as vscode.TextEdit;
81-
const range = snip.range.with(
82-
snip.range.start.with(snip.range.start.line + lineDelta),
83-
snip.range.end.with(snip.range.end.line + lineDelta),
84-
);
85-
await editor.insertSnippet(new vscode.SnippetString(snip.newText), range);
8693
}
87-
};
94+
});
95+
if (selection) editor.selection = selection;
96+
}
97+
98+
function parseSnippet(snip: string): [string, [number, number]] | undefined {
99+
const m = snip.match(/\$(0|\{0:([^}]*)\})/);
100+
if (!m) return undefined;
101+
const placeholder = m[2] ?? "";
102+
const range: [number, number] = [m.index!!, placeholder.length];
103+
const insert = snip.replace(m[0], placeholder);
104+
return [insert, range];
105+
}
106+
107+
function countLines(text: string): number {
108+
return (text.match(/\n/g) || []).length;
88109
}

editors/code/src/commands/on_enter.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import * as vscode from 'vscode';
22
import * as ra from '../rust-analyzer-api';
33

4-
import { applySourceChange } from '../source_change';
54
import { Cmd, Ctx } from '../ctx';
5+
import { applySnippetWorkspaceEdit } from '.';
66

77
async function handleKeypress(ctx: Ctx) {
88
const editor = ctx.activeRustEditor;
@@ -21,7 +21,8 @@ async function handleKeypress(ctx: Ctx) {
2121
});
2222
if (!change) return false;
2323

24-
await applySourceChange(ctx, change);
24+
const workspaceEdit = client.protocol2CodeConverter.asWorkspaceEdit(change);
25+
await applySnippetWorkspaceEdit(workspaceEdit);
2526
return true;
2627
}
2728

editors/code/src/main.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ export async function activate(context: vscode.ExtensionContext) {
9191
ctx.registerCommand('debugSingle', commands.debugSingle);
9292
ctx.registerCommand('showReferences', commands.showReferences);
9393
ctx.registerCommand('applySourceChange', commands.applySourceChange);
94-
ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEdit);
94+
ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand);
9595
ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange);
9696

9797
ctx.pushCleanup(activateTaskProvider(workspaceFolder));

editors/code/src/rust-analyzer-api.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export interface JoinLinesParams {
6969
export const joinLines = request<JoinLinesParams, SourceChange>("joinLines");
7070

7171

72-
export const onEnter = request<lc.TextDocumentPositionParams, Option<SourceChange>>("onEnter");
72+
export const onEnter = request<lc.TextDocumentPositionParams, Option<lc.WorkspaceEdit>>("onEnter");
7373

7474
export interface RunnablesParams {
7575
textDocument: lc.TextDocumentIdentifier;

0 commit comments

Comments
 (0)