Skip to main content

swls_core/feature/
completion.rs

1use crate::lsp_types::{MarkupContent, MarkupKind};
2use crate::prelude::{
3    MyTerm, PositionComponent, RopeC, TokenComponent, TripleComponent, TripleTarget,
4};
5use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
6use derive_more::{AsMut, AsRef, Deref, DerefMut};
7
8use crate::lsp_types::{
9    CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionTextEdit,
10    Documentation, InsertTextFormat, TextEdit,
11};
12pub use crate::{
13    systems::{
14        complete_class, complete_properties, keyword_complete,
15        prefix::rdf_lov_undefined_prefix_completion,
16    },
17    util::{token::get_current_cst_token, triple::get_current_triple},
18};
19
20/// [`ScheduleLabel`] related to the Completion schedule
21#[derive(ScheduleLabel, Clone, Eq, PartialEq, Debug, Hash)]
22pub struct Label;
23
24/// [`Component`] indicating that the current document is handling a Completion request.
25#[derive(Component, AsRef, Deref, AsMut, DerefMut, Debug)]
26pub struct CompletionRequest(pub Vec<SimpleCompletion>);
27
28pub fn setup_schedule(world: &mut World) {
29    let mut completion = Schedule::new(Label);
30    completion.add_systems((
31        get_current_cst_token,
32        get_current_triple
33            .after(get_current_cst_token)
34            .before(generate_completions),
35        get_cursor_context
36            .after(get_current_triple)
37            .before(generate_completions),
38        keyword_complete.after(generate_completions),
39        complete_class.after(generate_completions),
40        complete_properties.after(generate_completions),
41        crate::systems::complete_shape_templates.after(generate_completions),
42        crate::systems::shape_property_completions.after(complete_properties),
43        rdf_lov_undefined_prefix_completion.after(generate_completions),
44    ));
45    world.add_schedule(completion);
46}
47
48pub fn generate_completions() {}
49
50/// What a completion request is about, resolved once from the cursor so every
51/// completion source agrees. Inserted by [`get_cursor_context`].
52#[derive(Component, Debug, Clone)]
53pub struct CursorContext {
54    /// The role of the position at the cursor.
55    pub target: TripleTarget,
56    /// The resource being described: the subject of the triple at the cursor,
57    /// or the blank node whose `[ … ]` the cursor is in.
58    pub subject: Option<MyTerm<'static>>,
59    /// The word being typed at the cursor (empty in whitespace or after
60    /// punctuation).
61    pub typed: String,
62    /// Where completion text goes: the typed word, or an empty range at the
63    /// cursor.
64    pub range: crate::lsp_types::Range,
65    /// Whether inserted text needs a leading space (the cursor is right after
66    /// `;`, `,` or `[`).
67    pub needs_space: bool,
68}
69
70impl CursorContext {
71    /// Whether the cursor is where a predicate of [`Self::subject`] goes.
72    pub fn at_predicate(&self) -> bool {
73        self.target == TripleTarget::Predicate && self.subject.is_some()
74    }
75
76    /// `text` prefixed with a space when [`Self::needs_space`].
77    pub fn spaced(&self, text: &str) -> String {
78        if self.needs_space {
79            format!(" {}", text)
80        } else {
81            text.to_string()
82        }
83    }
84}
85
86/// Resolve the [`CursorContext`] of a completion request from the token and
87/// triple at the cursor.
88pub fn get_cursor_context(
89    query: Query<(
90        Entity,
91        &PositionComponent,
92        Option<&TokenComponent>,
93        Option<&TripleComponent>,
94        &RopeC,
95    )>,
96    mut commands: Commands,
97) {
98    for (entity, pos, token, triple, rope) in &query {
99        let offset = crate::util::position_to_offset(pos.0, &rope.0).unwrap_or_default();
100        let at_cursor = crate::lsp_types::Range::new(pos.0, pos.0);
101
102        let token_text = token.map(|t| t.text.as_str()).unwrap_or_default();
103        let punctuation =
104            !token_text.is_empty() && token_text.chars().all(|c| ";.,[](){}".contains(c));
105        let (typed, range, needs_space) = match token {
106            Some(t) if !t.text.is_empty() && !punctuation => (t.text.clone(), t.range, false),
107            // Right after `;` / `,` / `[`: insert behind it, separated by a space.
108            Some(t) if punctuation && t.source_span.end <= offset => {
109                let end = crate::lsp_types::Range::new(t.range.end, t.range.end);
110                (String::new(), end, matches!(token_text, ";" | "," | "["))
111            }
112            _ => (String::new(), at_cursor, false),
113        };
114
115        let (mut target, mut subject) = match triple {
116            Some(t) => (t.target, Some(t.triple.subject.to_owned())),
117            None => (TripleTarget::Subject, None),
118        };
119        // Inside `[ … ]` but not on a term: a predicate of that blank node.
120        if let Some(t) = triple {
121            let inside = |term: &MyTerm<'_>| {
122                term.ty == Some(sophia_api::term::TermKind::BlankNode)
123                    && term.span.start < offset
124                    && offset < term.span.end
125            };
126            let on_term = !typed.is_empty();
127            if !on_term && target == TripleTarget::Subject && inside(&t.triple.subject) {
128                target = TripleTarget::Predicate;
129            } else if !on_term && target == TripleTarget::Object && inside(&t.triple.object) {
130                target = TripleTarget::Predicate;
131                subject = Some(t.triple.object.to_owned());
132            }
133        }
134
135        commands.entity(entity).insert(CursorContext {
136            target,
137            subject,
138            typed,
139            range,
140            needs_space,
141        });
142    }
143}
144
145#[derive(Debug)]
146pub struct SimpleCompletion {
147    pub kind: CompletionItemKind,
148    pub label: String,
149    pub _is_snippet: bool,
150    pub _label_details: Option<CompletionItemLabelDetails>,
151    pub _documentation: Option<String>,
152    pub _sort_text: Option<String>,
153    pub _filter_text: Option<String>,
154    pub edits: Vec<TextEdit>,
155    pub _commit_char: Option<String>,
156}
157
158impl SimpleCompletion {
159    pub fn new(kind: CompletionItemKind, label: String, edit: TextEdit) -> Self {
160        Self {
161            kind,
162            label,
163            edits: vec![edit],
164            _is_snippet: false,
165            _label_details: None,
166            _documentation: None,
167            _sort_text: None,
168            _filter_text: None,
169            _commit_char: None,
170        }
171    }
172    pub fn as_snippet(mut self) -> Self {
173        self._is_snippet = true;
174        self
175    }
176
177    pub fn label_detail(mut self, detail: impl Into<String>) -> Self {
178        if let Some(ref mut t) = self._label_details {
179            t.detail = Some(detail.into());
180        } else {
181            self._label_details = Some(CompletionItemLabelDetails {
182                detail: Some(detail.into()),
183                description: None,
184            });
185        }
186        self
187    }
188
189    pub fn label_description(mut self, description: impl Into<String>) -> Self {
190        self.set_label_description(description);
191        self
192    }
193
194    /// Set the description shown next to the label of an existing item.
195    pub fn set_label_description(&mut self, description: impl Into<String>) {
196        if let Some(ref mut t) = self._label_details {
197            t.description = Some(description.into());
198        } else {
199            self._label_details = Some(CompletionItemLabelDetails {
200                description: Some(description.into()),
201                detail: None,
202            });
203        }
204    }
205
206    pub fn text_edit(mut self, edit: TextEdit) -> Self {
207        self.edits.push(edit);
208        self
209    }
210
211    pub fn documentation(mut self, documentation: impl Into<String>) -> Self {
212        self._documentation = Some(documentation.into());
213        self
214    }
215
216    pub fn m_documentation<S: Into<String>>(mut self, documentation: Option<S>) -> Self {
217        self._documentation = documentation.map(|x| x.into());
218        self
219    }
220
221    pub fn sort_text(mut self, sort_text: impl Into<String>) -> Self {
222        self._sort_text = Some(sort_text.into());
223        self
224    }
225
226    pub fn filter_text(mut self, filter_text: impl Into<String>) -> Self {
227        self._filter_text = Some(filter_text.into());
228        self
229    }
230
231    pub fn commit_char(mut self, commit_char: impl Into<String>) -> Self {
232        self._commit_char = Some(commit_char.into());
233        self
234    }
235}
236
237/// Order completions the way LSP clients do: by sort text, or by label when an
238/// item has none. (Comparing `Option`s would put every item without a sort
239/// text first.)
240pub fn sort_completions(items: &mut [SimpleCompletion]) {
241    items.sort_by(|a, b| {
242        let key = |c: &SimpleCompletion| c._sort_text.clone().unwrap_or_else(|| c.label.clone());
243        key(a).cmp(&key(b))
244    });
245}
246
247impl From<SimpleCompletion> for CompletionItem {
248    fn from(val: SimpleCompletion) -> Self {
249        let SimpleCompletion {
250            _is_snippet: is_snippet,
251            _filter_text: filter_text,
252            _sort_text: sort_text,
253            label,
254            _label_details,
255            _documentation: documentation,
256            kind,
257            edits,
258            _commit_char: commit_char,
259        } = val;
260
261        let text_edit = edits.first().map(|x| CompletionTextEdit::Edit(x.clone()));
262
263        let additional_text_edits = edits.into_iter().skip(1).collect();
264
265        CompletionItem {
266            label,
267            kind: Some(kind),
268            sort_text,
269            insert_text_format: (kind == CompletionItemKind::SNIPPET || is_snippet)
270                .then_some(InsertTextFormat::SNIPPET),
271            filter_text,
272            label_details: _label_details,
273            documentation: documentation.map(|st| {
274                Documentation::MarkupContent(MarkupContent {
275                    kind: MarkupKind::Markdown,
276                    value: st,
277                })
278            }),
279            text_edit,
280            additional_text_edits: Some(additional_text_edits),
281            commit_characters: commit_char.map(|x| vec![x]),
282            ..Default::default()
283        }
284    }
285}