aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--crates/ra_ide/src/typing/on_enter.rs29
-rw-r--r--crates/rust-analyzer/src/lsp_ext.rs2
-rw-r--r--crates/rust-analyzer/src/main_loop/handlers.rs4
-rw-r--r--crates/rust-analyzer/tests/heavy_tests/main.rs68
-rw-r--r--editors/code/src/commands/index.ts75
-rw-r--r--editors/code/src/commands/on_enter.ts5
-rw-r--r--editors/code/src/main.ts2
-rw-r--r--editors/code/src/rust-analyzer-api.ts2
8 files changed, 97 insertions, 90 deletions
diff --git a/crates/ra_ide/src/typing/on_enter.rs b/crates/ra_ide/src/typing/on_enter.rs
index 78a40cc94..85be14ad3 100644
--- a/crates/ra_ide/src/typing/on_enter.rs
+++ b/crates/ra_ide/src/typing/on_enter.rs
@@ -38,17 +38,15 @@ pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<Sour
38 } 38 }
39 39
40 let indent = node_indent(&file, comment.syntax())?; 40 let indent = node_indent(&file, comment.syntax())?;
41 let inserted = format!("\n{}{} ", indent, prefix); 41 let inserted = format!("\n{}{} $0", indent, prefix);
42 let cursor_position = position.offset + TextSize::of(&inserted);
43 let edit = TextEdit::insert(position.offset, inserted); 42 let edit = TextEdit::insert(position.offset, inserted);
44 43
45 Some( 44 let mut res = SourceChange::source_file_edit(
46 SourceChange::source_file_edit( 45 "On enter",
47 "On enter", 46 SourceFileEdit { edit, file_id: position.file_id },
48 SourceFileEdit { edit, file_id: position.file_id }, 47 );
49 ) 48 res.is_snippet = true;
50 .with_cursor(FilePosition { offset: cursor_position, file_id: position.file_id }), 49 Some(res)
51 )
52} 50}
53 51
54fn followed_by_comment(comment: &ast::Comment) -> bool { 52fn followed_by_comment(comment: &ast::Comment) -> bool {
@@ -84,7 +82,7 @@ fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
84 82
85#[cfg(test)] 83#[cfg(test)]
86mod tests { 84mod tests {
87 use test_utils::{add_cursor, assert_eq_text, extract_offset}; 85 use test_utils::{assert_eq_text, extract_offset};
88 86
89 use crate::mock_analysis::single_file; 87 use crate::mock_analysis::single_file;
90 88
@@ -98,7 +96,6 @@ mod tests {
98 assert_eq!(result.source_file_edits.len(), 1); 96 assert_eq!(result.source_file_edits.len(), 1);
99 let mut actual = before.to_string(); 97 let mut actual = before.to_string();
100 result.source_file_edits[0].edit.apply(&mut actual); 98 result.source_file_edits[0].edit.apply(&mut actual);
101 let actual = add_cursor(&actual, result.cursor_position.unwrap().offset);
102 Some(actual) 99 Some(actual)
103 } 100 }
104 101
@@ -121,7 +118,7 @@ fn foo() {
121", 118",
122 r" 119 r"
123/// Some docs 120/// Some docs
124/// <|> 121/// $0
125fn foo() { 122fn foo() {
126} 123}
127", 124",
@@ -137,7 +134,7 @@ impl S {
137 r" 134 r"
138impl S { 135impl S {
139 /// Some 136 /// Some
140 /// <|> docs. 137 /// $0 docs.
141 fn foo() {} 138 fn foo() {}
142} 139}
143", 140",
@@ -151,7 +148,7 @@ fn foo() {
151", 148",
152 r" 149 r"
153/// 150///
154/// <|> Some docs 151/// $0 Some docs
155fn foo() { 152fn foo() {
156} 153}
157", 154",
@@ -175,7 +172,7 @@ fn main() {
175 r" 172 r"
176fn main() { 173fn main() {
177 // Fix 174 // Fix
178 // <|> me 175 // $0 me
179 let x = 1 + 1; 176 let x = 1 + 1;
180} 177}
181", 178",
@@ -195,7 +192,7 @@ fn main() {
195 r" 192 r"
196fn main() { 193fn main() {
197 // Fix 194 // Fix
198 // <|> 195 // $0
199 // me 196 // me
200 let x = 1 + 1; 197 let x = 1 + 1;
201} 198}
diff --git a/crates/rust-analyzer/src/lsp_ext.rs b/crates/rust-analyzer/src/lsp_ext.rs
index f75a26eb7..3c7bd609d 100644
--- a/crates/rust-analyzer/src/lsp_ext.rs
+++ b/crates/rust-analyzer/src/lsp_ext.rs
@@ -102,7 +102,7 @@ pub enum OnEnter {}
102 102
103impl Request for OnEnter { 103impl Request for OnEnter {
104 type Params = lsp_types::TextDocumentPositionParams; 104 type Params = lsp_types::TextDocumentPositionParams;
105 type Result = Option<SourceChange>; 105 type Result = Option<SnippetWorkspaceEdit>;
106 const METHOD: &'static str = "rust-analyzer/onEnter"; 106 const METHOD: &'static str = "rust-analyzer/onEnter";
107} 107}
108 108
diff --git a/crates/rust-analyzer/src/main_loop/handlers.rs b/crates/rust-analyzer/src/main_loop/handlers.rs
index be6a0aece..fcf08cd79 100644
--- a/crates/rust-analyzer/src/main_loop/handlers.rs
+++ b/crates/rust-analyzer/src/main_loop/handlers.rs
@@ -159,12 +159,12 @@ pub fn handle_join_lines(
159pub fn handle_on_enter( 159pub fn handle_on_enter(
160 world: WorldSnapshot, 160 world: WorldSnapshot,
161 params: lsp_types::TextDocumentPositionParams, 161 params: lsp_types::TextDocumentPositionParams,
162) -> Result<Option<lsp_ext::SourceChange>> { 162) -> Result<Option<lsp_ext::SnippetWorkspaceEdit>> {
163 let _p = profile("handle_on_enter"); 163 let _p = profile("handle_on_enter");
164 let position = from_proto::file_position(&world, params)?; 164 let position = from_proto::file_position(&world, params)?;
165 match world.analysis().on_enter(position)? { 165 match world.analysis().on_enter(position)? {
166 None => Ok(None), 166 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),
168 } 168 }
169} 169}
170 170
diff --git a/crates/rust-analyzer/tests/heavy_tests/main.rs b/crates/rust-analyzer/tests/heavy_tests/main.rs
index 74676b3ee..4e94c37e1 100644
--- a/crates/rust-analyzer/tests/heavy_tests/main.rs
+++ b/crates/rust-analyzer/tests/heavy_tests/main.rs
@@ -474,27 +474,21 @@ fn main() {{}}
474 position: Position { line: 0, character: 5 }, 474 position: Position { line: 0, character: 5 },
475 }, 475 },
476 json!({ 476 json!({
477 "cursorPosition": { 477 "documentChanges": [
478 "position": { "character": 4, "line": 1 }, 478 {
479 "textDocument": { "uri": "file:///[..]src/m0.rs" } 479 "edits": [
480 }, 480 {
481 "label": "On enter", 481 "insertTextFormat": 2,
482 "workspaceEdit": { 482 "newText": "\n/// $0",
483 "documentChanges": [ 483 "range": {
484 { 484 "end": { "character": 5, "line": 0 },
485 "edits": [ 485 "start": { "character": 5, "line": 0 }
486 {
487 "newText": "\n/// ",
488 "range": {
489 "end": { "character": 5, "line": 0 },
490 "start": { "character": 5, "line": 0 }
491 }
492 } 486 }
493 ], 487 }
494 "textDocument": { "uri": "file:///[..]src/m0.rs", "version": null } 488 ],
495 } 489 "textDocument": { "uri": "file:///[..]src/m0.rs", "version": null }
496 ] 490 }
497 } 491 ]
498 }), 492 }),
499 ); 493 );
500 let elapsed = start.elapsed(); 494 let elapsed = start.elapsed();
@@ -526,27 +520,21 @@ version = \"0.0.0\"
526 position: Position { line: 0, character: 8 }, 520 position: Position { line: 0, character: 8 },
527 }, 521 },
528 json!({ 522 json!({
529 "cursorPosition": { 523 "documentChanges": [
530 "position": { "line": 1, "character": 4 }, 524 {
531 "textDocument": { "uri": "file:///[..]src/main.rs" } 525 "edits": [
532 }, 526 {
533 "label": "On enter", 527 "insertTextFormat": 2,
534 "workspaceEdit": { 528 "newText": "\r\n/// $0",
535 "documentChanges": [ 529 "range": {
536 { 530 "end": { "line": 0, "character": 8 },
537 "edits": [ 531 "start": { "line": 0, "character": 8 }
538 {
539 "newText": "\r\n/// ",
540 "range": {
541 "end": { "line": 0, "character": 8 },
542 "start": { "line": 0, "character": 8 }
543 }
544 } 532 }
545 ], 533 }
546 "textDocument": { "uri": "file:///[..]src/main.rs", "version": null } 534 ],
547 } 535 "textDocument": { "uri": "file:///[..]src/main.rs", "version": null }
548 ] 536 }
549 } 537 ]
550 }), 538 }),
551 ); 539 );
552} 540}
diff --git a/editors/code/src/commands/index.ts b/editors/code/src/commands/index.ts
index 0937b495c..e5ed77e32 100644
--- a/editors/code/src/commands/index.ts
+++ b/editors/code/src/commands/index.ts
@@ -53,36 +53,57 @@ export function selectAndApplySourceChange(ctx: Ctx): Cmd {
53 }; 53 };
54} 54}
55 55
56export function applySnippetWorkspaceEdit(_ctx: Ctx): Cmd { 56export function applySnippetWorkspaceEditCommand(_ctx: Ctx): Cmd {
57 return async (edit: vscode.WorkspaceEdit) => { 57 return async (edit: vscode.WorkspaceEdit) => {
58 assert(edit.entries().length === 1, `bad ws edit: ${JSON.stringify(edit)}`); 58 await applySnippetWorkspaceEdit(edit);
59 const [uri, edits] = edit.entries()[0]; 59 };
60}
61
62export 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];
60 65
61 const editor = vscode.window.visibleTextEditors.find((it) => it.document.uri.toString() === uri.toString()); 66 const editor = vscode.window.visibleTextEditors.find((it) => it.document.uri.toString() === uri.toString());
62 if (!editor) return; 67 if (!editor) return;
63 68
64 let editWithSnippet: vscode.TextEdit | undefined = undefined; 69 let selection: vscode.Selection | undefined = undefined;
65 let lineDelta = 0; 70 let lineDelta = 0;
66 await editor.edit((builder) => { 71 await editor.edit((builder) => {
67 for (const indel of edits) { 72 for (const indel of edits) {
68 const isSnippet = indel.newText.indexOf('$0') !== -1 || indel.newText.indexOf('${') !== -1; 73 const parsed = parseSnippet(indel.newText);
69 if (isSnippet) { 74 if (parsed) {
70 editWithSnippet = indel; 75 const [newText, [placeholderStart, placeholderLength]] = parsed;
71 } else { 76 const prefix = newText.substr(0, placeholderStart);
72 if (!editWithSnippet) { 77 const lastNewline = prefix.lastIndexOf('\n');
73 lineDelta = (indel.newText.match(/\n/g) || []).length - (indel.range.end.line - indel.range.start.line); 78
74 } 79 const startLine = indel.range.start.line + lineDelta + countLines(prefix);
75 builder.replace(indel.range, indel.newText); 80 const startColumn = lastNewline === -1 ?
76 } 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);
77 } 92 }
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);
86 } 93 }
87 }; 94 });
95 if (selection) editor.selection = selection;
96}
97
98function 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
107function countLines(text: string): number {
108 return (text.match(/\n/g) || []).length;
88} 109}
diff --git a/editors/code/src/commands/on_enter.ts b/editors/code/src/commands/on_enter.ts
index 285849db7..a7871c31e 100644
--- a/editors/code/src/commands/on_enter.ts
+++ b/editors/code/src/commands/on_enter.ts
@@ -1,8 +1,8 @@
1import * as vscode from 'vscode'; 1import * as vscode from 'vscode';
2import * as ra from '../rust-analyzer-api'; 2import * as ra from '../rust-analyzer-api';
3 3
4import { applySourceChange } from '../source_change';
5import { Cmd, Ctx } from '../ctx'; 4import { Cmd, Ctx } from '../ctx';
5import { applySnippetWorkspaceEdit } from '.';
6 6
7async function handleKeypress(ctx: Ctx) { 7async function handleKeypress(ctx: Ctx) {
8 const editor = ctx.activeRustEditor; 8 const editor = ctx.activeRustEditor;
@@ -21,7 +21,8 @@ async function handleKeypress(ctx: Ctx) {
21 }); 21 });
22 if (!change) return false; 22 if (!change) return false;
23 23
24 await applySourceChange(ctx, change); 24 const workspaceEdit = client.protocol2CodeConverter.asWorkspaceEdit(change);
25 await applySnippetWorkspaceEdit(workspaceEdit);
25 return true; 26 return true;
26} 27}
27 28
diff --git a/editors/code/src/main.ts b/editors/code/src/main.ts
index ac3bb365e..8b0a9d870 100644
--- a/editors/code/src/main.ts
+++ b/editors/code/src/main.ts
@@ -91,7 +91,7 @@ export async function activate(context: vscode.ExtensionContext) {
91 ctx.registerCommand('debugSingle', commands.debugSingle); 91 ctx.registerCommand('debugSingle', commands.debugSingle);
92 ctx.registerCommand('showReferences', commands.showReferences); 92 ctx.registerCommand('showReferences', commands.showReferences);
93 ctx.registerCommand('applySourceChange', commands.applySourceChange); 93 ctx.registerCommand('applySourceChange', commands.applySourceChange);
94 ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEdit); 94 ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand);
95 ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange); 95 ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange);
96 96
97 ctx.pushCleanup(activateTaskProvider(workspaceFolder)); 97 ctx.pushCleanup(activateTaskProvider(workspaceFolder));
diff --git a/editors/code/src/rust-analyzer-api.ts b/editors/code/src/rust-analyzer-api.ts
index 400ac3714..3b83b10e3 100644
--- a/editors/code/src/rust-analyzer-api.ts
+++ b/editors/code/src/rust-analyzer-api.ts
@@ -69,7 +69,7 @@ export interface JoinLinesParams {
69export const joinLines = request<JoinLinesParams, SourceChange>("joinLines"); 69export const joinLines = request<JoinLinesParams, SourceChange>("joinLines");
70 70
71 71
72export const onEnter = request<lc.TextDocumentPositionParams, Option<SourceChange>>("onEnter"); 72export const onEnter = request<lc.TextDocumentPositionParams, Option<lc.WorkspaceEdit>>("onEnter");
73 73
74export interface RunnablesParams { 74export interface RunnablesParams {
75 textDocument: lc.TextDocumentIdentifier; 75 textDocument: lc.TextDocumentIdentifier;