Skip to content

Visual Studio Code, rebuilt in Rust

Rust
53.3 KB
Raw Blame
//! suggestWidget.ts and suggestWidgetRenderer.ts: the list of completions under (or above) the cursor, its focus,
//! the Loading and No suggestions messages, and the resolve of the focused item.

use std::time::Duration;

use gpui::{AnyElement, BoxShadow, Context, Div, FontWeight, HighlightStyle, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, SharedString, canvas, StyledText, Task, Window, deferred, div, point, prelude::*, px};
use serde_json::{Value, json};

use super::Workbench;
use super::editor_message::horizontal_in_page;
use super::suggest_controller::InsertFlags;
use crate::editor::{LINE_HEIGHT, OpenEditor, Position, column_x};
use crate::filters::create_matches;
use crate::keybindings;
use crate::menus::{MenuAction, MenuId, menu_group_actions};
use crate::suggest::CompletionItem;
use crate::symbol_icons::completion_kind_icon;

const EDITOR_FONT: &str = "Menlo";
const EDITOR_FONT_SIZE: f32 = 12.;
/// cornerRadius-large.
const RADIUS: f32 = 8.;
/// `getLayoutInfo`: the default size shows 12 items; the widget keeps 22px from the window's edges.
const VISIBLE_ITEMS: usize = 12;
const DEFAULT_WIDTH: f32 = 430.;
const VERTICAL_PADDING: f32 = 22.;
const HORIZONTAL_PADDING: f32 = 14.;
/// suggestWidget.ts `_persistedSize`'s neighbour: whether the docs are expanded, in the profile storage.
const EXPAND_DOCS_KEY: &str = "expandSuggestionDocs";
/// `PersistedWidgetSize`'s key for a code editor that is not embedded.
const SIZE_KEY: &str = "suggestWidget.size/vs.editor.ICodeEditor/false";
/// sash.ts `size`, centered on the widget's edges.
const SASH_SIZE: f32 = 4.;
/// `minSize`'s width.
const MIN_WIDTH: f32 = 220.;
/// SuggestDetailsWidget `_size`'s width.
const DETAILS_WIDTH: f32 = 330.;

#[derive(Clone, Copy, Default, PartialEq, Debug)]
pub(super) enum State {
    #[default]
    Hidden,
    Loading,
    Empty,
    Open,
    Frozen,
}

#[derive(Default)]
pub(super) struct WidgetState {
    pub state: State,
    pub focused: Option<usize>,
    /// The first item in view.
    top: usize,
    list_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
    is_auto: bool,
    /// `_loadingTimeout`.
    loading: Option<Task<()>>,
    /// The content widget's position: the cursor when shown.
    position: Option<Position>,
    /// `_currentSuggestionDetails`: the resolve of the focused item, cancelled by dropping it.
    resolving: Option<Task<()>>,
    /// `expandSuggestionDocs` of the profile storage, read on the first show.
    pub details: bool,
    details_read: bool,
    /// `element.size` without the borders: the persisted size on show, then what a sash drag makes it.
    size: Option<(f32, f32)>,
    resize: Option<Resize>,
    /// SuggestDetailsOverlay `_userSize`: what a sash drag made the details, until the session ends.
    details_size: Option<(f32, f32)>,
    details_resize: Option<DetailsResize>,
    /// SuggestDetailsWidget `size.height`: the content's height as last drawn, with the borders.
    details_height: std::rc::Rc<std::cell::Cell<Option<f32>>>,
    /// The sash the pointer rests on past the hover delay: the list's or the details', and its index.
    pub hovered_sash: Option<(&'static str, usize)>,
    sash_hover: Option<Task<()>>,
}

/// A details sash drag: the edge (north, east, south, west), and `minSize` and `maxSize` as `_placeAtAnchor` set them.
struct DetailsResize {
    edge: usize,
    pointer: gpui::Point<f32>,
    start: (f32, f32),
    min: (f32, f32),
    max: (f32, f32),
}

/// `ResizeState` of a sash drag, with the limits `_layout` gave the element.
struct Resize {
    /// The north, east and south sashes; above the line the widget grows north, below it south.
    north: bool,
    east: bool,
    south: bool,
    pointer: gpui::Point<f32>,
    start: (f32, f32),
    persisted: Option<(f32, f32)>,
    persist_width: bool,
    persist_height: bool,
    above: bool,
    limits: SizeLimits,
}

/// `_layout`'s `maxSize` and `minSize` heights and `defaultSize`, without the borders.
#[derive(Clone, Copy)]
struct SizeLimits {
    max: (f32, f32),
    min_height: f32,
    default: (f32, f32),
}

impl Workbench {
    pub(super) fn suggest_widget_visible(&self) -> bool {
        self.suggest.widget.state != State::Hidden
    }

    pub(super) fn suggest_widget_frozen(&self) -> bool {
        self.suggest.widget.state == State::Frozen
    }

    /// `showTriggered`: a manual trigger shows "Loading..." after `delay` ms.
    pub(super) fn show_suggest_triggered(&mut self, auto: bool, cx: &mut Context<Self>) {
        let widget = &mut self.suggest.widget;
        if widget.state != State::Hidden {
            return;
        }
        widget.position = self.editors.active().map(|editor| editor.selection().head);
        widget.is_auto = auto;
        if !auto {
            widget.loading = Some(cx.spawn(async |workbench, cx| {
                cx.background_executor().timer(Duration::from_millis(50)).await;
                let _ = workbench.update(cx, |workbench, cx| {
                    workbench.set_suggest_widget_state(State::Loading, cx);
                    cx.notify();
                });
            }));
        }
    }

    /// `showSuggestions`.
    pub(super) fn show_suggestions(&mut self, index: usize, frozen: bool, auto: bool, no_focus: bool, cx: &mut Context<Self>) {
        let position = self.editors.active().map(|editor| editor.selection().head);
        let count = self.suggest_items().len();
        let widget = &mut self.suggest.widget;
        widget.position = position;
        widget.loading = None;
        widget.resolving = None;
        if frozen && widget.state != State::Empty && widget.state != State::Hidden {
            self.set_suggest_widget_state(State::Frozen, cx);
            cx.notify();
            return;
        }
        if count == 0 {
            self.set_suggest_widget_state(if auto { State::Hidden } else { State::Empty }, cx);
            cx.notify();
            return;
        }
        self.set_suggest_widget_state(if frozen { State::Frozen } else { State::Open }, cx);
        self.suggest.widget.top = 0;
        self.focus_suggestion(if no_focus { None } else { Some(index) }, cx);
        // `onDidShow`, also for a refilter that keeps the focused index but moves its item's range.
        self.inline_completions_suggest_changed(cx);
        cx.notify();
    }

