@@ -10,7 +10,7 @@ use helix_core::{
1010use once_cell::sync::Lazy;
1111
1212use crate::{
13− compositor::{Callback, Compositor},
13+ compositor::{Callback, Component, Compositor},
1414 ui::{self, Picker, Popup, Prompt, PromptEvent},
1515};
1616
@@ -26,14 +26,20 @@ use crossterm::event::{KeyCode, KeyEvent};
2626
2727use helix_lsp::lsp;
2828
29+use crate::application::{LspCallbackWrapper, LspCallbacks};
30+
2931pub struct Context<'a> {
3032 pub count: usize,
3133 pub editor: &'a mut Editor,
3234
3335 pub callback: Option<crate::compositor::Callback>,
3436 pub on_next_key_callback: Option<Box<dyn FnOnce(&mut Context, KeyEvent)>>,
37+ pub callbacks: &'a mut LspCallbacks,
3538}
3639
40+use futures_util::FutureExt;
41+use std::future::Future;
42+
3743impl<'a> Context<'a> {
3844 #[inline]
3945 pub fn view(&mut self) -> &mut View {
@@ -47,7 +53,7 @@ impl<'a> Context<'a> {
4753 }
4854
4955 /// Push a new component onto the compositor.
50− pub fn push_layer(&mut self, mut component: Box<dyn crate::compositor::Component>) {
56+ pub fn push_layer(&mut self, mut component: Box<dyn Component>) {
5157 self.callback = Some(Box::new(
5258 |compositor: &mut Compositor, editor: &mut Editor| {
5359 let size = compositor.size();
@@ -65,6 +71,27 @@ impl<'a> Context<'a> {
6571 ) {
6672 self.on_next_key_callback = Some(Box::new(on_next_key_callback));
6773 }
74+
75+ #[inline]
76+ pub fn callback<T, F>(
77+ &mut self,
78+ call: impl Future<Output = helix_lsp::Result<serde_json::Value>> + 'static + Send,
79+ callback: F,
80+ ) where
81+ T: for<'de> serde::Deserialize<'de> + Send + 'static,
82+ F: FnOnce(&mut Editor, &mut Compositor, T) + Send + 'static,
83+ {
84+ let callback = Box::pin(async move {
85+ let json = call.await?;
86+ let response = serde_json::from_value(json)?;
87+ let call: LspCallbackWrapper =
88+ Box::new(move |editor: &mut Editor, compositor: &mut Compositor| {
89+ callback(editor, compositor, response)
90+ });
91+ Ok(call)
92+ });
93+ self.callbacks.push(callback);
94+ }
6895}
6996
7097/// A command is a function that takes the current state and a count, and does a side-effect on the
@@ -1564,6 +1591,24 @@ pub fn save(cx: &mut Context) {
15641591}
15651592
15661593pub fn completion(cx: &mut Context) {
1594+ // trigger on trigger char, or if user calls it
1595+ // (or on word char typing??)
1596+ // after it's triggered, if response marked is_incomplete, update on every subsequent keypress
1597+ //
1598+ // lsp calls are done via a callback: it sends a request and doesn't block.
1599+ // when we get the response similarly to notification, trigger a call to the completion popup
1600+ //
1601+ // language_server.completion(params, |cx: &mut Context, _meta, response| {
1602+ // // called at response time
1603+ // // compositor, lookup completion layer
1604+ // // downcast dyn Component to Completion component
1605+ // // emit response to completion (completion.complete/handle(response))
1606+ // })
1607+ // async {
1608+ // let (response, callback) = response.await?;
1609+ // callback(response)
1610+ // }
1611+
15671612 let doc = cx.doc();
15681613
15691614 let language_server = match doc.language_server() {
@@ -1576,91 +1621,119 @@ pub fn completion(cx: &mut Context) {
15761621
15771622 // TODO: handle fails
15781623
1579− let res = smol::block_on(language_server.completion(doc.identifier(), pos)).unwrap_or_default();
1580−
1581− // TODO: if no completion, show some message or something
1582− if !res.is_empty() {
1583− // let snapshot = doc.state.clone();
1584− let mut menu = ui::Menu::new(
1585− res,
1586− |item| {
1587− // format_fn
1588− item.label.as_str().into()
1589−
1590− // TODO: use item.filter_text for filtering
1591− },
1592− move |editor: &mut Editor, item, event| {
1593− match event {
1594− PromptEvent::Abort => {
1595− // revert state
1596− // let id = editor.view().doc;
1597− // let doc = &mut editor.documents[id];
1598− // doc.state = snapshot.clone();
1599− }
1600− PromptEvent::Validate => {
1601− let id = editor.view().doc;
1602− let doc = &mut editor.documents[id];
1603−
1604− // revert state to what it was before the last update
1605− // doc.state = snapshot.clone();
1606−
1607− // extract as fn(doc, item):
1608−
1609− // TODO: need to apply without composing state...
1610− // TODO: need to update lsp on accept/cancel by diffing the snapshot with
1611− // the final state?
1612− // -> on update simply update the snapshot, then on accept redo the call,
1613− // finally updating doc.changes + notifying lsp.
1614− //
1615− // or we could simply use doc.undo + apply when changing between options
1616−
1617− // always present here
1618− let item = item.unwrap();
1619−
1620− use helix_lsp::{lsp, util};
1621− // determine what to insert: text_edit | insert_text | label
1622− let edit = if let Some(edit) = &item.text_edit {
1623− match edit {
1624− lsp::CompletionTextEdit::Edit(edit) => edit.clone(),
1625− lsp::CompletionTextEdit::InsertAndReplace(item) => {
1626− unimplemented!("completion: insert_and_replace {:?}", item)
1624+ let res = smol::block_on(language_server.completion(doc.identifier(), pos)).unwrap();
1625+
1626+ cx.callback(
1627+ res,
1628+ |editor: &mut Editor,
1629+ compositor: &mut Compositor,
1630+ response: Option<lsp::CompletionResponse>| {
1631+ let items = match response {
1632+ Some(lsp::CompletionResponse::Array(items)) => items,
1633+ // TODO: do something with is_incomplete
1634+ Some(lsp::CompletionResponse::List(lsp::CompletionList {
1635+ is_incomplete: _is_incomplete,
1636+ items,
1637+ })) => items,
1638+ None => Vec::new(),
1639+ };
1640+
1641+ // TODO: if no completion, show some message or something
1642+ if !items.is_empty() {
1643+ // let snapshot = doc.state.clone();
1644+ let mut menu = ui::Menu::new(
1645+ items,
1646+ |item| {
1647+ // format_fn
1648+ item.label.as_str().into()
1649+
1650+ // TODO: use item.filter_text for filtering
1651+ },
1652+ move |editor: &mut Editor, item, event| {
1653+ match event {
1654+ PromptEvent::Abort => {
1655+ // revert state
1656+ // let id = editor.view().doc;
1657+ // let doc = &mut editor.documents[id];
1658+ // doc.state = snapshot.clone();
1659+ }
1660+ PromptEvent::Validate => {
1661+ let id = editor.view().doc;
1662+ let doc = &mut editor.documents[id];
1663+
1664+ // revert state to what it was before the last update
1665+ // doc.state = snapshot.clone();
1666+
1667+ // extract as fn(doc, item):
1668+
1669+ // TODO: need to apply without composing state...
1670+ // TODO: need to update lsp on accept/cancel by diffing the snapshot with
1671+ // the final state?
1672+ // -> on update simply update the snapshot, then on accept redo the call,
1673+ // finally updating doc.changes + notifying lsp.
1674+ //
1675+ // or we could simply use doc.undo + apply when changing between options
1676+
1677+ // always present here
1678+ let item = item.unwrap();
1679+
1680+ use helix_lsp::{lsp, util};
1681+ // determine what to insert: text_edit | insert_text | label
1682+ let edit = if let Some(edit) = &item.text_edit {
1683+ match edit {
1684+ lsp::CompletionTextEdit::Edit(edit) => edit.clone(),
1685+ lsp::CompletionTextEdit::InsertAndReplace(item) => {
1686+ unimplemented!(
1687+ "completion: insert_and_replace {:?}",
1688+ item
1689+ )
1690+ }
1691+ }
1692+ } else {
1693+ item.insert_text.as_ref().unwrap_or(&item.label);
1694+ unimplemented!();
1695+ // lsp::TextEdit::new(); TODO: calculate a TextEdit from insert_text
1696+ // and we insert at position.
1697+ };
1698+
1699+ // TODO: merge edit with additional_text_edits
1700+ if let Some(additional_edits) = &item.additional_text_edits {
1701+ if !additional_edits.is_empty() {
1702+ unimplemented!(
1703+ "completion: additional_text_edits: {:?}",
1704+ additional_edits
1705+ );
1706+ }
16271707 }
1708+
1709+ let transaction =
1710+ util::generate_transaction_from_edits(doc.text(), vec![edit]);
1711+ doc.apply(&transaction);
1712+ // TODO: doc.append_changes_to_history(); if not in insert mode?
16281713 }
1629− } else {
1630− item.insert_text.as_ref().unwrap_or(&item.label);
1631− unimplemented!();
1632− // lsp::TextEdit::new(); TODO: calculate a TextEdit from insert_text
1633− // and we insert at position.
1714+ _ => (),
16341715 };
1716+ },
1717+ );
16351718
1636− // TODO: merge edit with additional_text_edits
1637− if let Some(additional_edits) = &item.additional_text_edits {
1638− if !additional_edits.is_empty() {
1639− unimplemented!(
1640− "completion: additional_text_edits: {:?}",
1641− additional_edits
1642− );
1643− }
1644− }
1719+ let popup = Popup::new(Box::new(menu));
1720+ let mut component: Box<dyn Component> = Box::new(popup);
16451721
1646− // TODO: <-- if state has changed by further input, transaction will panic on len
1647− let transaction =
1648− util::generate_transaction_from_edits(doc.text(), vec![edit]);
1649− doc.apply(&transaction);
1650− // TODO: doc.append_changes_to_history(); if not in insert mode?
1651− }
1652− _ => (),
1653− };
1654− },
1655− );
1722+ // Server error: content modified
16561723
1657− let popup = Popup::new(Box::new(menu));
1658− cx.push_layer(Box::new(popup));
1724+ // TODO: this is shared with cx.push_layer
1725+ let size = compositor.size();
1726+ // trigger required_size on init
1727+ component.required_size((size.width, size.height));
1728+ compositor.push(component);
1729+ }
1730+ },
1731+ );
16591732
1660− // TODO!: when iterating over items, show the docs in popup
1733+ // // TODO!: when iterating over items, show the docs in popup
16611734
1662− // language server client needs to be accessible via a registry of some sort
1663− }
1735+ // // language server client needs to be accessible via a registry of some sort
1736+ //}
16641737}
16651738
16661739pub fn hover(cx: &mut Context) {