feat(python): search in comments and strings when renaming a symbol (#7679)

The Python Rename dialog offers Search in comments and strings (off by default, remembered; in-place rename follows it). Whole-word, case-sensitive matches in comments and string text are merged into the language server's workspace edit, so they preview, apply and undo with it; a rename that gains text matches is always previewed with the matches under Non-code usages, and applying fails if a matched file changed after the preview. Locals and parameters are searched in their function, other symbols in the project's .py / .pyi files including unsaved buffers; symlinks leading out of the project are skipped.

Refs #4968

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-03 17:23:45 +08:00
1 джерело 5338a34008
коміт fa0783ab03
21 files changed
+871 -12

No files matched your search

+168 -1
Переглянути файл
@@ -3,7 +3,7 @@
use crate::Host;
use ide_command::command;
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
use ide_core::{FileEdit, IdeResult, IpcPath, Range, RequestId, WorkspaceEdit};
use ide_language::Syntax;
use ide_lsp::types::FileRenameEdits;
use ide_workspace::Documents;
@@ -291,12 +291,179 @@ pub async fn refactor_file_move_text_edits(
result
}
/// A comment or string match added to a rename, with its line for the preview.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct PythonMention {
pub path: IpcPath,
pub range: Range,
pub line: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct PythonMentionEdits {
/// The server's edit with the mentions merged in.
pub edit: WorkspaceEdit,
/// What was merged in, so the preview can show and drop each one.
pub mentions: Vec<PythonMention>,
}
/// Rename's "Search in comments and strings" for Python: adds the whole-word mentions of
/// `old_name` to the server's rename `edit`, so they preview, apply and undo with it. A local
/// symbol or parameter is searched in its function, anything else in the project's Python files.
#[command(trust = always)]
pub async fn refactor_python_mention_edits(
host: &Host,
window: &str,
request: RequestId,
old_name: String,
new_name: String,
edit: WorkspaceEdit,
) -> IdeResult<PythonMentionEdits> {
let project = host.project(window)?;
let syntax = host.syntax().clone();
let token = host.begin_request(request);
let cancel = token.clone();
let result = blocking(move || {
let mut edit = edit;
let found = python_mention_edits(
&project.root,
&project.exclude_globs(),
&project.documents,
&syntax,
&old_name,
&edit,
&|| cancel.is_cancelled(),
);
if cancel.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
let mut mentions = Vec::new();
for file in found {
let path = IpcPath::from(file.path);
let mut existing = edit.files.iter_mut().find_map(|f| match f {
FileEdit::Edit { path: p, edits, .. } if **p == *path => Some(edits),
_ => None,
});
let lines: Vec<&str> = file.text.split('\n').collect();
let mut added = Vec::new();
for range in file.ranges {
// The server may have renamed it already (`__all__`, a quoted annotation).
let renamed = existing
.as_ref()
.is_some_and(|e| e.iter().any(|e| e.range.start < range.end && range.start < e.range.end));
if !renamed {
let line = lines.get(range.start.line as usize).copied().unwrap_or_default().to_owned();
mentions.push(PythonMention { path: path.clone(), range, line });
added.push(ide_core::TextEdit { range, new_text: new_name.clone() });
}
}
if added.is_empty() {
continue;
}
match &mut existing {
Some(existing) => existing.extend(added),
None => edit.files.push(FileEdit::Edit { path, edits: added, version: None }),
}
// Apply refuses when a searched file changed after it was read.
edit.preconditions.extend(file.preconditions);
}
Ok(PythonMentionEdits { edit, mentions })
})
.await;
host.end_request(request);
result
}
struct Mentions {
path: PathBuf,
text: String,
ranges: Vec<Range>,
/// Captured before `text` was read.
preconditions: Vec<ide_core::WorkspaceEditPrecondition>,
}
fn python_mention_edits(
root: &Path,
excludes: &[String],
documents: &Documents,
syntax: &Syntax,
old: &str,
edit: &WorkspaceEdit,
cancelled: &(dyn Fn() -> bool + Sync),
) -> Vec<Mentions> {
let renamed: Vec<(PathBuf, Vec<Range>)> = edit
.files
.iter()
.filter_map(|f| match f {
FileEdit::Edit { path, edits, .. } => Some((path.to_path_buf(), edits.iter().map(|e| e.range).collect())),
_ => None,
})
.collect();
if old.is_empty() || !renamed.iter().any(|(path, _)| is_python(path)) {
return Vec::new();
}
let local: Vec<(PathBuf, Vec<Range>)> = renamed
.iter()
.filter(|(path, _)| is_python(path))
.filter_map(|(path, ranges)| {
let text = read_text(documents, path).ok()?;
let scopes = syntax.python_rename_scope(&text, old, ranges, renamed.len() == 1);
(!scopes.is_empty()).then(|| (path.clone(), scopes))
})
.collect();
let Ok(real_root) = dunce::canonicalize(root) else { return Vec::new() };
let found: Mutex<Vec<Mentions>> = Mutex::new(Vec::new());
let search = |path: &Path, within: &[Range]| {
// A symlink may lead out of the project.
if !dunce::canonicalize(path).is_ok_and(|p| p.starts_with(&real_root)) {
return;
}
// Cheap look first: most files never mention the name.
let mentions = match documents.text_of(path) {
Some(text) => text.contains(old),
None => std::fs::read(path).is_ok_and(|b| String::from_utf8_lossy(&b).contains(old)),
};
if !mentions {
return;
}
let mut guard = WorkspaceEdit {
files: vec![FileEdit::Edit { path: path.into(), edits: Vec::new(), version: None }],
..Default::default()
};
if documents.prepare_workspace_edit(&mut guard).is_err() {
return;
}
let Ok(text) = read_text(documents, path) else { return };
let ranges = syntax.python_mentions(&text, old, within);
if !ranges.is_empty() {
let preconditions = guard.preconditions;
found.lock().push(Mentions { path: path.to_path_buf(), text, ranges, preconditions });
}
};
if local.is_empty() {
ide_vfs::walk_files(root, excludes, |path| {
if !cancelled() && is_python(path) {
search(path, &[]);
}
});
} else {
for (path, scopes) in &local {
search(path, scopes);
}
}
let mut files = found.into_inner();
files.sort_by(|a, b| a.path.cmp(&b.path));
files
}
ide_command::domain!(
refactor:
refactor_can_undo_file_move,
refactor_file_move_edits,
refactor_file_move_text_edits,
refactor_move_files,
refactor_python_mention_edits,
refactor_undo_file_move,
);
+173
Переглянути файл
@@ -0,0 +1,173 @@
//! Python rename's "Search in comments and strings" against the real basedpyright: the rename, the
//! merged edit the preview shows, applying it and undoing it in one step. Needs
//! `basedpyright-langserver` on PATH:
//! `cargo test -p ide-host --test python_rename_comments -- --ignored`
mod common;
use ide_core::{IdeEvent, Pos, RequestId, WorkspaceEdit};
use ide_host::{Host, HostConfig, ops};
use parking_lot::Mutex;
use std::{path::Path, sync::Arc, time::Duration};
const LIB: &str = r#"__all__ = ["load_user"]
def load_user(user_id):
"""Run load_user(user_id) for one user_id.
>>> load_user(1)
"""
# load_user reads user_id; reload_user and load_users stay.
label = f"load_user {user_id} \"user_id\" \nuser_id"
return user_id, label
class Repo:
def load_user(self):
# unrelated method of the same name
return None
def other():
# user_id outside load_user
return "user_id"
"#;
const APP: &str = r#"from lib import load_user
# 😀 café: load_user
print("😀 load_user", load_user(user_id=1))
"#;
/// The position of the first `needle` in `file`.
fn at(text: &str, needle: &str) -> Pos {
let byte = text.find(needle).unwrap();
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
Pos::new(text[..byte].matches('\n').count() as u32, text[start..byte].encode_utf16().count() as u32)
}
async fn rename(host: &Host, doc: ide_core::DocId, pos: Pos, old: &str, new: &str, files: usize) -> WorkspaceEdit {
for _ in 0..120 {
let renamed = ops::lsp::lsp_rename(host, "main", RequestId(1), doc, pos, new.into()).await;
if let Ok(renamed) = renamed
&& renamed.edit.files.len() >= files
{
return ops::refactor::refactor_python_mention_edits(
host,
"main",
RequestId(2),
old.into(),
new.into(),
renamed.edit,
)
.await
.unwrap()
.edit;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
panic!("basedpyright did not rename {old}");
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs basedpyright-langserver on PATH"]
async fn python_rename_searches_comments_and_strings() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(&root).unwrap();
let (lib, app, notes, closed) =
(root.join("lib.py"), root.join("app.py"), root.join("notes.md"), root.join("x.py"));
std::fs::write(&lib, LIB).unwrap();
std::fs::write(&app, APP).unwrap();
std::fs::write(&notes, "load_user\n").unwrap();
// A file that is not open and has no code reference, with a BOM and CRLF.
std::fs::write(&closed, "\u{feff}# load_user\r\nload_user = 1\r\n").unwrap();
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink = events.clone();
let host = Host::new(HostConfig {
sink_for: Box::new(move |_| {
let sink = sink.clone();
Arc::new(move |e| sink.lock().push(e))
}),
..common::host_config(&tmp.path().join("ide"))
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let doc = ops::doc::doc_open(&host, "main", lib.clone()).await.unwrap();
let app_doc = ops::doc::doc_open(&host, "main", app.clone()).await.unwrap();
// An unsaved comment line exists only in the buffer.
let end = APP.encode_utf16().count() as u32;
let changes = ide_core::ChangeSet {
changes: vec![ide_core::TextChange { from: end, to: end, insert: "# unsaved load_user\n".into() }],
};
ops::doc::doc_edit(&host, "main", app_doc.id, app_doc.version, changes).await.unwrap();
// A local (a parameter): only its own function's mentions change, not the same text in another one.
let edit = rename(&host, doc.id, at(LIB, "user_id):"), "user_id", "uid", 1).await;
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
let after = ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text;
assert!(after.contains("def load_user(uid):\n \"\"\"Run load_user(uid) for one uid."), "{after}");
assert!(after.contains(r#"f"load_user {uid} \"uid\" \nuid""#), "{after}");
assert!(after.contains("# user_id outside load_user\n return \"user_id\""), "{after}");
let undo = |events: &Mutex<Vec<IdeEvent>>| {
events.lock().iter().rev().find_map(|e| match e {
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
_ => None,
})
};
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
assert_eq!(ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text, LIB);
// A module-level function: comments and strings in all of the project's Python files.
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "fetch_user", 2).await;
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
let lib_after = ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text;
assert!(lib_after.starts_with("__all__ = [\"fetch_user\"]"), "{lib_after}");
assert!(lib_after.contains(">>> fetch_user(1)"), "{lib_after}");
assert!(lib_after.contains("# fetch_user reads user_id; reload_user and load_users stay."), "{lib_after}");
// An unrelated method with the same name: its code is left alone.
assert!(lib_after.contains("def load_user(self):"), "{lib_after}");
let app_after = ops::doc::doc_snapshot(&host, "main", app_doc.id).await.unwrap().text;
assert_eq!(app_after, format!("{APP}# unsaved load_user\n").replace("load_user", "fetch_user"));
let closed_after = read(&closed);
assert!(closed_after.contains("# fetch_user\r\nload_user = 1"), "{closed_after:?}");
assert_eq!(read(&notes), "load_user\n");
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
assert_eq!(ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text, LIB);
assert_eq!(read(&closed), "\u{feff}# load_user\r\nload_user = 1\r\n");
// Renaming a parameter from a keyword argument in another file: comments change in its function, not at the caller.
let (base, caller) = (root.join("base.py"), root.join("caller.py"));
std::fs::write(&base, "class Base:\n def run(self, speed):\n return speed # base speed\n").unwrap();
let call = "from base import Base\n\n# outside speed\nBase().run(speed=1)\n";
std::fs::write(&caller, call).unwrap();
let caller_doc = ops::doc::doc_open(&host, "main", caller.clone()).await.unwrap();
let edit = rename(&host, caller_doc.id, at(call, "speed=1"), "speed", "pace", 2).await;
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
assert!(read(&base).contains("return pace # base pace"), "{}", read(&base));
assert!(read(&caller).contains("# outside speed"));
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
// A symlink in the project to a file outside it is not changed.
#[cfg(unix)]
{
let outside = tmp.path().join("outside.py");
std::fs::write(&outside, "# load_user\n").unwrap();
std::os::unix::fs::symlink(&outside, root.join("link.py")).unwrap();
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "get_user", 2).await;
let text = format!("{:?}", edit.files);
assert!(!text.contains("outside.py") && !text.contains("link.py"), "{text}");
}
// A file with only comment matches changed after the preview: applying must fail rather than write at stale positions.
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "get_user", 2).await;
std::fs::write(&closed, "keep = 'untouched line'\n# load_user\n").unwrap();
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap_err();
assert_eq!(read(&closed), "keep = 'untouched line'\n# load_user\n");
assert_eq!(read(&lib), LIB);
}
+1
Переглянути файл
@@ -16,6 +16,7 @@ mod python_exports;
mod python_facts;
mod python_fixtures;
mod python_imports;
mod python_mentions;
mod rearrange;
mod rst;
mod selection;
+254
Переглянути файл
@@ -0,0 +1,254 @@
//! Python 重命名的 "Search in comments and strings":注释和字符串里的整词匹配,
//! 以及局部符号(参数、局部变量)只在所在函数内查找。紧邻中日文字符的名字(`调用load_user函数`)
//! 不算整词,与按标识符字符分词一致。
use super::lines::LineIndex;
use crate::{LanguageId, Syntax};
use ide_core::Range;
use tree_sitter::Node;
impl Syntax {
/// Whole-word, case-sensitive occurrences of `name` in the comments and string literals of a
/// Python `text`; f-string interpolations are code and are left to the language server.
/// With `within` not empty, only those inside one of them.
pub fn python_mentions(&self, text: &str, name: &str, within: &[Range]) -> Vec<Range> {
self.analyze(&LanguageId::new("python"), text, |_, tree, text| {
let idx = LineIndex::new(text);
let mut out = Vec::new();
walk(tree.root_node(), &mut |node| {
if !matches!(node.kind(), "comment" | "string_content") {
return;
}
let escapes: Vec<(usize, usize)> = (0..node.child_count())
.filter_map(|i| node.child(i))
.filter(|c| c.kind() == "escape_sequence")
.map(|c| (c.start_byte(), c.end_byte()))
.collect();
// 组合符号(NFD 的 `é`)是单词的一部分。
let word = |c: char| {
c.is_alphanumeric()
|| c == '_'
|| matches!(c, '\u{300}'..='\u{36f}' | '\u{1ab0}'..='\u{1aff}' | '\u{1dc0}'..='\u{1dff}'
| '\u{20d0}'..='\u{20ff}' | '\u{fe20}'..='\u{fe2f}')
};
for (at, _) in text[node.start_byte()..node.end_byte()].match_indices(name) {
let (start, end) = (node.start_byte() + at, node.start_byte() + at + name.len());
// `"\n" + name`:转义序列算分隔符,落在转义序列里面的匹配不算。
if escapes.iter().any(|&(a, b)| start < b && a < end) {
continue;
}
let joined_before = !escapes.iter().any(|&(_, b)| b == start)
&& text[..start].chars().next_back().is_some_and(word);
if joined_before || text[end..].chars().next().is_some_and(word) {
continue;
}
let range = Range::new(idx.pos(start), idx.pos(end));
if within.is_empty() || within.iter().any(|w| w.start <= range.start && range.end <= w.end) {
out.push(range);
}
}
});
Some(out)
})
.unwrap_or_default()
}
/// The functions (or lambdas) a renamed symbol is local to, judging by the rename's `edits`
/// of this `text`; empty when it is visible outside one. `only_file`: no other file is edited.
/// A parameter belongs to its function even when callers name it as a keyword elsewhere; a
/// method's parameter renamed with its overrides belongs to each of them.
pub fn python_rename_scope(&self, text: &str, name: &str, edits: &[Range], only_file: bool) -> Vec<Range> {
self.analyze(&LanguageId::new("python"), text, |_, tree, text| {
let idx = LineIndex::new(text);
let mut nodes = Vec::new();
let mut global = false;
walk(tree.root_node(), &mut |node| {
if node.kind() == "identifier" && text[node.start_byte()..node.end_byte()] == *name {
let start = idx.pos(node.start_byte());
if edits.iter().any(|e| e.start == start) {
// 只有服务器一起改了的 `global v` 才说明改的是模块级变量。
global |= node.parent().is_some_and(|p| p.kind() == "global_statement");
nodes.push(node);
}
}
});
let range = |f: Node| Range::new(idx.pos(f.start_byte()), idx.pos(f.end_byte()));
let owners: Vec<Range> =
nodes.iter().filter(|n| is_parameter(**n)).filter_map(|n| enclosing_function(*n)).map(range).collect();
if !owners.is_empty() {
return Some(owners);
}
// 属性(`self.x`)在函数外可见;`global x` 指向模块级变量。
if !only_file || global || nodes.len() != edits.len() || nodes.iter().any(|n| is_attribute(*n)) {
return None;
}
let mut scope = enclosing_function(*nodes.first()?);
while let Some(f) = scope {
let inside = |n: &Node| {
f.start_byte() <= n.start_byte()
&& n.end_byte() <= f.end_byte()
&& f.child_by_field_name("name") != Some(*n)
};
if nodes.iter().all(inside) {
return Some(vec![range(f)]);
}
scope = enclosing_function(f);
}
None
})
.unwrap_or_default()
}
}
fn walk<'a>(root: Node<'a>, f: &mut impl FnMut(Node<'a>)) {
let mut cursor = root.walk();
loop {
f(cursor.node());
if cursor.goto_first_child() {
continue;
}
while !cursor.goto_next_sibling() {
if !cursor.goto_parent() {
return;
}
}
}
}
fn enclosing_function(node: Node) -> Option<Node> {
std::iter::successors(node.parent(), Node::parent).find(|p| matches!(p.kind(), "function_definition" | "lambda"))
}
fn is_attribute(node: Node) -> bool {
node.parent().is_some_and(|p| p.kind() == "attribute" && p.child_by_field_name("attribute") == Some(node))
}
fn is_parameter(node: Node) -> bool {
let Some(parent) = node.parent() else { return false };
match parent.kind() {
"parameters" | "lambda_parameters" => true,
"default_parameter" | "typed_default_parameter" => parent.child_by_field_name("name") == Some(node),
"typed_parameter" => parent.named_child(0) == Some(node),
// `*args` / `**kw`
"list_splat_pattern" | "dictionary_splat_pattern" => {
parent.parent().is_some_and(|p| matches!(p.kind(), "parameters" | "lambda_parameters" | "typed_parameter"))
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::Pos;
/// 匹配处用 `[[…]]` 标出。
fn marked(text: &str, name: &str, within: &[Range]) -> String {
let mut lines: Vec<Vec<u16>> = text.split('\n').map(|l| l.encode_utf16().collect()).collect();
for r in Syntax::new().python_mentions(text, name, within).into_iter().rev() {
let line = &mut lines[r.start.line as usize];
line.splice(r.end.col as usize..r.end.col as usize, "]]".encode_utf16());
line.splice(r.start.col as usize..r.start.col as usize, "[[".encode_utf16());
}
lines.iter().map(|l| String::from_utf16_lossy(l)).collect::<Vec<_>>().join("\n")
}
fn check(name: &str, expected: &str) {
let text = expected.replace("[[", "").replace("]]", "");
assert_eq!(marked(&text, name, &[]), expected);
}
#[test]
fn comments_and_docstrings() {
check("load", "# [[load]](): [[load]], x.[[load]]; reload load_all Load load2\nload()\n");
check(
"load",
"def load():\n \"\"\"[[load]] things.\n\n >>> [[load]]()\n :func:`[[load]]`\n \"\"\"\n",
);
check("load", "x = 1 #[[load]]\n'''[[load]]'''\nb'[[load]]'\nu\"[[load]]\" '[[load]]'\n");
}
#[test]
fn f_string_interpolations_are_code() {
check("user", "f\"[[user]] {user} {user.name!r:>{user}} {{[[user]]}} [[user]]={user=}\"\n");
check("user", "f\"\"\"\n[[user]]: {user}\n\"\"\"\n");
// 插值里的字符串仍然是字符串。
check("user", "f\"{row['[[user]]']}\"\n");
}
#[test]
fn escapes_and_raw_strings() {
check("name", r#"x = "\n[[name]]\t[[name]] \"[[name]]\" \\[[name]]""#);
check("name", r#"x = r"\nname [[name]]""#);
check("x41", r#"x = "\x41 [[x41]]""#);
check("n", r#"x = "\n [[n]]""#);
}
#[test]
fn unicode_names_and_utf16_columns() {
check("café", "# 😀 [[café]] cafés 中café\ns = '😀[[café]]😀'\n");
check("数据", "# 加载 [[数据]]。数据库\n");
}
#[test]
fn syntax_errors_and_limits() {
check("a", "def f(:\n # [[a]]\n");
check("a", "a = 1\nprint(a.a)\n");
let within = Range::new(Pos::new(1, 0), Pos::new(1, 10));
assert_eq!(marked("# a\n# a\n# a", "a", &[within]), "# a\n# [[a]]\n# a");
}
/// `^` 标出服务器改名的位置。
fn scope(code: &str, name: &str, only_file: bool) -> Option<u32> {
let mut edits = Vec::new();
let mut text = String::new();
for (n, line) in code.split('\n').enumerate() {
let mut parts = line.split('^');
let mut out = parts.next().unwrap_or_default().to_owned();
for part in parts {
let col = out.encode_utf16().count() as u32;
edits.push(Range::new(Pos::new(n as u32, col), Pos::new(n as u32, col + name.len() as u32)));
out.push_str(part);
}
text.push_str(&out);
text.push('\n');
}
Syntax::new().python_rename_scope(&text, name, &edits, only_file).first().map(|r| r.start.line)
}
#[test]
fn locals_and_parameters_stay_in_their_function() {
assert_eq!(scope("def f():\n ^v = 1\n return ^v\n", "v", true), Some(0));
for p in ["^v", "^v=1", "^v: int", "^v: int = 1", "*^v", "**^v", "*^v: int"] {
assert_eq!(scope(&format!("\ndef f({p}):\n pass\n"), "v", false), Some(1), "{p}");
}
assert_eq!(scope("g = lambda ^v: ^v\n", "v", true), Some(0));
// 闭包:包含全部引用的那一层函数。
assert_eq!(scope("def f():\n ^v = 1\n def g():\n return ^v\n", "v", true), Some(0));
assert_eq!(scope("def f():\n def ^g():\n ^g()\n ^g()\n", "g", true), Some(0));
}
#[test]
fn review_repros() {
// #5:别处的 `global v` 不影响无关的局部变量。
assert_eq!(scope("def f():\n ^v = 1\n return ^v\ndef g():\n global v\n", "v", true), Some(0));
// #6:参数在多个函数里一起改名时每个函数都算。
let two = "def f(v):\n pass\ndef g(v):\n pass\n";
let edit = |line| Range::new(Pos::new(line, 6), Pos::new(line, 7));
assert_eq!(Syntax::new().python_rename_scope(two, "v", &[edit(0), edit(2)], true).len(), 2);
// NFD 的 café 不是 cafe。
check("cafe", "# cafe\u{301} [[cafe]]\n");
}
#[test]
fn module_level_names_attributes_and_globals_are_project_wide() {
assert_eq!(scope("def ^f():\n ^f()\n", "f", true), None);
assert_eq!(scope("^v = 1\ndef f():\n return ^v\n", "v", true), None);
assert_eq!(scope("def f(self):\n self.^v = 1\n", "v", true), None);
assert_eq!(scope("def f():\n global ^v\n ^v = 1\n", "v", true), None);
assert_eq!(scope("def f():\n ^v()\n", "v", false), None);
assert_eq!(scope("class C:\n def ^m(self):\n pass\n", "m", true), None);
// 参数默认值不是参数名。
assert_eq!(scope("^v = 1\ndef f(a=^v):\n pass\n", "v", true), None);
}
}
+1
Переглянути файл
@@ -660,6 +660,7 @@ refactor_can_undo_file_move always project_host bin
refactor_file_move_edits always project_host bindings async
refactor_file_move_text_edits always project_host bindings async
refactor_move_files always project_host bindings async
refactor_python_mention_edits always project_host bindings async
refactor_undo_file_move always project_host bindings async
remote_bootstrap_list always desktop bindings async
remote_connect always desktop bindings async
+20
Переглянути файл
@@ -1887,6 +1887,12 @@ export const commands = {
* files and notifies the servers. Returns the id for [`refactor_undo_file_move`].
*/
refactorMoveFiles: (moves: FileMove[], edit: WorkspaceEdit, label: string) => typedError<number, IdeError>(__TAURI_INVOKE("refactor_move_files", { moves, edit, label })),
/**
* Rename's "Search in comments and strings" for Python: adds the whole-word mentions of
* `old_name` to the server's rename `edit`, so they preview, apply and undo with it. A local
* symbol or parameter is searched in its function, anything else in the project's Python files.
*/
refactorPythonMentionEdits: (request: RequestId, oldName: string, newName: string, edit: WorkspaceEdit) => typedError<PythonMentionEdits, IdeError>(__TAURI_INVOKE("refactor_python_mention_edits", { request, oldName, newName, edit })),
/** Undoes a file move: moves back and reverts the reference updates. */
refactorUndoFileMove: (id: number) => typedError<UndoOutcome, IdeError>(__TAURI_INVOKE("refactor_undo_file_move", { id })),
/** Browse before connecting, using the desktop's SSH configuration even in a remote window. */
@@ -15187,6 +15193,20 @@ export type PythonImportCandidate = {
name: string | null,
};
/** A comment or string match added to a rename, with its line for the preview. */
export type PythonMention = {
path: IpcPath,
range: Range,
line: string,
};
export type PythonMentionEdits = {
/** The server's edit with the mentions merged in. */
edit: WorkspaceEdit,
/** What was merged in, so the preview can show and drop each one. */
mentions: PythonMention[],
};
/** A method definition the inspections can reason about. */
export type PythonMethodFacts = {
name: string,
+22
Переглянути файл
@@ -340,6 +340,7 @@
font-size: var(--fs-ui);
}
.renameContext,
.symbolRenameOption,
.symbolRenameNote {
grid-column: 1 / -1;
min-width: 0;
@@ -703,6 +704,27 @@
font-variant-numeric: tabular-nums;
}
.previewMatches {
list-style: none;
margin: 0;
padding: 0 0 8px;
}
.previewMatchRow {
min-width: 0;
white-space: pre;
}
.previewMatchRow > span:last-child {
display: flex;
align-items: baseline;
gap: var(--space-2);
min-width: 0;
}
.previewLocation {
flex: none;
font-size: var(--fs-small);
color: var(--fg-muted);
}
.previewWarning {
flex: none;
display: flex;
+45 -1
Переглянути файл
@@ -36,6 +36,7 @@ import { DOC_MIN_HEIGHT, DOC_MIN_WIDTH, loadDocSize, saveDocSize, useDocWindow }
import { DocView, DomContent } from "./DocView";
import { renderCode } from "./markdown";
import { describeSummary } from "./workspaceEdit";
import { searchInComments, setSearchInComments } from "./renameOptions";
import { useUsagesStatus } from "./navigation";
import styles from "./Popups.module.css";
import fieldsetStyles from "@/ui/DialogFieldset.module.css";
@@ -479,6 +480,7 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
function SymbolRenameDialog({ popup }: { popup: Extract<LspPopup, { kind: "symbolRename" }> }) {
const [value, setValue] = useState(popup.initial);
const [comments, setComments] = useState(searchInComments);
const field = useId();
const name = value.trim();
return (
@@ -496,6 +498,7 @@ function SymbolRenameDialog({ popup }: { popup: Extract<LspPopup, { kind: "symbo
disabled: !name,
onClick: () => {
closePopup();
if (popup.commentsOption) setSearchInComments(comments);
popup.onSubmit(name);
},
},
@@ -518,6 +521,11 @@ function SymbolRenameDialog({ popup }: { popup: Extract<LspPopup, { kind: "symbo
onChange={(e) => setValue(e.target.value)}
invalid={!name}
/>
{popup.commentsOption && (
<div className={styles.symbolRenameOption}>
<Checkbox checked={comments} onChange={setComments} label="Search in comments and strings" />
</div>
)}
{popup.note && <div className={styles.symbolRenameNote}>{popup.note}</div>}
</div>
</div>
@@ -707,6 +715,7 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
const root = useProject((s) => s.project?.root ?? "");
const { summary } = popup;
const [initialSize] = useState(loadPreviewSize);
const [excluded, setExcluded] = useState<ReadonlySet<number>>(new Set<number>());
return (
<Dialog
open
@@ -728,7 +737,7 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
autoFocus: true,
onClick: () => {
closePopup();
popup.onConfirm();
popup.onConfirm(excluded);
},
},
{ label: "Cancel", role: "cancel" },
@@ -798,6 +807,41 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
})}
</ul>
)}
{popup.textMatches && (
<>
<div className={styles.previewSummary}>
<T>Non-code usages</T>
</div>
<ul className={clsx(styles.previewMatches, popup.renameThemeClasses)} aria-label={tx("Non-code usages")}>
{popup.textMatches.map((m, i) => (
<li key={`${m.path}:${m.line}:${m.from}`} className={styles.previewRow}>
<Checkbox
className={styles.previewMatchRow}
checked={!excluded.has(i)}
onChange={(on) => {
const next = new Set(excluded);
if (on) next.delete(i);
else next.add(i);
setExcluded(next);
}}
label={
<>
<span className={styles.previewLocation} title={relativePath(root, m.path)}>
{basename(m.path)}:{m.line + 1}
</span>
<span className={styles.previewCode}>
{m.text.slice(0, m.from).trimStart()}
<mark className={styles.previewMatch}>{m.text.slice(m.from, m.to)}</mark>
{m.text.slice(m.to)}
</span>
</>
}
/>
</li>
))}
</ul>
</>
)}
</Dialog>
);
}
+6 -1
Переглянути файл
@@ -155,6 +155,8 @@ export type LspPopup =
title: string;
initial: string;
note?: string;
/** Offers "Search in comments and strings" (Python). */
commentsOption?: boolean;
themeClasses: string;
onSubmit: (name: string) => void;
}
@@ -163,7 +165,10 @@ export type LspPopup =
title: string;
summary: WorkspaceEditSummary;
confirmLabel: string;
onConfirm: () => void;
/** `excluded`: indexes into `textMatches` the user unchecked. */
onConfirm: (excluded?: ReadonlySet<number>) => void;
/** Comment and string matches of a rename, each with its line and a checkbox to leave it out. */
textMatches?: (PreviewOccurrence & { path: string })[];
/** Why confirmation is needed (shown as warnings above the changes). */
warnings?: string[];
/** Individual occurrences with line previews (single-file syntax-based renames). */
+72 -9
Переглянути файл
@@ -12,6 +12,7 @@
* symbols — is left to the server. Ambiguous cases ask first.
*/
import type { EditorView } from "@codemirror/view";
import type { PythonMention } from "@/bindings";
import {
commands,
IpcError,
@@ -44,6 +45,7 @@ import {
import { tx } from "@/platform/i18n";
import { synchronizeDocumentIndexes } from "@/workbench/contributions";
import { contributedRename, type ContributedRename } from "@/editor/refactorProviders";
import { searchInComments, searchInCommentsAvailable } from "./renameOptions";
async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
try {
@@ -147,6 +149,7 @@ export async function startRename(view: EditorView) {
title: tx`Rename '${oldName}'`,
initial,
themeClasses: view.themeClasses,
commentsOption: searchInCommentsAvailable(doc.path),
onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName),
});
if (from === to) {
@@ -283,12 +286,30 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o
const request = nextRequestId();
renameRequest = request;
let renamed;
let edit;
let preview;
let mentions: PythonMention[] = [];
const before = view.state.doc;
try {
await synchronizeDocumentIndexes(doc.path, "refactor");
if (renameRequest !== request || view.state.doc !== before) return;
renamed = await lspRequest(() => commands.lspRename(request, doc.doc, pos, newName));
if (renameRequest !== request) return;
({ edit } = renamed);
preview = !!renamed.preview;
if (searchInCommentsAvailable(doc.path) && searchInComments() && edit.files.length) {
const server = edit;
({ edit, mentions } = await lspRequest(() =>
commands.refactorPythonMentionEdits(request, oldName, newName, server),
));
if (renameRequest !== request) return;
if (view.state.doc !== before) {
showHint(view, "The file changed; rename cancelled", { tone: "warning" });
return;
}
// Text matches are guesses: never applied unseen.
preview ||= mentions.length > 0;
}
} catch (e) {
if (renameRequest !== request) return;
reportLspError(view, e, true);
@@ -296,15 +317,24 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o
} finally {
if (renameRequest === request) renameRequest = null;
}
const { edit, incomplete } = renamed;
const { incomplete } = renamed;
const note = incomplete && incompleteNote(incomplete, oldName);
await presentRename(view, edit, oldName, newName, note || null, !!renamed.preview, async () => {
if (!(await hasSyntaxErrors(doc.doc))) return false;
const plan = await syntaxPlan(view, doc, pos);
if (!plan || plan.symbol.name !== oldName) return false;
await commitSyntaxRename(view, doc, plan, newName);
return true;
});
await presentRename(
view,
edit,
oldName,
newName,
note || null,
preview,
async () => {
if (!(await hasSyntaxErrors(doc.doc))) return false;
const plan = await syntaxPlan(view, doc, pos);
if (!plan || plan.symbol.name !== oldName) return false;
await commitSyntaxRename(view, doc, plan, newName);
return true;
},
mentions,
);
}
async function finishContributedRename(view: EditorView, own: ContributedRename, oldName: string, newName: string) {
@@ -339,6 +369,7 @@ async function presentRename(
note: string | null,
preview: boolean,
fallback: () => Promise<boolean>,
mentions: PythonMention[] = [],
) {
const summary = summarizeWorkspaceEdit(edit);
if (!summary.files) {
@@ -359,10 +390,42 @@ async function presentRename(
renameThemeClasses: view.themeClasses,
...(note ? { warnings: [note] } : {}),
confirmLabel: note ? "Rename Anyway" : "Do Refactor",
onConfirm: () => void applyEdit(view, edit),
...(mentions.length
? {
textMatches: mentions.map((m) => ({
path: m.path,
line: m.range.start.line,
text: m.line,
from: m.range.start.col,
to: m.range.end.col,
})),
}
: {}),
onConfirm: (excluded) =>
void applyEdit(
view,
excluded?.size
? withoutMatches(
edit,
mentions.filter((_, i) => excluded.has(i)),
)
: edit,
),
});
}
/** `edit` without the replacements at `dropped`; its preconditions stay. */
function withoutMatches(edit: WorkspaceEdit, dropped: PythonMention[]): WorkspaceEdit {
const key = (path: string, at: Pos) => `${path}:${at.line}:${at.col}`;
const keys = new Set(dropped.map((m) => key(m.path, m.range.start)));
const files = edit.files.flatMap<WorkspaceEdit["files"][number]>((f) => {
if (f.kind !== "edit") return [f];
const edits = f.edits.filter((e) => !keys.has(key(f.path, e.range.start)));
return edits.length ? [{ ...f, edits }] : [];
});
return { ...edit, files };
}
// ---------------------------------------------------------------------------
// Syntax-based local rename
+86
Переглянути файл
@@ -0,0 +1,86 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { WorkspaceEdit } from "@/bindings";
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
const at = (line: number) => ({ range: { start: { line, col: 0 }, end: { line, col: 1 } }, new_text: "b" });
const server: WorkspaceEdit = { files: [{ kind: "edit", path: "/p/a.py", edits: [at(0)] }] };
const withMentions: WorkspaceEdit = { files: [{ kind: "edit", path: "/p/a.py", edits: [at(0), at(1)] }] };
const cmd = {
lspPrepareRename: vi.fn(() => ok({ start: { line: 0, col: 0 }, end: { line: 0, col: 1 } })),
lspRename: vi.fn(() => ok({ edit: server, incomplete: null })),
lspDocumentHighlights: vi.fn(() => ok([])),
refactorPythonMentionEdits: vi.fn(() =>
ok({ edit: withMentions, mentions: [{ path: "/p/a.py", range: at(1).range, line: "# a" }] }),
),
applyWorkspaceEdit: vi.fn(() => ok(null)),
};
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, isTauri: () => true, commands: { ...actual.commands, ...cmd } };
});
const { renameNamePart } = await import("./rename");
const { lspDoc } = await import("./lsp");
const { useLspPopup, closePopup } = await import("./popupStore");
const options = await import("./renameOptions");
async function rename(path: string) {
const view = new EditorView({
state: EditorState.create({
doc: "a = 1\n# a\n",
extensions: lspDoc.of({ doc: 7, path, language: "python", uiMode: null, readOnly: false }),
}),
parent: document.body,
});
await renameNamePart(view, { from: 0, to: 1 }, "b");
view.destroy();
}
beforeEach(() => {
localStorage.clear();
for (const f of Object.values(cmd)) f.mockClear();
closePopup();
});
describe("Search in comments and strings", () => {
it("is off by default and offered for Python files only", () => {
expect(options.searchInComments()).toBe(false);
expect(options.searchInCommentsAvailable("/p/a.py")).toBe(true);
expect(options.searchInCommentsAvailable("/p/a.pyi")).toBe(true);
expect(options.searchInCommentsAvailable("/p/a.ts")).toBe(false);
});
it("applies the server's edit directly when off", async () => {
await rename("/p/a.py");
expect(cmd.refactorPythonMentionEdits).not.toHaveBeenCalled();
expect(cmd.applyWorkspaceEdit).toHaveBeenCalledWith(server);
});
it("previews the mentions it adds", async () => {
options.setSearchInComments(true);
await rename("/p/a.py");
expect(cmd.refactorPythonMentionEdits).toHaveBeenCalledWith(expect.anything(), "a", "b", server);
expect(cmd.applyWorkspaceEdit).not.toHaveBeenCalled();
expect(useLspPopup.getState().popup).toMatchObject({ kind: "preview", summary: { occurrences: 2 } });
});
it("shows each match and leaves out the unchecked ones", async () => {
options.setSearchInComments(true);
await rename("/p/a.py");
const popup = useLspPopup.getState().popup;
if (popup?.kind !== "preview") throw new Error("no preview");
expect(popup.textMatches).toEqual([{ path: "/p/a.py", line: 1, text: "# a", from: 0, to: 1 }]);
popup.onConfirm(new Set([0]));
await vi.waitFor(() => expect(cmd.applyWorkspaceEdit).toHaveBeenCalledWith(server));
});
it("leaves other languages alone when on", async () => {
options.setSearchInComments(true);
await rename("/p/a.ts");
expect(cmd.refactorPythonMentionEdits).not.toHaveBeenCalled();
});
});
+14
Переглянути файл
@@ -0,0 +1,14 @@
/** Rename 对话框的 "Search in comments and strings"(Python):默认关闭,记住上次的选择,同 PyCharm。 */
const KEY = "openidea.rename.searchInComments";
export function searchInCommentsAvailable(path: string): boolean {
return /\.pyi?$/i.test(path);
}
export function searchInComments(): boolean {
return localStorage.getItem(KEY) === "true";
}
export function setSearchInComments(on: boolean) {
localStorage.setItem(KEY, String(on));
}
+1
Переглянути файл
@@ -1954,6 +1954,7 @@
"Search for references": "Buscar referencias",
"Search frames": "Buscar marcos",
"Search in comments and strings": "Buscar en comentarios y cadenas de texto",
"Non-code usages": "Usos fuera del código",
"Search packages": "Buscar paquetes",
"Search plugins": "Buscar plugins",
"Search projects": "Buscar proyectos",
+1
Переглянути файл
@@ -1882,6 +1882,7 @@
"Search for references": "Rechercher les références",
"Search frames": "Rechercher des cadres",
"Search in comments and strings": "Rechercher dans les commentaires et les chaînes",
"Non-code usages": "Utilisations hors code",
"Search packages": "Rechercher des paquets",
"Search projects": "Rechercher des projets",
"Search pull requests": "Rechercher des pull requests",
+1
Переглянути файл
@@ -2004,6 +2004,7 @@
"Search for references": "참조 검색",
"Search frames": "프레임 검색",
"Search in comments and strings": "주석 및 문자열에서 검색",
"Non-code usages": "코드가 아닌 사용",
"Search packages": "패키지 검색",
"Search plugins": "플러그인 검색",
"Search projects": "프로젝트 검색",
+1
Переглянути файл
@@ -1943,6 +1943,7 @@
"Search for references": "Szukaj referencji",
"Search frames": "Szukaj ramek",
"Search in comments and strings": "Szukaj w komentarzach i ciągach znaków",
"Non-code usages": "Użycia poza kodem",
"Search packages": "Szukaj pakietów",
"Search projects": "Szukaj projektów",
"Search pull requests": "Szukaj pull requestów",
+1
Переглянути файл
@@ -1944,6 +1944,7 @@
"Search for references": "Pesquisar referências",
"Search frames": "Pesquisar quadros",
"Search in comments and strings": "Pesquisar em comentários e strings",
"Non-code usages": "Usos fora do código",
"Search packages": "Pesquisar pacotes",
"Search projects": "Pesquisar projetos",
"Search pull requests": "Pesquisar pull requests",
+1
Переглянути файл
@@ -3235,6 +3235,7 @@
"Search for references": "Поиск ссылок",
"Search frames": "Поиск фреймов",
"Search in comments and strings": "Поиск в комментариях и строках",
"Non-code usages": "Использования вне кода",
"Search packages": "Поиск пакетов",
"Search plugins": "Поиск плагинов",
"Search installed plugins": "Поиск установленных плагинов",
+1
Переглянути файл
@@ -4675,6 +4675,7 @@
"Search for references": "Başvuruları ara",
"Search frames": "Çerçeveleri ara",
"Search in comments and strings": "Yorumlarda ve metin sabitlerinde ara",
"Non-code usages": "Kod dışı kullanımlar",
"Search packages": "Paketleri ara",
"Search plugins": "Eklentileri ara",
"Search projects": "Projeleri ara",
+1
Переглянути файл
@@ -2873,6 +2873,7 @@
"Search for references": "搜尋引用",
"Search frames": "搜尋幀",
"Search in comments and strings": "在註解和字串中搜尋",
"Non-code usages": "非程式碼用法",
"Search packages": "搜尋軟體包",
"Search plugins": "搜尋外掛",
"Search installed plugins": "搜尋已安裝的外掛",
+1
Переглянути файл
@@ -3549,6 +3549,7 @@
"Search for references": "搜索引用",
"Search frames": "搜索帧",
"Search in comments and strings": "在注释和字符串中搜索",
"Non-code usages": "非代码用法",
"Search packages": "搜索软件包",
"Search plugins": "搜索插件",
"Search installed plugins": "搜索已安装的插件",