    pub(super) fn hide_suggest_widget(&mut self, cx: &mut Context<Self>) {
        self.set_suggest_widget_state(State::Hidden, cx);
    }

    /// `_setState`.
    fn set_suggest_widget_state(&mut self, state: State, cx: &mut Context<Self>) {
        let widget = &mut self.suggest.widget;
        if widget.state == state {
            return;
        }
        if !widget.details_read {
            widget.details_read = true;
            widget.details = self.profile_storage.lock().unwrap().get(EXPAND_DOCS_KEY) == Some("true");
        }
        let restored = persisted_size(&self.profile_storage.lock().unwrap());
        let widget = &mut self.suggest.widget;
        widget.state = state;
        widget.resize = None;
        if state == State::Hidden {
            widget.details_size = None;
            widget.details_resize = None;
            // `hideWidget`: a persisted height under 4.3 items grows back to it.
            let min_persisted_height = (LINE_HEIGHT * 4.3).ceil();
            if let Some((width, _)) = restored.filter(|(_, height)| *height < min_persisted_height) {
                store_size(&mut self.profile_storage.lock().unwrap(), (width, min_persisted_height));
            }
        } else {
            widget.size = restored;
        }
        if matches!(state, State::Hidden | State::Loading | State::Empty) {
            widget.focused = None;
            widget.resolving = None;
            widget.top = 0;
            if state == State::Hidden {
                widget.loading = None;
            }
            self.suggest_item_focused(None, cx);
        }
    }

    /// The session's items as last filtered.
    pub(super) fn suggest_items(&self) -> &[CompletionItem] {
        match self.suggest.session.as_ref().and_then(|session| session.model.as_ref()) {
            Some(model) => model.filtered(),
            None => &[],
        }
    }

