1use lsp_types::{
2 AnnotatedTextEdit, ChangeAnnotation, DocumentChangeOperation, DocumentChanges, OneOf,
3 OptionalVersionedTextDocumentIdentifier, RenameFile, TextDocumentEdit,
4};
5use rustc_hash::FxHashSet;
6use tinymist_std::path::{PathClean, unix_slash};
7use typst::{
8 foundations::{Repr, Str},
9 syntax::Span,
10};
11
12use crate::adt::interner::Interned;
13use crate::{
14 analysis::{LinkObject, LinkTarget, get_link_exprs},
15 find_references,
16 prelude::*,
17 prepare_renaming,
18 syntax::{Decl, RefExpr, SyntaxClass, first_ancestor_expr, get_index_info, node_ancestors},
19};
20
21#[derive(Debug, Clone)]
27pub struct RenameRequest {
28 pub path: PathBuf,
30 pub position: LspPosition,
32 pub new_name: String,
34}
35
36impl SemanticRequest for RenameRequest {
37 type Response = WorkspaceEdit;
38
39 fn request(self, ctx: &mut LocalContext) -> Option<Self::Response> {
40 let source = ctx.source_by_path(&self.path).ok()?;
41 let syntax = ctx.classify_for_decl(&source, self.position)?;
42
43 let def = ctx.def_of_syntax(&source, syntax.clone())?;
44
45 prepare_renaming(&syntax, &def)?;
46
47 match syntax {
48 SyntaxClass::ImportPath(path) | SyntaxClass::IncludePath(path) => {
50 let ref_path_str = path.cast::<ast::Str>()?.get();
51 let new_path_str = if !self.new_name.ends_with(".typ") {
52 self.new_name + ".typ"
53 } else {
54 self.new_name
55 };
56
57 let def_fid = def.file_id()?;
58 let old_path = ctx.path_for_id(def_fid).ok()?.to_err().ok()?;
60
61 let new_path = Path::new(new_path_str.as_str());
62 let rename_loc = Path::new(ref_path_str.as_str());
63 let diff = tinymist_std::path::diff(new_path, rename_loc)?;
64 if diff.is_absolute() {
65 log::info!(
66 "bad rename: absolute path, base: {rename_loc:?}, new: {new_path:?}, diff: {diff:?}"
67 );
68 return None;
69 }
70
71 let new_path = old_path.join(&diff).clean();
72
73 let old_uri = path_to_url(&old_path).ok()?;
74 let new_uri = path_to_url(&new_path).ok()?;
75
76 let mut edits: HashMap<Url, Vec<TextEdit>> = HashMap::new();
77 do_rename_file(ctx, def_fid, diff, &mut edits);
78
79 let mut document_changes = edits_to_document_changes(edits, None);
80
81 document_changes.push(lsp_types::DocumentChangeOperation::Op(
82 lsp_types::ResourceOp::Rename(RenameFile {
83 old_uri,
84 new_uri,
85 options: None,
86 annotation_id: None,
87 }),
88 ));
89
90 Some(WorkspaceEdit {
92 document_changes: Some(DocumentChanges::Operations(document_changes)),
93 ..Default::default()
94 })
95 }
96 _ => {
97 let is_label = matches!(def.decl.kind(), DefKind::Reference);
98 let references = find_references(ctx, &source, syntax)?;
99
100 let mut edits = HashMap::new();
101
102 for loc in references {
103 let uri = loc.uri;
104 let range = loc.range;
105 let edits = edits.entry(uri).or_insert_with(Vec::new);
106 edits.push(TextEdit {
107 range,
108 new_text: self.new_name.clone(),
109 });
110 }
111
112 crate::log_debug_ct!("rename edits: {edits:?}");
113
114 if !is_label {
115 Some(WorkspaceEdit {
116 changes: Some(edits),
117 ..Default::default()
118 })
119 } else {
120 let change_id = "Typst Rename Labels";
121
122 let document_changes = edits_to_document_changes(edits, Some(change_id));
123
124 let change_annotations = Some(create_change_annotation(
125 change_id,
126 true,
127 Some("The language server fuzzy searched the labels".to_string()),
128 ));
129
130 Some(WorkspaceEdit {
131 document_changes: Some(DocumentChanges::Operations(document_changes)),
132 change_annotations,
133 ..Default::default()
134 })
135 }
136 }
137 }
138 }
139}
140
141pub(crate) fn do_rename_file(
142 ctx: &mut LocalContext,
143 def_fid: TypstFileId,
144 diff: PathBuf,
145 edits: &mut HashMap<Url, Vec<TextEdit>>,
146) -> Option<()> {
147 let def_path = def_fid
148 .vpath()
149 .as_rooted_path()
150 .file_name()
151 .unwrap_or_default()
152 .to_str()
153 .unwrap_or_default()
154 .into();
155 let mut worker = RenameFileWorker {
156 ctx,
157 def_fid,
158 def_path,
159 diff,
160 inserted: FxHashSet::default(),
161 };
162 worker.work(edits)
163}
164
165struct RenameFileWorker<'a> {
166 ctx: &'a mut LocalContext,
167 def_fid: TypstFileId,
168 def_path: Interned<str>,
169 diff: PathBuf,
170 inserted: FxHashSet<Span>,
171}
172
173impl RenameFileWorker<'_> {
174 pub(crate) fn work(&mut self, edits: &mut HashMap<Url, Vec<TextEdit>>) -> Option<()> {
175 let dep = self.ctx.module_dependencies().get(&self.def_fid).cloned();
176 if let Some(dep) = dep {
177 for ref_fid in dep.dependents.iter() {
178 self.refs_in_file(*ref_fid, edits);
179 }
180 }
181
182 for ref_fid in self.ctx.source_files().clone() {
183 self.links_in_file(ref_fid, edits);
184 }
185
186 Some(())
187 }
188
189 fn refs_in_file(
190 &mut self,
191 ref_fid: TypstFileId,
192 edits: &mut HashMap<Url, Vec<TextEdit>>,
193 ) -> Option<()> {
194 let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
195 let uri = self.ctx.uri_for_id(ref_fid).ok()?;
196
197 let import_info = self.ctx.expr_stage(&ref_src);
198
199 let edits = edits.entry(uri).or_default();
200 for (span, r) in &import_info.resolves {
201 if !matches!(
202 r.decl.as_ref(),
203 Decl::ImportPath(..) | Decl::IncludePath(..) | Decl::PathStem(..)
204 ) {
205 continue;
206 }
207
208 if let Some(edit) = self.rename_module_path(*span, r, &ref_src) {
209 edits.push(edit);
210 }
211 }
212
213 Some(())
214 }
215
216 fn links_in_file(
217 &mut self,
218 ref_fid: TypstFileId,
219 edits: &mut HashMap<Url, Vec<TextEdit>>,
220 ) -> Option<()> {
221 let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
222
223 let index = get_index_info(&ref_src);
224 if !index.paths.contains(&self.def_path) {
225 return Some(());
226 }
227
228 let uri = self.ctx.uri_for_id(ref_fid).ok()?;
229
230 let link_info = get_link_exprs(&ref_src);
231 let root = LinkedNode::new(ref_src.root());
232 let edits = edits.entry(uri).or_default();
233 for obj in &link_info.objects {
234 if !matches!(&obj.target,
235 LinkTarget::Path(file_id, _) if *file_id == self.def_fid
236 ) {
237 continue;
238 }
239 if let Some(edit) = self.rename_resource_path(obj, &root, &ref_src) {
240 edits.push(edit);
241 }
242 }
243
244 Some(())
245 }
246
247 fn rename_resource_path(
248 &mut self,
249 obj: &LinkObject,
250 root: &LinkedNode,
251 src: &Source,
252 ) -> Option<TextEdit> {
253 let r = root.find(obj.span)?;
254 self.rename_path_expr(r.clone(), r.cast()?, src, false)
255 }
256
257 fn rename_module_path(&mut self, span: Span, r: &RefExpr, src: &Source) -> Option<TextEdit> {
258 let importing = r.root.as_ref()?.file_id();
259
260 if importing != Some(self.def_fid) {
261 return None;
262 }
263 crate::log_debug_ct!("import: {span:?} -> {importing:?} v.s. {:?}", self.def_fid);
264 let root = LinkedNode::new(src.root());
267 let import_node = root.find(span).and_then(first_ancestor_expr)?;
268 let (import_path, has_path_var) = node_ancestors(&import_node).find_map(|import_node| {
269 match import_node.cast::<ast::Expr>()? {
270 ast::Expr::ModuleImport(import) => Some((
271 import.source(),
272 import.new_name().is_none() && import.imports().is_none(),
273 )),
274 ast::Expr::ModuleInclude(include) => Some((include.source(), false)),
275 _ => None,
276 }
277 })?;
278
279 self.rename_path_expr(import_node.clone(), import_path, src, has_path_var)
280 }
281
282 fn rename_path_expr(
283 &mut self,
284 node: LinkedNode,
285 path: ast::Expr,
286 src: &Source,
287 has_path_var: bool,
288 ) -> Option<TextEdit> {
289 let new_text = match path {
290 ast::Expr::Str(s) => {
291 if !self.inserted.insert(s.span()) {
292 return None;
293 }
294
295 let old_str = s.get();
296 let old_path = Path::new(old_str.as_str());
297 let new_path = old_path.join(&self.diff).clean();
298 let new_str = unix_slash(&new_path);
299
300 let path_part = Str::from(new_str).repr();
301 let need_alias = new_path.file_name() != old_path.file_name();
302
303 if has_path_var && need_alias {
304 let alias = old_path.file_stem()?.to_str()?;
305 format!("{path_part} as {alias}")
306 } else {
307 path_part.to_string()
308 }
309 }
310 _ => return None,
311 };
312
313 let import_path_range = node.find(path.span())?.range();
314 let range = self.ctx.to_lsp_range(import_path_range, src);
315
316 Some(TextEdit { range, new_text })
317 }
318}
319
320pub(crate) fn edits_to_document_changes(
321 edits: HashMap<Url, Vec<TextEdit>>,
322 change_id: Option<&str>,
323) -> Vec<DocumentChangeOperation> {
324 let mut document_changes = vec![];
325
326 for (uri, edits) in edits {
327 document_changes.push(lsp_types::DocumentChangeOperation::Edit(TextDocumentEdit {
328 text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
329 edits: edits
330 .into_iter()
331 .map(|edit| match change_id {
332 Some(change_id) => OneOf::Right(AnnotatedTextEdit {
333 text_edit: edit,
334 annotation_id: change_id.to_owned(),
335 }),
336 None => OneOf::Left(edit),
337 })
338 .collect(),
339 }));
340 }
341
342 document_changes
343}
344
345pub(crate) fn create_change_annotation(
346 label: &str,
347 needs_confirmation: bool,
348 description: Option<String>,
349) -> HashMap<String, ChangeAnnotation> {
350 let mut change_annotations = HashMap::new();
351 change_annotations.insert(
352 label.to_owned(),
353 ChangeAnnotation {
354 label: label.to_owned(),
355 needs_confirmation: Some(needs_confirmation),
356 description,
357 },
358 );
359
360 change_annotations
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366 use crate::tests::*;
367
368 #[test]
369 fn test() {
370 snapshot_testing("rename", &|ctx, path| {
371 let source = ctx.source_by_path(&path).unwrap();
372
373 let request = RenameRequest {
374 path: path.clone(),
375 position: find_test_position(&source),
376 new_name: "new_name".to_string(),
377 };
378
379 let mut result = request.request(ctx);
380 if let Some(r) = result.as_mut().and_then(|r| r.changes.as_mut()) {
382 for edits in r.values_mut() {
383 edits.sort_by(|a, b| {
384 a.range
385 .start
386 .cmp(&b.range.start)
387 .then(a.range.end.cmp(&b.range.end))
388 });
389 }
390 };
391
392 assert_snapshot!(JsonRepr::new_redacted(result, &REDACT_LOC));
393 });
394 }
395}