summaryrefslogtreecommitdiff
path: root/support/texlab/src/features/rename/command.rs
blob: 1e5f2ff0ca409b331f19a98970a3409794644691 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use rowan::{TextRange, TextSize};
use rustc_hash::FxHashMap;

use crate::{syntax::latex, util::cursor::CursorContext};

use super::{Indel, Params, RenameResult};

pub(super) fn prepare_rename<T>(context: &CursorContext<T>) -> Option<TextRange> {
    context.cursor.command_range(context.offset)
}

pub(super) fn rename(context: &CursorContext<Params>) -> Option<RenameResult> {
    prepare_rename(context)?;
    let name = context.cursor.as_tex()?.text();
    let mut changes = FxHashMap::default();
    for document in context.related() {
        if let Some(data) = document.parse(context.db).as_tex() {
            let root = data.root(context.db);
            let edits = root
                .descendants_with_tokens()
                .filter_map(|element| element.into_token())
                .filter(|token| token.kind() == latex::COMMAND_NAME && token.text() == name)
                .map(|token| {
                    let range = token.text_range();
                    Indel {
                        delete: TextRange::new(range.start() + TextSize::from(1), range.end()),
                        insert: context.params.new_name.clone(),
                    }
                })
                .collect();

            changes.insert(document, edits);
        }
    }

    Some(RenameResult { changes })
}