    /// `_onListFocus`: the focused item is revealed and resolved.
    fn focus_suggestion(&mut self, index: Option<usize>, cx: &mut Context<Self>) {
        let count = self.suggest_items().len();
        let index = index.filter(|index| *index < count);
        let widget = &mut self.suggest.widget;
        if widget.focused == index && index.is_some() {
            return;
        }
        widget.focused = index;
        widget.resolving = None;
        let Some(index) = index else {
            self.suggest_item_focused(None, cx);
            return;
        };
        let visible = count.min(VISIBLE_ITEMS);
        if index < widget.top {
            widget.top = index;
        } else if index >= widget.top + visible {
            widget.top = index + 1 - visible;
        }
        let item = self.suggest_items()[index].clone();
        self.suggest_item_focused(Some(&item), cx);
        if item.resolved {
            return;
        }
        let resolve = self.host.call_cancellable("ExtHostLanguageFeatures", "$resolveCompletionItem", vec![json!(item.provider), item.id.clone()]);
        self.suggest.widget.resolving = Some(cx.spawn(async move |workbench, cx| {
            let answer = resolve.await;
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.suggest.widget.resolving = None;
                let Some(model) = workbench.suggest.session.as_mut().and_then(|session| session.model.as_mut()) else { return };
                let Some(focused) = model.item_mut(index).filter(|focused| focused.label == item.label && focused.provider == item.provider) else { return };
                match answer {
                    Ok(Ok(resolved)) if resolved.is_object() => focused.merge_resolved(&resolved),
                    _ => focused.resolved = true,
                }
                let focused = focused.clone();
                workbench.suggest_item_focused(Some(&focused), cx);
                cx.notify();
            });
        }));
    }

    pub(super) fn register_suggest_widget_commands(&mut self) {
        type Move = fn(usize, usize, usize, Option<usize>) -> Option<usize>;
        let moves: [(&str, Move); 6] = [
            ("selectNextSuggestion", |count, _, _, focused| Some(focused.map_or(0, |focused| (focused + 1) % count))),
            ("selectPrevSuggestion", |count, _, _, focused| Some(focused.map_or(count - 1, |focused| (focused + count - 1) % count))),
            ("selectFirstSuggestion", |_, _, _, _| Some(0)),
            ("selectLastSuggestion", |count, _, _, _| Some(count - 1)),
            // list.focusNextPage: the last item in view, else a page further.
            ("selectNextPageSuggestion", |count, top, visible, focused| {
                let last = (top + visible).min(count) - 1;
                Some(match focused {
                    Some(focused) if focused >= last => (focused + visible - 1).min(count - 1),
                    _ => last,
                })
            }),
            ("selectPrevPageSuggestion", |_, top, visible, focused| {
                Some(match focused {
                    Some(focused) if focused <= top => focused.saturating_sub(visible - 1),
                    _ => top,
                })
            }),
        ];
        for (id, step) in moves {
            self.commands.register(id, move |workbench, _, _, cx| {
                match workbench.suggest.widget.state {
                    State::Hidden | State::Loading | State::Empty => {}
                    State::Open | State::Frozen => {
                        let count = workbench.suggest_items().len();
                        if count > 0 {
                            let widget = &workbench.suggest.widget;
                            let next = step(count, widget.top, count.min(VISIBLE_ITEMS), widget.focused);
                            workbench.focus_suggestion(next, cx);
                            cx.notify();
                        }
                    }
                }
                crate::commands::Outcome::done()
            });
        }
        // `toggleDetails`: off always; on for a focused item with details or documentation, stored for the profile.
        self.commands.register("toggleSuggestionDetails", |workbench, _, _, cx| {
            let can_expand = matches!(workbench.suggest.widget.state, State::Open | State::Frozen) && workbench.focused_suggestion().is_some_and(CompletionItem::can_expand);
            let widget = &mut workbench.suggest.widget;
            if widget.details || can_expand {
                widget.details = !widget.details;
                let value = if widget.details { "true" } else { "false" };
                workbench.profile_storage.lock().unwrap().set(EXPAND_DOCS_KEY, value.into());
                cx.notify();
            }
            crate::commands::Outcome::done()
        });
        // `resetWidgetSize`.
        self.commands.register("editor.action.resetSuggestSize", |workbench, _, _, _| {
            workbench.profile_storage.lock().unwrap().delete(SIZE_KEY);
            crate::commands::Outcome::done()
        });
        self.commands.register("focusSuggestion", |workbench, _, _, cx| {
            if workbench.suggest_items().len() > 0 {
                workbench.focus_suggestion(Some(0), cx);
                cx.notify();
            }
            crate::commands::Outcome::done()
        });
    }

    /// The suggest context keys of suggest.ts `Context` and the controller.
    pub(super) fn suggest_context(&self, context: &mut std::collections::HashMap<String, Value>) {
        let Some(editor) = self.editors.active() else { return };
        let uri = editor.document().uri();
        let candidate = crate::language_features::Candidate { uri: &uri, language: &editor.document().language_id };
        context.insert("editorHasCompletionItemProvider".into(), json!(!self.language_features.ordered("$registerCompletionsProvider", &candidate).is_empty()));
        let accept_on_enter = self.suggest_setting(editor, "editor.acceptSuggestionOnEnter");
        context.insert("acceptSuggestionOnEnter".into(), json!(matches!(accept_on_enter.as_str(), Some("on" | "smart") | None)));
        context.insert("suggestionInsertMode".into(), self.suggest_setting(editor, "editor.suggest.insertMode"));
        let head = editor.selection().head;
        let line = editor.document().lines[head.line].clone();
        let smart = accept_on_enter == "smart";
        let visible = self.suggest_widget_visible();
        let auto = self.suggest.session.as_ref().is_some_and(|session| session.options.auto);
        context.insert("suggestWidgetVisible".into(), json!(visible));
        context.insert("suggestWidgetMultipleSuggestions".into(), json!(visible && self.suggest_items().len() > 1));
        let focused = self.suggest.widget.focused.filter(|_| visible).and_then(|index| self.suggest_items().get(index).cloned());
        context.insert("suggestWidgetHasFocusedSuggestion".into(), json!(focused.is_some()));
        context.insert("suggestWidgetDetailsVisible".into(), json!(self.suggest_details_visible()));
        if let Some(item) = focused {
            // The `onDidFocus` listener: with `smart`, an automatic suggestion that would only write what is typed makes no edit.
            let mut makes_text_edit = true;
            let typed = head.column.saturating_sub(item.edit_start.column);
            if smart && auto && item.additional_text_edits.is_null() && item.insert_text_rules & crate::suggest::INSERT_AS_SNIPPET == 0 && typed == item.insert_text.chars().count() {
                let old: String = line.chars().skip(item.edit_start.column).take(typed).collect();
                makes_text_edit = old != item.insert_text;
            }
            context.insert("suggestionMakesTextEdit".into(), json!(makes_text_edit));
            context.insert("suggestionHasInsertAndReplaceRange".into(), json!(item.edit_insert_end != item.edit_replace_end));
            let can_resolve = !item.resolved || !item.documentation.is_null() || item.detail.as_deref() != Some(&item.label);
            context.insert("suggestionCanResolve".into(), json!(can_resolve));
        }
    }

    /// The content widget at the cursor: below the line, or above when it fits better there (`_layout`).
    pub(super) fn suggest_widget(&self, editor: &OpenEditor, content_left: f32, char_width: f32, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
        let state = self.suggest.widget.state;
        if state == State::Hidden {
            return None;
        }
        let position = self.suggest.widget.position?;
        if self.suggest.session.as_ref().is_none_or(|session| session.model_id != editor.model_id) || editor.folding.is_hidden(position.line) {
            return None;
        }
        let text = editor.document().lines.get(position.line)?.clone();
        let left = column_x(&text, position.column, editor.document().indentation.tab_size) * char_width - editor.scroll.left + content_left;
        let line_top = editor.line_top(editor.view_line(position.line), self.editors.viewport) - editor.scroll.top;
        let editor_bounds = self.text_area_bounds.get();
        let window_size = window.viewport_size().map(f32::from);
        let item_height = LINE_HEIGHT;
        let count = self.suggest_items().len();
        let message = matches!(state, State::Loading | State::Empty);
        let status_bar_height = if !message && self.suggest_setting(editor, "editor.suggest.showStatusBar") == Value::Bool(true) { item_height } else { 0. };
        let cursor_bottom = editor_bounds.origin.y + line_top + LINE_HEIGHT;
        let space_below = window_size.height - cursor_bottom - VERTICAL_PADDING;
        let space_above = editor_bounds.origin.y + line_top - VERTICAL_PADDING;
        // The persisted 430px width is the list's; the 1px borders come on top (432px measured in 1.147.0).
        let default_size = (DEFAULT_WIDTH, status_bar_height + VISIBLE_ITEMS as f32 * item_height);
        let (width, height, above, limits) = if message {
            (DEFAULT_WIDTH / 2. + 2., item_height + 2., false, None)
        } else {
            let (wanted_width, wanted_height) = self.suggest.widget.size.unwrap_or(default_size);
            let max_width = window_size.width - 2. - 2. * HORIZONTAL_PADDING;
            let full = status_bar_height + count as f32 * item_height + 2.;
            let min_height = item_height + status_bar_height + 2.;
            let (max_below, max_above) = (space_below.min(full), space_above.min(full));
            let height = (wanted_height + 2.).max(min_height).min(max_above.max(max_below));
            // `lockPreference` while a sash drags.
            let above = match &self.suggest.widget.resize {
                Some(resize) => resize.above,
                None => height > max_below && max_above > max_below,
            };
            let max_height = if above { max_above } else { max_below }.max(min_height);
            let limits = SizeLimits { max: (max_width, max_height - 2.), min_height: min_height - 2., default: default_size };
            (wanted_width.min(max_width) + 2., height.min(max_height), above, Some(limits))
        };
        let top = if above { line_top - height } else { line_top + LINE_HEIGHT };
        // suggestWidget.ts `beforeRender`: the layout's width adds `horizontalPadding` (14px) to the drawn one.
        let left = horizontal_in_page(left, width + 14., editor_bounds, window_size);
        let high_contrast = self.theme.kind.is_high_contrast();
        let mut widget = div()
            .id("suggest-widget")
            .debug_selector(|| "suggest-widget".into())
            .absolute()
            .left(px(left))
            .top(px(top))
            .w(px(width))
            .h(px(height))
            .flex()
            .flex_col()
            .overflow_hidden()
            .border(px(if high_contrast { 2. } else { 1. }))
            .border_color(self.color("editorSuggestWidget.border"))
            .rounded(px(RADIUS))
            .bg(self.color("editorSuggestWidget.background"))
            .text_color(self.foreground_or("editorSuggestWidget.foreground"))
            .font_family(EDITOR_FONT)
            .text_size(px(EDITOR_FONT_SIZE))
            .line_height(px(item_height))
            .cursor_default()
            .occlude()
            .on_any_mouse_down(|_, _, cx| cx.stop_propagation())
            .when(!high_contrast, |widget| {
                // `box-shadow: 0 2px 8px var(--vscode-widget-shadow)`; GPUI's blur radius is half the CSS blur.
                widget.shadow(vec![BoxShadow { color: self.color("widget.shadow").into(), offset: point(px(0.), px(2.)), blur_radius: px(4.), spread_radius: px(0.), inset: false }])
            });
        if message {
            let text = if state == State::Loading { "Loading..." } else { "No suggestions." };
            widget = widget.flex_row().items_center().child(div().pl(px(22.)).child(text));
        } else {
            widget = widget.child(self.suggest_rows(height - 2. - status_bar_height, status_bar_height > 0., cx));
            if status_bar_height > 0. {
                widget = widget.child(self.suggest_status_bar(item_height, window, cx));
            }
        }
        let mut layer = div().absolute().top_0().left_0().child(widget);
        if let Some(limits) = limits {
            layer = layer.children(self.suggest_sashes(gpui::Bounds { origin: point(left, top), size: gpui::size(width, height) }, above, limits, cx));
        }
        let anchor = gpui::Bounds { origin: gpui::point(left, top), size: gpui::size(width, height) };
        if let Some(details) = self.suggest_details(anchor, above, editor_bounds, window_size, high_contrast, editor, char_width, cx) {
            layer = layer.children(details);
        }
        Some(deferred(layer).with_priority(1).into_any_element())
    }

    /// ResizableHTMLElement's sashes as `_layout` enables them: east and south below the line, north and east above.
    fn suggest_sashes(&self, bounds: gpui::Bounds<f32>, above: bool, limits: SizeLimits, cx: &mut Context<Self>) -> Vec<AnyElement> {
        let gpui::Bounds { origin, size } = bounds;
        let half = SASH_SIZE / 2.;
        let vertical = if above { (true, origin.y - half) } else { (false, origin.y + size.height - half) };
        // [north, east, south] and [left, top, width, height].
        let mut sashes: Vec<([bool; 3], [f32; 4], gpui::CursorStyle)> = vec![([false, true, false], [origin.x + size.width - half, origin.y, SASH_SIZE, size.height], gpui::CursorStyle::ResizeLeftRight)];
        sashes.push(([vertical.0, false, !vertical.0], [origin.x, vertical.1, size.width, SASH_SIZE], gpui::CursorStyle::ResizeUpDown));
        let corner = if above { gpui::CursorStyle::ResizeUpRightDownLeft } else { gpui::CursorStyle::ResizeUpLeftDownRight };
        sashes.push(([vertical.0, true, !vertical.0], [origin.x + size.width - half, vertical.1, SASH_SIZE, SASH_SIZE], corner));
        let dragging = self.suggest.widget.resize.is_some();
        let workbench = cx.entity();
        let mut elements = Vec::new();
        for (index, ([north, east, south], [left, top, width, height], cursor)) in sashes.into_iter().enumerate() {
            let resize = self.suggest.widget.resize.as_ref().filter(|resize| [resize.north, resize.east, resize.south] == [north, east, south]);
            let sash = div()
                .id(("suggest-sash", index))
                .debug_selector(move || format!("suggest-sash-{}{}{}", if north { "n" } else { "" }, if east { "e" } else { "" }, if south { "s" } else { "" }))
                .absolute()
                .left(px(left))
                .top(px(top))
                .w(px(width))
                .h(px(height))
                .cursor(cursor)
                .occlude()
                .children(self.sash_highlight(("suggest-sash", index), (resize.is_some() || self.suggest.widget.hovered_sash == Some(("list", index))) && index < 2, div().absolute().inset_0()))
                .on_hover(self.sash_hover_listener(("list", index), cx))
                .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, _, cx| {
                    cx.stop_propagation();
                    workbench.start_suggest_resize([north, east, south], above, (size.width - 2., size.height - 2.), event.position.map(f32::from), limits, cx);
                }))
                .when(dragging && index == 0, |sash| {
                    let workbench = workbench.clone();
                    sash.child(
                        canvas(
                            |_, _, _| (),
                            move |_, _, window, _| {
                                let moved = workbench.clone();
                                window.on_mouse_event(move |event: &MouseMoveEvent, _, _, cx| {
                                    moved.update(cx, |workbench, cx| workbench.drag_suggest_sash(event.position.map(f32::from), false, cx));
                                });
                                let released = workbench.clone();
                                window.on_mouse_event(move |event: &MouseUpEvent, _, _, cx| {
                                    released.update(cx, |workbench, cx| workbench.drag_suggest_sash(event.position.map(f32::from), true, cx));
                                });
                            },
                        )
                        .size_0(),
                    )
                });
            elements.push(sash.into_any_element());
        }
        elements
    }

    /// `onDidWillResize`: the drag starts from the size as drawn and the persisted one.
    fn start_suggest_resize(&mut self, [north, east, south]: [bool; 3], above: bool, start: (f32, f32), pointer: gpui::Point<f32>, limits: SizeLimits, cx: &mut Context<Self>) {
        let persisted = persisted_size(&self.profile_storage.lock().unwrap());
        self.suggest.widget.size = Some(start);
        self.suggest.widget.resize = Some(Resize { north, east, south, above, pointer, start, persisted, persist_width: false, persist_height: false, limits });
        cx.notify();
    }

    /// `onDidResize`: the size follows the pointer within the limits; on release a width or height that moved more
    /// than half an item is stored, the other keeps its persisted (or default) value.
    fn drag_suggest_sash(&mut self, pointer: gpui::Point<f32>, done: bool, cx: &mut Context<Self>) {
        let Some(resize) = self.suggest.widget.resize.as_mut() else { return };
        let SizeLimits { max, min_height, default } = resize.limits;
        let mut size = resize.start;
        if resize.east {
            size.0 = (resize.start.0 + pointer.x - resize.pointer.x).clamp(MIN_WIDTH, max.0.max(MIN_WIDTH));
        }
        let dy = pointer.y - resize.pointer.y;
        if resize.north || resize.south {
            let height = if resize.north { resize.start.1 - dy } else { resize.start.1 + dy };
            size.1 = height.clamp(min_height, max.1.max(min_height));
        }
        resize.persist_width |= resize.east;
        resize.persist_height |= resize.north || resize.south;
        self.suggest.widget.size = Some(size);
        if done {
            let threshold = (LINE_HEIGHT / 2.).round();
            let fallback = resize.persisted.unwrap_or(default);
            let width = if resize.persist_width && (resize.start.0 - size.0).abs() > threshold { size.0 } else { fallback.0 };
            let height = if resize.persist_height && (resize.start.1 - size.1).abs() > threshold { size.1 } else { fallback.1 };
            self.suggest.widget.resize = None;
            store_size(&mut self.profile_storage.lock().unwrap(), (width, height));
        }
        cx.notify();
    }

    /// `suggestWidgetVisible`'s details: shown with the docs expanded and a focused item that has any.
    pub(super) fn suggest_details_visible(&self) -> bool {
        self.suggest.widget.details && matches!(self.suggest.widget.state, State::Open | State::Frozen) && self.focused_suggestion().is_some_and(CompletionItem::can_expand)
    }

    pub(super) fn focused_suggestion(&self) -> Option<&CompletionItem> {
        self.suggest.widget.focused.and_then(|index| self.suggest_items().get(index))
    }

    /// suggestWidgetDetails.ts: the detail in the editor font and the documentation in a ResizableHTMLElement.
    /// `anchor` is the list in text area coordinates; the details and their sashes come back in the same ones.
    fn suggest_details(&self, anchor: gpui::Bounds<f32>, above: bool, editor_bounds: gpui::Bounds<f32>, window_size: gpui::Size<f32>, high_contrast: bool, editor: &OpenEditor, char_width: f32, cx: &mut Context<Self>) -> Option<Vec<AnyElement>> {
        if !self.suggest_details_visible() {
            return None;
        }
        let item = self.focused_suggestion()?;
        let border = if high_contrast { 2. } else { 1. };
        let measured = self.suggest.widget.details_height.get();
        // `_userSize ?? widget.size`: the content's height, unknown on the frame that first draws it.
        let size = self.suggest.widget.details_size.unwrap_or((DETAILS_WIDTH, measured.unwrap_or(0.)));
        let page_anchor = gpui::Bounds { origin: anchor.origin + editor_bounds.origin, size: anchor.size };
        let placed = place_details(page_anchor, size, !above, border, window_size);
        let (width, height) = placed.size;
        let left = placed.left - editor_bounds.origin.x;
        let top = placed.top - editor_bounds.origin.y;
        let detail = item.detail.as_deref().filter(|detail| !detail.is_empty() && *detail != item.label).map(|detail| detail.chars().take(100_000).collect::<String>());
        let has_docs = !item.documentation.is_null();
        let docs = match &item.documentation {
            Value::String(text) => Some(div().px(px(5.)).py(px(4.)).when(detail.is_none(), |docs| docs.mr(px(24.))).whitespace_normal().child(text.clone())),
            Value::Object(_) => {
                let style = super::markdown_view::MarkdownStyle { font_size: EDITOR_FONT_SIZE, line_height: LINE_HEIGHT, foreground: self.foreground_or("editorSuggestWidget.foreground"), action_handler: None, code_foreground: None, code_background: Some(self.color("textCodeBlock.background")), selectable: false };
                let blocks = crate::markdown::parse(&crate::markdown::MarkdownString::from_value(&item.documentation));
                Some(div().px(px(5.)).py(px(4.)).child(self.markdown_blocks("suggest-details", &blocks, style, &editor.document().language_id, cx)))
            }
            _ => None,
        };
        let close = self.icon("close", LINE_HEIGHT, 14., self.foreground_or("editorSuggestWidget.foreground"));
        // `renderItem`'s `layout(width, type.clientHeight + docs.clientHeight)`: the content's own height, with the borders.
        let details_height = self.suggest.widget.details_height.clone();
        let measure = canvas(
            move |bounds, window, _| {
                let content = f32::from(bounds.size.height) + 2. * border;
                if details_height.get() != Some(content) {
                    details_height.set(Some(content));
                    // `refresh` is a no-op while drawing.
                    window.request_animation_frame();
                }
            },
            |_, _, _, _| (),
        )
        .absolute()
        .inset_0();
        let details = div()
            .id("suggest-details")
            .debug_selector(|| "suggest-details".into())
            .absolute()
            .left(px(left))
            .top(px(top))
            .w(px(width))
            .when(measured.is_some() || self.suggest.widget.details_size.is_some(), |details| details.h(px(height)))
            .when(measured.is_none(), |details| details.opacity(0.))
            .flex()
            .flex_col()
            .overflow_hidden()
            .border(px(border))
            .border_color(self.color("editorSuggestWidget.border"))
            .rounded(px(RADIUS))
            .bg(self.color("editorSuggestWidget.background"))
            .text_color(self.foreground_or("editorSuggestWidget.foreground"))
            .font_family(".SystemUIFont")
            .text_size(px(EDITOR_FONT_SIZE))
            .cursor_default()
            .occlude()
            .on_any_mouse_down(|_, _, cx| cx.stop_propagation())
            .child(self.scrollable("suggest-details-body", None, div().id("suggest-details-body").child(
                div()
                    .relative()
                    .flex_none()
                    .child(measure)
                    .child(div().absolute().top(px(6.)).right(px(2.)).cursor_pointer().child(close).on_mouse_down(MouseButton::Left, cx.listener(|workbench, _, window, cx| {
                        drop(workbench.execute_command("toggleSuggestionDetails", vec![], window, cx));
                    })))
                    .children(detail.map(|detail| {
                        // suggest.css `.type.auto-wrap`: `word-break: break-all` in the monospace editor font, so a line
                        // holds as many characters as fit left of the borders, padding and close button (299px at 330).
                        let columns = ((width - 2. * border - 5. - 24.) / char_width).floor().max(1.) as usize;
                        let lines = break_all(&detail, columns).into_iter().map(|line| div().whitespace_nowrap().child(line));
                        div().font_family(EDITOR_FONT).opacity(0.7).mr(px(24.)).pl(px(5.)).pt(px(4.)).pb(px(if has_docs { 12. } else { 4. })).children(lines)
                    }))
                    .children(docs),
            ), cx).flex_1());
        let bounds = gpui::Bounds { origin: point(left, top), size: gpui::size(width, height) };
        let mut elements = vec![details.into_any_element()];
        elements.extend(self.details_sashes(bounds, placed.sashes, placed.min, placed.max, cx));
        Some(elements)
    }

    /// The sashes `enableSashes` turned on, each moving one edge (`onDidResize`); north and west keep the other edge
    /// in place as the placement draws from the size.
    fn details_sashes(&self, bounds: gpui::Bounds<f32>, enabled: [bool; 4], min: (f32, f32), max: (f32, f32), cx: &mut Context<Self>) -> Vec<AnyElement> {
        let gpui::Bounds { origin, size } = bounds;
        let half = SASH_SIZE / 2.;
        let edges = [
            ("n", [origin.x, origin.y - half, size.width, SASH_SIZE], gpui::CursorStyle::ResizeUpDown),
            ("e", [origin.x + size.width - half, origin.y, SASH_SIZE, size.height], gpui::CursorStyle::ResizeLeftRight),
            ("s", [origin.x, origin.y + size.height - half, size.width, SASH_SIZE], gpui::CursorStyle::ResizeUpDown),
            ("w", [origin.x - half, origin.y, SASH_SIZE, size.height], gpui::CursorStyle::ResizeLeftRight),
        ];
        let dragging = self.suggest.widget.details_resize.as_ref().map(|resize| resize.edge);
        let workbench = cx.entity();
        let mut elements = Vec::new();
        for (edge, (name, [left, top, width, height], cursor)) in edges.into_iter().enumerate() {
            if !enabled[edge] {
                continue;
            }
            let sash = div()
                .id(("suggest-details-sash", edge))
                .debug_selector(move || format!("suggest-details-sash-{name}"))
                .absolute()
                .left(px(left))
                .top(px(top))
                .w(px(width))
                .h(px(height))
                .cursor(cursor)
                .occlude()
                .children(self.sash_highlight(("suggest-details-sash", edge), dragging == Some(edge) || self.suggest.widget.hovered_sash == Some(("details", edge)), div().absolute().inset_0()))
                .on_hover(self.sash_hover_listener(("details", edge), cx))
                .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, _, cx| {
                    cx.stop_propagation();
                    let pointer = event.position.map(f32::from);
                    workbench.suggest.widget.details_resize = Some(DetailsResize { edge, pointer, start: (size.width, size.height), min, max });
                    cx.notify();
                }))
                .when(dragging == Some(edge), |sash| {
                    let workbench = workbench.clone();
                    sash.child(
                        canvas(
                            |_, _, _| (),
                            move |_, _, window, _| {
                                let moved = workbench.clone();
                                window.on_mouse_event(move |event: &MouseMoveEvent, _, _, cx| {
                                    moved.update(cx, |workbench, cx| workbench.drag_details_sash(event.position.map(f32::from), false, cx));
                                });
                                let released = workbench.clone();
                                window.on_mouse_event(move |event: &MouseUpEvent, _, _, cx| {
                                    released.update(cx, |workbench, cx| workbench.drag_details_sash(event.position.map(f32::from), true, cx));
                                });
                            },
                        )
                        .size_0(),
                    )
                });
            elements.push(sash.into_any_element());
        }
        elements
    }

    /// sash.ts `onMouseEnter`: the `hover` class, and its `sash.hoverBorder`, after `workbench.sash.hoverDelay`.
    fn sash_hover_listener(&self, key: (&'static str, usize), cx: &mut Context<Self>) -> impl Fn(&bool, &mut Window, &mut gpui::App) + 'static {
        cx.listener(move |workbench, hovered: &bool, window, cx| {
            let widget = &mut workbench.suggest.widget;
            if !*hovered {
                if widget.hovered_sash == Some(key) {
                    widget.hovered_sash = None;
                }
                widget.sash_hover = None;
                cx.notify();
                return;
            }
            let delay = workbench.sash_hover_delay();
            workbench.suggest.widget.sash_hover = Some(cx.spawn_in(window, async move |workbench, cx| {
                cx.background_executor().timer(delay).await;
                let _ = workbench.update(cx, |workbench, cx| {
                    workbench.suggest.widget.hovered_sash = Some(key);
                    cx.notify();
                });
            }));
        })
    }

    /// `ResizableHTMLElement.layout` clamps to the limits of the drag's start; on release the size is `_userSize`.
    fn drag_details_sash(&mut self, pointer: gpui::Point<f32>, done: bool, cx: &mut Context<Self>) {
        let Some(resize) = self.suggest.widget.details_resize.as_ref() else { return };
        let (dx, dy) = (pointer.x - resize.pointer.x, pointer.y - resize.pointer.y);
        let (mut width, mut height) = resize.start;
        match resize.edge {
            0 => height -= dy,
            1 => width += dx,
            2 => height += dy,
            _ => width -= dx,
        }
        let size = (width.min(resize.max.0).max(resize.min.0), height.min(resize.max.1).max(resize.min.1));
        self.suggest.widget.details_size = Some(size);
        if done {
            self.suggest.widget.details_resize = None;
        }
        cx.notify();
    }

    /// suggestWidgetStatus.ts: the `suggestWidgetStatusbarMenu` actions, group `left` on the left and the rest on the
    /// right, as `TextOnlyMenuEntryActionViewItem`s: `title (keybinding)` with Enter as ⏎, joined by commas.
    fn suggest_status_bar(&self, height: f32, window: &Window, cx: &mut Context<Self>) -> Div {
        let context = self.key_context(window);
        let bar = |left: bool, cx: &mut Context<Self>| {
            let actions = menu_group_actions(&self.menus, MenuId::SuggestWidgetStatusBar, &context, |group| (group == "left") == left);
            let mut commands = Vec::new();
            for action in actions {
                if let MenuAction::Command { id, title, .. } = action {
                    let keybinding = self.keybindings.resolver.lookup_primary_keybinding(&id, &context).map(|item| keybindings::label(&item.keybinding));
                    let label = match keybinding {
                        Some(keybinding) => format!("{title} ({})", enter_and_escape_symbols(&keybinding)),
                        None => title,
                    };
                    commands.push((id, label));
                }
            }
            let count = commands.len();
            let items = commands.into_iter().enumerate().map(|(index, (id, label))| {
                let label = if index + 1 < count { format!("{label},") } else { label };
                div().id(SharedString::from(format!("suggest-status-{id}-{index}"))).when(index + 1 < count, |item| item.mr(px(EDITOR_FONT_SIZE * 0.8 * 0.3))).cursor_pointer().child(label).on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _, window, cx| {
                    cx.stop_propagation();
                    drop(workbench.execute_command(&id, vec![], window, cx));
                }))
            });
            div().flex().items_center().when(left, |bar| bar.pr(px(8.))).children(items)
        };
        let (left, right) = (bar(true, cx), bar(false, cx));
        div()
            .debug_selector(|| "suggest-status-bar".into())
            .flex()
            .flex_none()
            .justify_between()
            .items_center()
            .w_full()
            .h(px(height))
            .px(px(4.))
            .overflow_hidden()
            .whitespace_nowrap()
            .text_size(px(EDITOR_FONT_SIZE * 0.8))
            .border_t_1()
            .border_color(self.color("editorSuggestWidget.border"))
            .text_color(self.color("editorSuggestWidgetStatus.foreground"))
            .child(left)
            .child(right)
    }

    fn suggest_rows(&self, height: f32, with_status_bar: bool, cx: &mut Context<Self>) -> impl IntoElement {
        let visible = ((height / LINE_HEIGHT).floor() as usize).max(1);
        let (top, focused) = (self.suggest.widget.top, self.suggest.widget.focused);
        let frozen = self.suggest_widget_frozen();
        let items: Vec<CompletionItem> = self.suggest_items().iter().skip(top).take(visible).cloned().collect();
        let list_bounds = self.suggest.widget.list_bounds.clone();
        // The list's scroll layer is laid out from these bounds: new ones draw again.
        let measure = canvas(
            move |bounds, window, cx| {
                if list_bounds.replace(bounds) != bounds {
                    super::part_view::redraw_after_frame(window, cx);
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .size_full();
        let mut list = div()
            .id("suggest-list")
            .relative()
            .flex()
            .flex_col()
            .size_full()
            .child(measure);
        let shown = items.len();
        for (offset, item) in items.into_iter().enumerate() {
            let index = top + offset;
            let row = self.suggest_row(&item, index, focused == Some(index), frozen, cx);
            // roundedCorners.css: rows are 4px; suggestWidget.css clips the list to the widget's 8px inner corners, which
            // GPUI cannot, so the first and last rows take them; the last row keeps 4px above the status bar.
            list = list.child(row.rounded(px(4.)).when(offset == 0, |row| row.rounded_t(px(RADIUS))).when(offset + 1 == shown && !with_status_bar, |row| row.rounded_b(px(RADIUS))));
        }
        list.child(self.list_scroll_layer(super::list_scroll::ListId::Suggest, cx))
    }

    pub(super) fn suggest_list_scroller(&self) -> super::list_scroll::ListScroller {
        let bounds = self.suggest.widget.list_bounds.get();
        let max = self.suggest_items().len() as f32 * LINE_HEIGHT - f32::from(bounds.size.height);
        super::list_scroll::ListScroller::Placed { bounds, top: self.suggest.widget.top as f32 * LINE_HEIGHT, max }
    }

    /// shortcut: the rows move whole, where listView.ts scrolls by the pixel; draw a partial top row to upgrade.
    pub(super) fn set_suggest_scroll_top(&mut self, top: f32) {
        self.suggest.widget.top = (top / LINE_HEIGHT).round() as usize;
    }

    /// suggestWidgetRenderer.ts `renderElement`.
    fn suggest_row(&self, item: &CompletionItem, index: usize, focused: bool, frozen: bool, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let foreground = if focused { self.foreground_or("editorSuggestWidget.selectedForeground") } else { self.foreground_or("editorSuggestWidget.foreground") };
        let (codicon, icon_color) = completion_kind_icon(item.kind);
        let icon_color = match (focused, icon_color) {
            (true, _) => self.theme.color("editorSuggestWidget.selectedIconForeground").unwrap_or(foreground),
            (false, Some(key)) => self.foreground_or(key),
            (false, None) => foreground,
        };
        let highlight = if focused { self.color("editorSuggestWidget.focusHighlightForeground") } else { self.color("editorSuggestWidget.highlightForeground") };
        let matches = if item.deprecated { Vec::new() } else { create_matches(Some(&item.score)) };
        let label = item.label.replace(['\r', '\n'], "");
        let mut styles = Vec::new();
        for range in matches {
            let start = label.char_indices().nth(range.start).map_or(label.len(), |(offset, _)| offset);
            let end = label.char_indices().nth(range.end).map_or(label.len(), |(offset, _)| offset);
            styles.push((start..end, HighlightStyle { color: Some(highlight.into()), font_weight: (!frozen).then_some(FontWeight::BOLD), ..Default::default() }));
        }
        let (signature, details) = match item.string_label {
            true => (None, item.detail.clone()),
            false => (item.label_detail.clone(), item.label_description.clone()),
        };
        let show_details = !item.string_label || (focused && !self.suggest_details_visible());
        let label = div().flex_none().when(item.deprecated, |label| label.opacity(0.66).line_through()).child(StyledText::new(label).with_highlights(styles));
        let left = div()
            .flex()
            .flex_grow(1.)
            .flex_shrink(1.)
            .overflow_hidden()
            .child(div().flex().items_center().mr(px(4.)).child(self.icon(codicon, 16., 16., icon_color)))
            .child(label)
            .children(signature.map(|signature| div().overflow_hidden().text_ellipsis().opacity(0.6).child(signature.replace(['\r', '\n'], ""))));
        let right = div()
            .flex()
            .flex_shrink(4.)
            .max_w(gpui::relative(0.7))
            .overflow_hidden()
            .children(details.filter(|_| show_details).map(|details| div().ml(px(EDITOR_FONT_SIZE * 0.85 * 1.1)).text_size(px(EDITOR_FONT_SIZE * 0.85)).overflow_hidden().text_ellipsis().whitespace_nowrap().text_color(foreground).child(details.replace(['\r', '\n'], ""))));
        div()
            .id(("suggest-row", index))
            .flex()
            .flex_none()
            .h(px(LINE_HEIGHT))
            .pr(px(10.))
            .whitespace_nowrap()
            .cursor_pointer()
            .text_color(foreground)
            .when(focused, |row| {
                let outline = self.theme.color("editorSuggestWidget.focusOutline");
                row.bg(self.color("editorSuggestWidget.selectedBackground")).when_some(outline, |row, outline| row.border_1().border_color(outline))
            })
            .when(!focused, |row| row.hover(|row| row.bg(self.color("list.hoverBackground"))))
            .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _, window, cx| {
                // `onDidSelect` of a click: the item is focused and inserted.
                workbench.focus_suggestion(Some(index), cx);
                workbench.insert_suggestion(index, InsertFlags::default(), window, cx);
            }))
            .child(div().flex_1().h_full().overflow_hidden().pl(px(2.)).child(div().flex().justify_between().overflow_hidden().child(left).child(right)))
    }
}

