tinymist_query/
rename.rs

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/// The [`textDocument/rename`] request is sent from the client to the server to
22/// ask the server to compute a workspace change so that the client can perform
23/// a workspace-wide rename of a symbol.
24///
25/// [`textDocument/rename`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_rename
26#[derive(Debug, Clone)]
27pub struct RenameRequest {
28    /// The path of the document to request for.
29    pub path: PathBuf,
30    /// The source code position to request for.
31    pub position: LspPosition,
32    /// The new name to rename to.
33    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            // todo: abs path
49            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                // todo: rename in untitled files
59                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                // todo: validate: workspace.workspaceEdit.resourceOperations
91                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.vpath().get_with_slash();
148    let def_path = std::path::Path::new(def_path)
149        .file_name()
150        .unwrap_or_default()
151        .to_str()
152        .unwrap_or_default()
153        .into();
154    let mut worker = RenameFileWorker {
155        ctx,
156        def_fid,
157        def_path,
158        diff,
159        inserted: FxHashSet::default(),
160    };
161    worker.work(edits)
162}
163
164fn link_path_matches_def(def_fid: TypstFileId, file_id: TypstFileId, path: &str) -> bool {
165    resolve_path_from_id(file_id, path).is_ok_and(|resolved| {
166        resolved.root() == def_fid.root() && resolved.vpath() == def_fid.vpath()
167    })
168}
169
170struct RenameFileWorker<'a> {
171    ctx: &'a mut LocalContext,
172    def_fid: TypstFileId,
173    def_path: Interned<str>,
174    diff: PathBuf,
175    inserted: FxHashSet<Span>,
176}
177
178impl RenameFileWorker<'_> {
179    pub(crate) fn work(&mut self, edits: &mut HashMap<Url, Vec<TextEdit>>) -> Option<()> {
180        let dep = self.ctx.module_dependencies().get(&self.def_fid).cloned();
181        if let Some(dep) = dep {
182            for ref_fid in dep.dependents.iter() {
183                self.refs_in_file(*ref_fid, edits);
184            }
185        }
186
187        for ref_fid in self.ctx.source_files().clone() {
188            self.links_in_file(ref_fid, edits);
189        }
190
191        Some(())
192    }
193
194    fn refs_in_file(
195        &mut self,
196        ref_fid: TypstFileId,
197        edits: &mut HashMap<Url, Vec<TextEdit>>,
198    ) -> Option<()> {
199        let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
200        let uri = self.ctx.uri_for_id(ref_fid).ok()?;
201
202        let import_info = self.ctx.expr_stage(&ref_src);
203
204        let edits = edits.entry(uri).or_default();
205        for (span, r) in &import_info.resolves {
206            if !matches!(
207                r.decl.as_ref(),
208                Decl::ImportPath(..) | Decl::IncludePath(..) | Decl::PathStem(..)
209            ) {
210                continue;
211            }
212
213            if let Some(edit) = self.rename_module_path(*span, r, &ref_src) {
214                edits.push(edit);
215            }
216        }
217
218        Some(())
219    }
220
221    fn links_in_file(
222        &mut self,
223        ref_fid: TypstFileId,
224        edits: &mut HashMap<Url, Vec<TextEdit>>,
225    ) -> Option<()> {
226        let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
227
228        let index = get_index_info(&ref_src);
229        if !index.paths.contains(&self.def_path) {
230            return Some(());
231        }
232
233        let uri = self.ctx.uri_for_id(ref_fid).ok()?;
234
235        let link_info = get_link_exprs(&ref_src);
236        let root = LinkedNode::new(ref_src.root());
237        let edits = edits.entry(uri).or_default();
238        for obj in &link_info.objects {
239            if !matches!(&obj.target,
240                LinkTarget::Path(file_id, path) if link_path_matches_def(self.def_fid, *file_id, path.as_ref())
241            ) {
242                continue;
243            }
244            if let Some(edit) = self.rename_resource_path(obj, &root, &ref_src) {
245                edits.push(edit);
246            }
247        }
248
249        Some(())
250    }
251
252    fn rename_resource_path(
253        &mut self,
254        obj: &LinkObject,
255        root: &LinkedNode,
256        src: &Source,
257    ) -> Option<TextEdit> {
258        let r = root.find(obj.span)?;
259        self.rename_path_expr(r.clone(), r.cast()?, src, false)
260    }
261
262    fn rename_module_path(&mut self, span: Span, r: &RefExpr, src: &Source) -> Option<TextEdit> {
263        let importing = r.root.as_ref()?.file_id();
264
265        if importing != Some(self.def_fid) {
266            return None;
267        }
268        crate::log_debug_ct!("import: {span:?} -> {importing:?} v.s. {:?}", self.def_fid);
269        // rename_importer(self.ctx, &ref_src, *span, &self.diff, edits);
270
271        let root = LinkedNode::new(src.root());
272        let import_node = root.find(span).and_then(first_ancestor_expr)?;
273        let (import_path, has_path_var) = node_ancestors(&import_node).find_map(|import_node| {
274            match import_node.cast::<ast::Expr>()? {
275                ast::Expr::ModuleImport(import) => Some((
276                    import.source(),
277                    import.new_name().is_none() && import.imports().is_none(),
278                )),
279                ast::Expr::ModuleInclude(include) => Some((include.source(), false)),
280                _ => None,
281            }
282        })?;
283
284        self.rename_path_expr(import_node.clone(), import_path, src, has_path_var)
285    }
286
287    fn rename_path_expr(
288        &mut self,
289        node: LinkedNode,
290        path: ast::Expr,
291        src: &Source,
292        has_path_var: bool,
293    ) -> Option<TextEdit> {
294        let new_text = match path {
295            ast::Expr::Str(s) => {
296                if !self.inserted.insert(s.span()) {
297                    return None;
298                }
299
300                let old_str = s.get();
301                let old_path = Path::new(old_str.as_str());
302                let new_path = old_path.join(&self.diff).clean();
303                let new_str = unix_slash(&new_path);
304
305                let path_part = Str::from(new_str).repr();
306                let need_alias = new_path.file_name() != old_path.file_name();
307
308                if has_path_var && need_alias {
309                    let alias = old_path.file_stem()?.to_str()?;
310                    format!("{path_part} as {alias}")
311                } else {
312                    path_part.to_string()
313                }
314            }
315            _ => return None,
316        };
317
318        let import_path_range = node.find(path.span())?.range();
319        let range = self.ctx.to_lsp_range(import_path_range, src);
320
321        Some(TextEdit { range, new_text })
322    }
323}
324
325pub(crate) fn edits_to_document_changes(
326    edits: HashMap<Url, Vec<TextEdit>>,
327    change_id: Option<&str>,
328) -> Vec<DocumentChangeOperation> {
329    let mut document_changes = vec![];
330
331    for (uri, edits) in edits {
332        document_changes.push(lsp_types::DocumentChangeOperation::Edit(TextDocumentEdit {
333            text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
334            edits: edits
335                .into_iter()
336                .map(|edit| match change_id {
337                    Some(change_id) => OneOf::Right(AnnotatedTextEdit {
338                        text_edit: edit,
339                        annotation_id: change_id.to_owned(),
340                    }),
341                    None => OneOf::Left(edit),
342                })
343                .collect(),
344        }));
345    }
346
347    document_changes
348}
349
350pub(crate) fn create_change_annotation(
351    label: &str,
352    needs_confirmation: bool,
353    description: Option<String>,
354) -> HashMap<String, ChangeAnnotation> {
355    let mut change_annotations = HashMap::new();
356    change_annotations.insert(
357        label.to_owned(),
358        ChangeAnnotation {
359            label: label.to_owned(),
360            needs_confirmation: Some(needs_confirmation),
361            description,
362        },
363    );
364
365    change_annotations
366}
367
368#[cfg(test)]
369mod tests {
370    use std::str::FromStr;
371
372    use super::*;
373    use crate::tests::*;
374    use tinymist_world::package::PackageSpec;
375    use typst::syntax::VirtualPath;
376
377    #[test]
378    fn test() {
379        snapshot_testing("rename", &|ctx, path| {
380            let source = ctx.source_by_path(&path).unwrap();
381
382            let request = RenameRequest {
383                path: path.clone(),
384                position: find_test_position(&source),
385                new_name: "new_name".to_string(),
386            };
387
388            let mut result = request.request(ctx);
389            // sort the edits to make the snapshot stable
390            if let Some(r) = result.as_mut().and_then(|r| r.changes.as_mut()) {
391                for edits in r.values_mut() {
392                    edits.sort_by(|a, b| {
393                        a.range
394                            .start
395                            .cmp(&b.range.start)
396                            .then(a.range.end.cmp(&b.range.end))
397                    });
398                }
399            };
400
401            assert_snapshot!(JsonRepr::new_redacted(result, &REDACT_LOC));
402        });
403    }
404
405    #[test]
406    fn link_path_match_requires_same_package_spec() {
407        let package_v010 = PackageSpec::from_str("@preview/example:0.1.0").unwrap();
408        let package_v011 = PackageSpec::from_str("@preview/example:0.1.1").unwrap();
409        let def_fid = TypstFileId::new(typst::syntax::RootedPath::new(
410            typst::syntax::VirtualRoot::Package(package_v010.clone()),
411            VirtualPath::new("/assets/logo.typ").unwrap(),
412        ));
413        let same_package_ref = TypstFileId::new(typst::syntax::RootedPath::new(
414            typst::syntax::VirtualRoot::Package(package_v010),
415            VirtualPath::new("/docs/main.typ").unwrap(),
416        ));
417        let other_package_ref = TypstFileId::new(typst::syntax::RootedPath::new(
418            typst::syntax::VirtualRoot::Package(package_v011),
419            VirtualPath::new("/docs/main.typ").unwrap(),
420        ));
421
422        assert!(link_path_matches_def(
423            def_fid,
424            same_package_ref,
425            "../assets/logo.typ"
426        ));
427        assert!(!link_path_matches_def(
428            def_fid,
429            other_package_ref,
430            "../assets/logo.typ"
431        ));
432    }
433
434    #[test]
435    fn link_path_match_keeps_root_fallback_for_root_base() {
436        let package = PackageSpec::from_str("@preview/example:0.1.0").unwrap();
437        let root = typst::syntax::VirtualRoot::Package(package);
438        let def_fid = TypstFileId::new(typst::syntax::RootedPath::new(
439            root.clone(),
440            VirtualPath::new("/assets/logo.typ").unwrap(),
441        ));
442        let root_ref = TypstFileId::new(typst::syntax::RootedPath::new(
443            root,
444            VirtualPath::new("/").unwrap(),
445        ));
446
447        assert!(link_path_matches_def(def_fid, root_ref, "assets/logo.typ"));
448    }
449}