/// suggestWidgetDetails.ts `auto-wrap`: a detail without indented lines is laid out as `white-space: normal` with
/// `word-break: break-all` (runs of whitespace collapse, lines break after `columns` characters); one with them keeps
/// its lines as `pre-wrap`.
/// Where `_placeAtAnchor` puts the details, in page coordinates, with the sashes it enables (north, east, south, west).
struct DetailsPlacement {
    left: f32,
    top: f32,
    size: (f32, f32),
    sashes: [bool; 4],
    min: (f32, f32),
    max: (f32, f32),
}

/// One of `_placeAtAnchor`'s `Placement`s.
#[derive(Clone, Copy)]
struct Candidate {
    side: Side,
    top: f32,
    left: f32,
    fit: f32,
    max_top: (f32, f32),
    max_bottom: (f32, f32),
    min: (f32, f32),
}

#[derive(Clone, Copy, PartialEq)]
enum Side {
    East,
    West,
    South,
    North,
}

/// `_placeAtAnchor`: east, west, then south (north when the list is above the line, `prefer_align_at_top` false),
/// the first that fits or else the least bad; beside the list the details hang from its top or, when that leaves too
/// little room, rise from its bottom.
fn place_details(anchor: gpui::Bounds<f32>, size: (f32, f32), prefer_align_at_top: bool, border: f32, body: gpui::Size<f32>) -> DetailsPlacement {
    let border_height = 2. * border;
    let (anchor_left, anchor_top, anchor_width, anchor_height) = (anchor.origin.x, anchor.origin.y, anchor.size.width, anchor.size.height);
    let min_height = 2. * LINE_HEIGHT;
    let beside = |side: Side, width: f32, left: f32| Candidate {
        side,
        top: anchor_top,
        left,
        fit: width - size.0,
        max_top: (width, body.height - anchor_top - border_height - VERTICAL_PADDING),
        max_bottom: (width, anchor_top + anchor_height - border_height - VERTICAL_PADDING),
        min: (width.min(MIN_WIDTH), min_height),
    };
    let east_width = body.width - (anchor_left + anchor_width + border + HORIZONTAL_PADDING);
    let east = beside(Side::East, east_width, -border + anchor_left + anchor_width);
    let west_width = anchor_left - border - HORIZONTAL_PADDING;
    let west = beside(Side::West, west_width, HORIZONTAL_PADDING.max(anchor_left - size.0 - border));
    let vertical = if prefer_align_at_top {
        let max = (anchor_width - border_height, body.height - anchor_top - anchor_height - VERTICAL_PADDING);
        Candidate { side: Side::South, top: -border + anchor_top + anchor_height, left: anchor_left, fit: max.1 - size.1, max_top: max, max_bottom: max, min: (max.0, min_height) }
    } else {
        let max = (anchor_width - border_height, anchor_top - VERTICAL_PADDING);
        Candidate { side: Side::North, top: VERTICAL_PADDING.max(anchor_top - size.1), left: anchor_left, fit: max.1 - size.1, max_top: max, max_bottom: max, min: (max.0, min_height) }
    };
    let placements = [east, west, vertical];
    let mut placement = placements[0];
    match placements.iter().find(|placement| placement.fit >= 0.) {
        Some(fitting) => placement = *fitting,
        None => {
            for candidate in placements {
                if candidate.fit > placement.fit {
                    placement = candidate;
                }
            }
        }
    }
    let Candidate { side, mut top, left, max_top, max_bottom, min, .. } = placement;
    let bottom = anchor_top + anchor_height - border_height;
    let height = size.1.min(max_top.1.max(max_bottom.1));
    let align_at_top = if prefer_align_at_top { height <= max_top.1 } else { height > max_bottom.1 };
    let max = if align_at_top { max_top } else { max_bottom };
    if side == Side::North {
        top = anchor_top - height + border;
    } else if !align_at_top && height > anchor_height {
        top = bottom - height;
    }
    let sashes = if side == Side::North { [true, false, false, true] } else { [!align_at_top, side == Side::East, align_at_top, side != Side::East] };
    // `ResizableHTMLElement.layout`: `max(min, min(max, value))`.
    let width = min.0.max(max.0.min(size.0));
    let height = min.1.max(max.1.min(height));
    DetailsPlacement { left, top, size: (width, height), sashes, min, max }
}

/// `PersistedWidgetSize.restore`: a stored `{ width, height }`.
fn persisted_size(storage: &storage::Storage) -> Option<(f32, f32)> {
    let value: Value = serde_json::from_str(storage.get(SIZE_KEY)?).ok()?;
    Some((value["width"].as_f64()? as f32, value["height"].as_f64()? as f32))
}

fn store_size(storage: &mut storage::Storage, (width, height): (f32, f32)) {
    storage.set(SIZE_KEY, json!({ "width": width, "height": height }).to_string());
}

/// `TextOnlyMenuEntryActionViewItem._symbolPrintEnter`.
fn enter_and_escape_symbols(keybinding: &str) -> String {
    static ENTER: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| regex::Regex::new(r"(?i)\benter\b").unwrap());
    static ESCAPE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| regex::Regex::new(r"(?i)\bEscape\b").unwrap());
    ESCAPE.replace_all(&ENTER.replace_all(keybinding, "\u{23CE}"), "Esc").into_owned()
}

fn break_all(detail: &str, columns: usize) -> Vec<String> {
    let lines: Vec<&str> = detail.split('\n').map(|line| line.strip_suffix('\r').unwrap_or(line)).collect();
    if lines.iter().skip(1).any(|line| line.starts_with(char::is_whitespace)) {
        return lines.into_iter().map(String::from).collect();
    }
    let collapsed = detail.split_whitespace().collect::<Vec<_>>().join(" ");
    let mut result = Vec::new();
    let mut line = String::new();
    for character in collapsed.chars() {
        if line.chars().count() == columns {
            result.push(std::mem::take(&mut line));
            if character == ' ' {
                continue;
            }
        }
        line.push(character);
    }
    result.push(line);
    result
}

#[cfg(test)]
mod tests;