Merge branch 'main' into chat-again
This commit is contained in:
@@ -16,8 +16,8 @@ use workspace::{item::ItemHandle, StatusItemView, Workspace};
|
||||
|
||||
actions!(lsp_status, [ShowErrorMessage]);
|
||||
|
||||
const DOWNLOAD_ICON: &str = "icons/download_12.svg";
|
||||
const WARNING_ICON: &str = "icons/triangle_exclamation_12.svg";
|
||||
const DOWNLOAD_ICON: &str = "icons/download.svg";
|
||||
const WARNING_ICON: &str = "icons/warning.svg";
|
||||
|
||||
pub enum Event {
|
||||
ShowError { lsp_name: Arc<str>, error: String },
|
||||
|
||||
@@ -386,10 +386,12 @@ impl AssistantPanel {
|
||||
);
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.finish_inline_assist(inline_assist_id, false, cx);
|
||||
this.finish_inline_assist(inline_assist_id, false, cx);
|
||||
}
|
||||
} else {
|
||||
this.finish_inline_assist(inline_assist_id, false, cx);
|
||||
}
|
||||
}
|
||||
}),
|
||||
],
|
||||
@@ -702,7 +704,7 @@ impl AssistantPanel {
|
||||
}
|
||||
|
||||
if foreground_ranges.is_empty() {
|
||||
editor.clear_text_highlights::<PendingInlineAssist>(cx);
|
||||
editor.clear_highlights::<PendingInlineAssist>(cx);
|
||||
} else {
|
||||
editor.highlight_text::<PendingInlineAssist>(
|
||||
foreground_ranges,
|
||||
@@ -2374,7 +2376,7 @@ impl ConversationEditor {
|
||||
.with_children(
|
||||
if let MessageStatus::Error(error) = &message.status {
|
||||
Some(
|
||||
Svg::new("icons/circle_x_mark_12.svg")
|
||||
Svg::new("icons/error.svg")
|
||||
.with_color(style.error_icon.color)
|
||||
.constrained()
|
||||
.with_width(style.error_icon.width)
|
||||
@@ -2702,7 +2704,7 @@ impl View for InlineAssistant {
|
||||
)
|
||||
.with_children(if let Some(error) = self.codegen.read(cx).error() {
|
||||
Some(
|
||||
Svg::new("icons/circle_x_mark_12.svg")
|
||||
Svg::new("icons/error.svg")
|
||||
.with_color(theme.assistant.error_icon.color)
|
||||
.constrained()
|
||||
.with_width(theme.assistant.error_icon.width)
|
||||
@@ -2837,6 +2839,7 @@ impl InlineAssistant {
|
||||
cx,
|
||||
);
|
||||
} else {
|
||||
self.confirmed = false;
|
||||
editor.set_read_only(false);
|
||||
editor.set_field_editor_style(
|
||||
Some(Arc::new(|theme| theme.assistant.inline.editor.clone())),
|
||||
|
||||
@@ -50,7 +50,7 @@ impl View for UpdateNotification {
|
||||
.with_child(
|
||||
MouseEventHandler::new::<Cancel, _>(0, cx, |state, _| {
|
||||
let style = theme.dismiss_button.style_for(state);
|
||||
Svg::new("icons/x_mark_8.svg")
|
||||
Svg::new("icons/x.svg")
|
||||
.with_color(style.color)
|
||||
.constrained()
|
||||
.with_width(style.icon_width)
|
||||
|
||||
@@ -1243,7 +1243,7 @@ impl CollabPanel {
|
||||
.collab_panel
|
||||
.add_contact_button
|
||||
.style_for(is_selected, state),
|
||||
"icons/plus_16.svg",
|
||||
"icons/plus.svg",
|
||||
)
|
||||
})
|
||||
.with_cursor_style(CursorStyle::PointingHand)
|
||||
@@ -1687,7 +1687,7 @@ impl CollabPanel {
|
||||
cx.font_cache(),
|
||||
))
|
||||
.with_child(
|
||||
Svg::new("icons/radix/file.svg")
|
||||
Svg::new("icons/file.svg")
|
||||
.with_color(theme.channel_hash.color)
|
||||
.constrained()
|
||||
.with_width(theme.channel_hash.width)
|
||||
|
||||
@@ -211,7 +211,7 @@ impl PickerDelegate for ContactFinderDelegate {
|
||||
ContactRequestStatus::None | ContactRequestStatus::RequestReceived => {
|
||||
Some("icons/check_8.svg")
|
||||
}
|
||||
ContactRequestStatus::RequestSent => Some("icons/x_mark_8.svg"),
|
||||
ContactRequestStatus::RequestSent => Some("icons/x.svg"),
|
||||
ContactRequestStatus::RequestAccepted => None,
|
||||
};
|
||||
let button_style = if self.user_store.read(cx).is_contact_request_pending(user) {
|
||||
|
||||
@@ -483,10 +483,10 @@ impl CollabTitlebarItem {
|
||||
let icon;
|
||||
let tooltip;
|
||||
if room.read(cx).is_screen_sharing() {
|
||||
icon = "icons/radix/desktop.svg";
|
||||
icon = "icons/desktop.svg";
|
||||
tooltip = "Stop Sharing Screen"
|
||||
} else {
|
||||
icon = "icons/radix/desktop.svg";
|
||||
icon = "icons/desktop.svg";
|
||||
tooltip = "Share Screen";
|
||||
}
|
||||
|
||||
@@ -533,10 +533,10 @@ impl CollabTitlebarItem {
|
||||
let tooltip;
|
||||
let is_muted = room.read(cx).is_muted(cx);
|
||||
if is_muted {
|
||||
icon = "icons/radix/mic-mute.svg";
|
||||
icon = "icons/mic-mute.svg";
|
||||
tooltip = "Unmute microphone";
|
||||
} else {
|
||||
icon = "icons/radix/mic.svg";
|
||||
icon = "icons/mic.svg";
|
||||
tooltip = "Mute microphone";
|
||||
}
|
||||
|
||||
@@ -586,10 +586,10 @@ impl CollabTitlebarItem {
|
||||
let tooltip;
|
||||
let is_deafened = room.read(cx).is_deafened().unwrap_or(false);
|
||||
if is_deafened {
|
||||
icon = "icons/radix/speaker-off.svg";
|
||||
icon = "icons/speaker-off.svg";
|
||||
tooltip = "Unmute speakers";
|
||||
} else {
|
||||
icon = "icons/radix/speaker-loud.svg";
|
||||
icon = "icons/speaker-loud.svg";
|
||||
tooltip = "Mute speakers";
|
||||
}
|
||||
|
||||
@@ -625,7 +625,7 @@ impl CollabTitlebarItem {
|
||||
.into_any()
|
||||
}
|
||||
fn render_leave_call(&self, theme: &Theme, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
|
||||
let icon = "icons/radix/exit.svg";
|
||||
let icon = "icons/exit.svg";
|
||||
let tooltip = "Leave call";
|
||||
|
||||
let titlebar = &theme.titlebar;
|
||||
@@ -748,7 +748,7 @@ impl CollabTitlebarItem {
|
||||
|
||||
dropdown
|
||||
.with_child(
|
||||
Svg::new("icons/caret_down_8.svg")
|
||||
Svg::new("icons/caret_down.svg")
|
||||
.with_color(user_menu_button_style.icon.color)
|
||||
.constrained()
|
||||
.with_width(user_menu_button_style.icon.width)
|
||||
@@ -1116,7 +1116,7 @@ impl CollabTitlebarItem {
|
||||
| client::Status::Reauthenticating { .. }
|
||||
| client::Status::Reconnecting { .. }
|
||||
| client::Status::ReconnectionError { .. } => Some(
|
||||
Svg::new("icons/cloud_slash_12.svg")
|
||||
Svg::new("icons/disconnected.svg")
|
||||
.with_color(theme.titlebar.offline_icon.color)
|
||||
.constrained()
|
||||
.with_width(theme.titlebar.offline_icon.width)
|
||||
|
||||
@@ -53,7 +53,7 @@ where
|
||||
.with_child(
|
||||
MouseEventHandler::new::<Dismiss, _>(user.id as usize, cx, |state, _| {
|
||||
let style = theme.dismiss_button.style_for(state);
|
||||
Svg::new("icons/x_mark_8.svg")
|
||||
Svg::new("icons/x.svg")
|
||||
.with_color(style.color)
|
||||
.constrained()
|
||||
.with_width(style.icon_width)
|
||||
|
||||
@@ -78,15 +78,15 @@ impl View for CopilotButton {
|
||||
.with_child(
|
||||
Svg::new({
|
||||
match status {
|
||||
Status::Error(_) => "icons/copilot_error_16.svg",
|
||||
Status::Error(_) => "icons/copilot_error.svg",
|
||||
Status::Authorized => {
|
||||
if enabled {
|
||||
"icons/copilot_16.svg"
|
||||
"icons/copilot.svg"
|
||||
} else {
|
||||
"icons/copilot_disabled_16.svg"
|
||||
"icons/copilot_disabled.svg"
|
||||
}
|
||||
}
|
||||
_ => "icons/copilot_init_16.svg",
|
||||
_ => "icons/copilot_init.svg",
|
||||
}
|
||||
})
|
||||
.with_color(style.icon_color)
|
||||
|
||||
@@ -686,11 +686,9 @@ fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
|
||||
let font_size = (style.text_scale_factor * settings.buffer_font_size(cx)).round();
|
||||
let icon_width = cx.em_width * style.icon_width_factor;
|
||||
let icon = if diagnostic.severity == DiagnosticSeverity::ERROR {
|
||||
Svg::new("icons/circle_x_mark_12.svg")
|
||||
.with_color(theme.error_diagnostic.message.text.color)
|
||||
Svg::new("icons/error.svg").with_color(theme.error_diagnostic.message.text.color)
|
||||
} else {
|
||||
Svg::new("icons/triangle_exclamation_12.svg")
|
||||
.with_color(theme.warning_diagnostic.message.text.color)
|
||||
Svg::new("icons/warning.svg").with_color(theme.warning_diagnostic.message.text.color)
|
||||
};
|
||||
|
||||
Flex::row()
|
||||
@@ -748,7 +746,7 @@ pub(crate) fn render_summary<T: 'static>(
|
||||
let summary_spacing = theme.tab_summary_spacing;
|
||||
Flex::row()
|
||||
.with_child(
|
||||
Svg::new("icons/circle_x_mark_12.svg")
|
||||
Svg::new("icons/error.svg")
|
||||
.with_color(text_style.color)
|
||||
.constrained()
|
||||
.with_width(icon_width)
|
||||
@@ -767,7 +765,7 @@ pub(crate) fn render_summary<T: 'static>(
|
||||
.aligned(),
|
||||
)
|
||||
.with_child(
|
||||
Svg::new("icons/triangle_exclamation_12.svg")
|
||||
Svg::new("icons/warning.svg")
|
||||
.with_color(text_style.color)
|
||||
.constrained()
|
||||
.with_width(icon_width)
|
||||
|
||||
@@ -5,11 +5,11 @@ mod tab_map;
|
||||
mod wrap_map;
|
||||
|
||||
use crate::{
|
||||
link_go_to_definition::{DocumentRange, InlayRange},
|
||||
Anchor, AnchorRangeExt, InlayId, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,
|
||||
link_go_to_definition::InlayHighlight, Anchor, AnchorRangeExt, InlayId, MultiBuffer,
|
||||
MultiBufferSnapshot, ToOffset, ToPoint,
|
||||
};
|
||||
pub use block_map::{BlockMap, BlockPoint};
|
||||
use collections::{HashMap, HashSet};
|
||||
use collections::{BTreeMap, HashMap, HashSet};
|
||||
use fold_map::FoldMap;
|
||||
use gpui::{
|
||||
color::Color,
|
||||
@@ -43,7 +43,8 @@ pub trait ToDisplayPoint {
|
||||
fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
|
||||
}
|
||||
|
||||
type TextHighlights = TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<DocumentRange>)>>;
|
||||
type TextHighlights = TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>;
|
||||
type InlayHighlights = BTreeMap<TypeId, HashMap<InlayId, (HighlightStyle, InlayHighlight)>>;
|
||||
|
||||
pub struct DisplayMap {
|
||||
buffer: ModelHandle<MultiBuffer>,
|
||||
@@ -54,6 +55,7 @@ pub struct DisplayMap {
|
||||
wrap_map: ModelHandle<WrapMap>,
|
||||
block_map: BlockMap,
|
||||
text_highlights: TextHighlights,
|
||||
inlay_highlights: InlayHighlights,
|
||||
pub clip_at_line_ends: bool,
|
||||
}
|
||||
|
||||
@@ -89,6 +91,7 @@ impl DisplayMap {
|
||||
wrap_map,
|
||||
block_map,
|
||||
text_highlights: Default::default(),
|
||||
inlay_highlights: Default::default(),
|
||||
clip_at_line_ends: false,
|
||||
}
|
||||
}
|
||||
@@ -113,6 +116,7 @@ impl DisplayMap {
|
||||
wrap_snapshot,
|
||||
block_snapshot,
|
||||
text_highlights: self.text_highlights.clone(),
|
||||
inlay_highlights: self.inlay_highlights.clone(),
|
||||
clip_at_line_ends: self.clip_at_line_ends,
|
||||
}
|
||||
}
|
||||
@@ -215,37 +219,32 @@ impl DisplayMap {
|
||||
ranges: Vec<Range<Anchor>>,
|
||||
style: HighlightStyle,
|
||||
) {
|
||||
self.text_highlights.insert(
|
||||
Some(type_id),
|
||||
Arc::new((style, ranges.into_iter().map(DocumentRange::Text).collect())),
|
||||
);
|
||||
self.text_highlights
|
||||
.insert(Some(type_id), Arc::new((style, ranges)));
|
||||
}
|
||||
|
||||
pub fn highlight_inlays(
|
||||
&mut self,
|
||||
type_id: TypeId,
|
||||
ranges: Vec<InlayRange>,
|
||||
highlights: Vec<InlayHighlight>,
|
||||
style: HighlightStyle,
|
||||
) {
|
||||
self.text_highlights.insert(
|
||||
Some(type_id),
|
||||
Arc::new((
|
||||
style,
|
||||
ranges.into_iter().map(DocumentRange::Inlay).collect(),
|
||||
)),
|
||||
);
|
||||
for highlight in highlights {
|
||||
self.inlay_highlights
|
||||
.entry(type_id)
|
||||
.or_default()
|
||||
.insert(highlight.inlay, (style, highlight));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text_highlights(&self, type_id: TypeId) -> Option<(HighlightStyle, &[DocumentRange])> {
|
||||
pub fn text_highlights(&self, type_id: TypeId) -> Option<(HighlightStyle, &[Range<Anchor>])> {
|
||||
let highlights = self.text_highlights.get(&Some(type_id))?;
|
||||
Some((highlights.0, &highlights.1))
|
||||
}
|
||||
|
||||
pub fn clear_text_highlights(
|
||||
&mut self,
|
||||
type_id: TypeId,
|
||||
) -> Option<Arc<(HighlightStyle, Vec<DocumentRange>)>> {
|
||||
self.text_highlights.remove(&Some(type_id))
|
||||
pub fn clear_highlights(&mut self, type_id: TypeId) -> bool {
|
||||
let mut cleared = self.text_highlights.remove(&Some(type_id)).is_some();
|
||||
cleared |= self.inlay_highlights.remove(&type_id).is_none();
|
||||
cleared
|
||||
}
|
||||
|
||||
pub fn set_font(&self, font_id: FontId, font_size: f32, cx: &mut ModelContext<Self>) -> bool {
|
||||
@@ -309,6 +308,14 @@ impl DisplayMap {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Highlights<'a> {
|
||||
pub text_highlights: Option<&'a TextHighlights>,
|
||||
pub inlay_highlights: Option<&'a InlayHighlights>,
|
||||
pub inlay_highlight_style: Option<HighlightStyle>,
|
||||
pub suggestion_highlight_style: Option<HighlightStyle>,
|
||||
}
|
||||
|
||||
pub struct DisplaySnapshot {
|
||||
pub buffer_snapshot: MultiBufferSnapshot,
|
||||
pub fold_snapshot: fold_map::FoldSnapshot,
|
||||
@@ -317,6 +324,7 @@ pub struct DisplaySnapshot {
|
||||
wrap_snapshot: wrap_map::WrapSnapshot,
|
||||
block_snapshot: block_map::BlockSnapshot,
|
||||
text_highlights: TextHighlights,
|
||||
inlay_highlights: InlayHighlights,
|
||||
clip_at_line_ends: bool,
|
||||
}
|
||||
|
||||
@@ -422,15 +430,6 @@ impl DisplaySnapshot {
|
||||
.to_inlay_offset(anchor.to_offset(&self.buffer_snapshot))
|
||||
}
|
||||
|
||||
pub fn inlay_offset_to_display_point(&self, offset: InlayOffset, bias: Bias) -> DisplayPoint {
|
||||
let inlay_point = self.inlay_snapshot.to_point(offset);
|
||||
let fold_point = self.fold_snapshot.to_fold_point(inlay_point, bias);
|
||||
let tab_point = self.tab_snapshot.to_tab_point(fold_point);
|
||||
let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
|
||||
let block_point = self.block_snapshot.to_block_point(wrap_point);
|
||||
DisplayPoint(block_point)
|
||||
}
|
||||
|
||||
fn display_point_to_inlay_point(&self, point: DisplayPoint, bias: Bias) -> InlayPoint {
|
||||
let block_point = point.0;
|
||||
let wrap_point = self.block_snapshot.to_wrap_point(block_point);
|
||||
@@ -463,9 +462,7 @@ impl DisplaySnapshot {
|
||||
.chunks(
|
||||
display_row..self.max_point().row() + 1,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Highlights::default(),
|
||||
)
|
||||
.map(|h| h.text)
|
||||
}
|
||||
@@ -474,7 +471,7 @@ impl DisplaySnapshot {
|
||||
pub fn reverse_text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
|
||||
(0..=display_row).into_iter().rev().flat_map(|row| {
|
||||
self.block_snapshot
|
||||
.chunks(row..row + 1, false, None, None, None)
|
||||
.chunks(row..row + 1, false, Highlights::default())
|
||||
.map(|h| h.text)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
@@ -482,19 +479,22 @@ impl DisplaySnapshot {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn chunks(
|
||||
&self,
|
||||
pub fn chunks<'a>(
|
||||
&'a self,
|
||||
display_rows: Range<u32>,
|
||||
language_aware: bool,
|
||||
hint_highlight_style: Option<HighlightStyle>,
|
||||
inlay_highlight_style: Option<HighlightStyle>,
|
||||
suggestion_highlight_style: Option<HighlightStyle>,
|
||||
) -> DisplayChunks<'_> {
|
||||
self.block_snapshot.chunks(
|
||||
display_rows,
|
||||
language_aware,
|
||||
Some(&self.text_highlights),
|
||||
hint_highlight_style,
|
||||
suggestion_highlight_style,
|
||||
Highlights {
|
||||
text_highlights: Some(&self.text_highlights),
|
||||
inlay_highlights: Some(&self.inlay_highlights),
|
||||
inlay_highlight_style,
|
||||
suggestion_highlight_style,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -752,12 +752,20 @@ impl DisplaySnapshot {
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn highlight_ranges<Tag: ?Sized + 'static>(
|
||||
pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
|
||||
&self,
|
||||
) -> Option<Arc<(HighlightStyle, Vec<DocumentRange>)>> {
|
||||
) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
|
||||
let type_id = TypeId::of::<Tag>();
|
||||
self.text_highlights.get(&Some(type_id)).cloned()
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn inlay_highlights<Tag: ?Sized + 'static>(
|
||||
&self,
|
||||
) -> Option<&HashMap<InlayId, (HighlightStyle, InlayHighlight)>> {
|
||||
let type_id = TypeId::of::<Tag>();
|
||||
self.inlay_highlights.get(&type_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::{
|
||||
wrap_map::{self, WrapEdit, WrapPoint, WrapSnapshot},
|
||||
TextHighlights,
|
||||
Highlights,
|
||||
};
|
||||
use crate::{Anchor, Editor, ExcerptId, ExcerptRange, ToPoint as _};
|
||||
use collections::{Bound, HashMap, HashSet};
|
||||
use gpui::{fonts::HighlightStyle, AnyElement, ViewContext};
|
||||
use gpui::{AnyElement, ViewContext};
|
||||
use language::{BufferSnapshot, Chunk, Patch, Point};
|
||||
use parking_lot::Mutex;
|
||||
use std::{
|
||||
@@ -576,9 +576,7 @@ impl BlockSnapshot {
|
||||
self.chunks(
|
||||
0..self.transforms.summary().output_rows,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Highlights::default(),
|
||||
)
|
||||
.map(|chunk| chunk.text)
|
||||
.collect()
|
||||
@@ -588,9 +586,7 @@ impl BlockSnapshot {
|
||||
&'a self,
|
||||
rows: Range<u32>,
|
||||
language_aware: bool,
|
||||
text_highlights: Option<&'a TextHighlights>,
|
||||
hint_highlight_style: Option<HighlightStyle>,
|
||||
suggestion_highlight_style: Option<HighlightStyle>,
|
||||
highlights: Highlights<'a>,
|
||||
) -> BlockChunks<'a> {
|
||||
let max_output_row = cmp::min(rows.end, self.transforms.summary().output_rows);
|
||||
let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
|
||||
@@ -622,9 +618,7 @@ impl BlockSnapshot {
|
||||
input_chunks: self.wrap_snapshot.chunks(
|
||||
input_start..input_end,
|
||||
language_aware,
|
||||
text_highlights,
|
||||
hint_highlight_style,
|
||||
suggestion_highlight_style,
|
||||
highlights,
|
||||
),
|
||||
input_chunk: Default::default(),
|
||||
transforms: cursor,
|
||||
@@ -1501,9 +1495,7 @@ mod tests {
|
||||
.chunks(
|
||||
start_row as u32..blocks_snapshot.max_point().row + 1,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Highlights::default(),
|
||||
)
|
||||
.map(|chunk| chunk.text)
|
||||
.collect::<String>();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
inlay_map::{InlayBufferRows, InlayChunks, InlayEdit, InlayOffset, InlayPoint, InlaySnapshot},
|
||||
TextHighlights,
|
||||
Highlights,
|
||||
};
|
||||
use crate::{Anchor, AnchorRangeExt, MultiBufferSnapshot, ToOffset};
|
||||
use gpui::{color::Color, fonts::HighlightStyle};
|
||||
@@ -475,7 +475,7 @@ pub struct FoldSnapshot {
|
||||
impl FoldSnapshot {
|
||||
#[cfg(test)]
|
||||
pub fn text(&self) -> String {
|
||||
self.chunks(FoldOffset(0)..self.len(), false, None, None, None)
|
||||
self.chunks(FoldOffset(0)..self.len(), false, Highlights::default())
|
||||
.map(|c| c.text)
|
||||
.collect()
|
||||
}
|
||||
@@ -651,9 +651,7 @@ impl FoldSnapshot {
|
||||
&'a self,
|
||||
range: Range<FoldOffset>,
|
||||
language_aware: bool,
|
||||
text_highlights: Option<&'a TextHighlights>,
|
||||
hint_highlight_style: Option<HighlightStyle>,
|
||||
suggestion_highlight_style: Option<HighlightStyle>,
|
||||
highlights: Highlights<'a>,
|
||||
) -> FoldChunks<'a> {
|
||||
let mut transform_cursor = self.transforms.cursor::<(FoldOffset, InlayOffset)>();
|
||||
|
||||
@@ -674,9 +672,7 @@ impl FoldSnapshot {
|
||||
inlay_chunks: self.inlay_snapshot.chunks(
|
||||
inlay_start..inlay_end,
|
||||
language_aware,
|
||||
text_highlights,
|
||||
hint_highlight_style,
|
||||
suggestion_highlight_style,
|
||||
highlights,
|
||||
),
|
||||
inlay_chunk: None,
|
||||
inlay_offset: inlay_start,
|
||||
@@ -687,8 +683,12 @@ impl FoldSnapshot {
|
||||
}
|
||||
|
||||
pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
|
||||
self.chunks(start.to_offset(self)..self.len(), false, None, None, None)
|
||||
.flat_map(|chunk| chunk.text.chars())
|
||||
self.chunks(
|
||||
start.to_offset(self)..self.len(),
|
||||
false,
|
||||
Highlights::default(),
|
||||
)
|
||||
.flat_map(|chunk| chunk.text.chars())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1496,7 +1496,7 @@ mod tests {
|
||||
let text = &expected_text[start.0..end.0];
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.chunks(start..end, false, None, None, None)
|
||||
.chunks(start..end, false, Highlights::default())
|
||||
.map(|c| c.text)
|
||||
.collect::<String>(),
|
||||
text,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::{
|
||||
link_go_to_definition::DocumentRange,
|
||||
multi_buffer::{MultiBufferChunks, MultiBufferRows},
|
||||
Anchor, InlayId, MultiBufferSnapshot, ToOffset,
|
||||
};
|
||||
@@ -11,12 +10,13 @@ use std::{
|
||||
cmp,
|
||||
iter::Peekable,
|
||||
ops::{Add, AddAssign, Range, Sub, SubAssign},
|
||||
sync::Arc,
|
||||
vec,
|
||||
};
|
||||
use sum_tree::{Bias, Cursor, SumTree};
|
||||
use sum_tree::{Bias, Cursor, SumTree, TreeMap};
|
||||
use text::{Patch, Rope};
|
||||
|
||||
use super::TextHighlights;
|
||||
use super::Highlights;
|
||||
|
||||
pub struct InlayMap {
|
||||
snapshot: InlaySnapshot,
|
||||
@@ -214,10 +214,11 @@ pub struct InlayChunks<'a> {
|
||||
inlay_chunk: Option<&'a str>,
|
||||
output_offset: InlayOffset,
|
||||
max_output_offset: InlayOffset,
|
||||
hint_highlight_style: Option<HighlightStyle>,
|
||||
inlay_highlight_style: Option<HighlightStyle>,
|
||||
suggestion_highlight_style: Option<HighlightStyle>,
|
||||
highlight_endpoints: Peekable<vec::IntoIter<HighlightEndpoint>>,
|
||||
active_highlights: BTreeMap<Option<TypeId>, HighlightStyle>,
|
||||
highlights: Highlights<'a>,
|
||||
snapshot: &'a InlaySnapshot,
|
||||
}
|
||||
|
||||
@@ -293,8 +294,41 @@ impl<'a> Iterator for InlayChunks<'a> {
|
||||
prefix
|
||||
}
|
||||
Transform::Inlay(inlay) => {
|
||||
let mut inlay_style_and_highlight = None;
|
||||
if let Some(inlay_highlights) = self.highlights.inlay_highlights {
|
||||
for (_, inlay_id_to_data) in inlay_highlights.iter() {
|
||||
let style_and_highlight = inlay_id_to_data.get(&inlay.id);
|
||||
if style_and_highlight.is_some() {
|
||||
inlay_style_and_highlight = style_and_highlight;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut highlight_style = match inlay.id {
|
||||
InlayId::Suggestion(_) => self.suggestion_highlight_style,
|
||||
InlayId::Hint(_) => self.inlay_highlight_style,
|
||||
};
|
||||
let next_inlay_highlight_endpoint;
|
||||
let offset_in_inlay = self.output_offset - self.transforms.start().0;
|
||||
if let Some((style, highlight)) = inlay_style_and_highlight {
|
||||
let range = &highlight.range;
|
||||
if offset_in_inlay.0 < range.start {
|
||||
next_inlay_highlight_endpoint = range.start - offset_in_inlay.0;
|
||||
} else if offset_in_inlay.0 >= range.end {
|
||||
next_inlay_highlight_endpoint = usize::MAX;
|
||||
} else {
|
||||
next_inlay_highlight_endpoint = range.end - offset_in_inlay.0;
|
||||
highlight_style
|
||||
.get_or_insert_with(|| Default::default())
|
||||
.highlight(style.clone());
|
||||
}
|
||||
} else {
|
||||
next_inlay_highlight_endpoint = usize::MAX;
|
||||
}
|
||||
|
||||
let inlay_chunks = self.inlay_chunks.get_or_insert_with(|| {
|
||||
let start = self.output_offset - self.transforms.start().0;
|
||||
let start = offset_in_inlay;
|
||||
let end = cmp::min(self.max_output_offset, self.transforms.end(&()).0)
|
||||
- self.transforms.start().0;
|
||||
inlay.text.chunks_in_range(start.0..end.0)
|
||||
@@ -302,21 +336,15 @@ impl<'a> Iterator for InlayChunks<'a> {
|
||||
let inlay_chunk = self
|
||||
.inlay_chunk
|
||||
.get_or_insert_with(|| inlay_chunks.next().unwrap());
|
||||
let (chunk, remainder) = inlay_chunk.split_at(
|
||||
inlay_chunk
|
||||
.len()
|
||||
.min(next_highlight_endpoint.0 - self.output_offset.0),
|
||||
);
|
||||
let (chunk, remainder) =
|
||||
inlay_chunk.split_at(inlay_chunk.len().min(next_inlay_highlight_endpoint));
|
||||
*inlay_chunk = remainder;
|
||||
if inlay_chunk.is_empty() {
|
||||
self.inlay_chunk = None;
|
||||
}
|
||||
|
||||
self.output_offset.0 += chunk.len();
|
||||
let mut highlight_style = match inlay.id {
|
||||
InlayId::Suggestion(_) => self.suggestion_highlight_style,
|
||||
InlayId::Hint(_) => self.hint_highlight_style,
|
||||
};
|
||||
|
||||
if !self.active_highlights.is_empty() {
|
||||
for active_highlight in self.active_highlights.values() {
|
||||
highlight_style
|
||||
@@ -625,18 +653,20 @@ impl InlayMap {
|
||||
.filter(|ch| *ch != '\r')
|
||||
.take(len)
|
||||
.collect::<String>();
|
||||
log::info!(
|
||||
"creating inlay at buffer offset {} with bias {:?} and text {:?}",
|
||||
position,
|
||||
bias,
|
||||
text
|
||||
);
|
||||
|
||||
let inlay_id = if i % 2 == 0 {
|
||||
InlayId::Hint(post_inc(next_inlay_id))
|
||||
} else {
|
||||
InlayId::Suggestion(post_inc(next_inlay_id))
|
||||
};
|
||||
log::info!(
|
||||
"creating inlay {:?} at buffer offset {} with bias {:?} and text {:?}",
|
||||
inlay_id,
|
||||
position,
|
||||
bias,
|
||||
text
|
||||
);
|
||||
|
||||
to_insert.push(Inlay {
|
||||
id: inlay_id,
|
||||
position: snapshot.buffer.anchor_at(position, bias),
|
||||
@@ -992,77 +1022,24 @@ impl InlaySnapshot {
|
||||
&'a self,
|
||||
range: Range<InlayOffset>,
|
||||
language_aware: bool,
|
||||
text_highlights: Option<&'a TextHighlights>,
|
||||
hint_highlight_style: Option<HighlightStyle>,
|
||||
suggestion_highlight_style: Option<HighlightStyle>,
|
||||
highlights: Highlights<'a>,
|
||||
) -> InlayChunks<'a> {
|
||||
let mut cursor = self.transforms.cursor::<(InlayOffset, usize)>();
|
||||
cursor.seek(&range.start, Bias::Right, &());
|
||||
|
||||
let mut highlight_endpoints = Vec::new();
|
||||
if let Some(text_highlights) = text_highlights {
|
||||
if let Some(text_highlights) = highlights.text_highlights {
|
||||
if !text_highlights.is_empty() {
|
||||
while cursor.start().0 < range.end {
|
||||
let transform_start = self.buffer.anchor_after(
|
||||
self.to_buffer_offset(cmp::max(range.start, cursor.start().0)),
|
||||
);
|
||||
let transform_start =
|
||||
self.to_inlay_offset(transform_start.to_offset(&self.buffer));
|
||||
|
||||
let transform_end = {
|
||||
let overshoot = InlayOffset(range.end.0 - cursor.start().0 .0);
|
||||
self.buffer.anchor_before(self.to_buffer_offset(cmp::min(
|
||||
cursor.end(&()).0,
|
||||
cursor.start().0 + overshoot,
|
||||
)))
|
||||
};
|
||||
let transform_end = self.to_inlay_offset(transform_end.to_offset(&self.buffer));
|
||||
|
||||
for (tag, text_highlights) in text_highlights.iter() {
|
||||
let style = text_highlights.0;
|
||||
let ranges = &text_highlights.1;
|
||||
|
||||
let start_ix = match ranges.binary_search_by(|probe| {
|
||||
let cmp = self
|
||||
.document_to_inlay_range(probe)
|
||||
.end
|
||||
.cmp(&transform_start);
|
||||
if cmp.is_gt() {
|
||||
cmp::Ordering::Greater
|
||||
} else {
|
||||
cmp::Ordering::Less
|
||||
}
|
||||
}) {
|
||||
Ok(i) | Err(i) => i,
|
||||
};
|
||||
for range in &ranges[start_ix..] {
|
||||
let range = self.document_to_inlay_range(range);
|
||||
if range.start.cmp(&transform_end).is_ge() {
|
||||
break;
|
||||
}
|
||||
|
||||
highlight_endpoints.push(HighlightEndpoint {
|
||||
offset: range.start,
|
||||
is_start: true,
|
||||
tag: *tag,
|
||||
style,
|
||||
});
|
||||
highlight_endpoints.push(HighlightEndpoint {
|
||||
offset: range.end,
|
||||
is_start: false,
|
||||
tag: *tag,
|
||||
style,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
cursor.next(&());
|
||||
}
|
||||
highlight_endpoints.sort();
|
||||
self.apply_text_highlights(
|
||||
&mut cursor,
|
||||
&range,
|
||||
text_highlights,
|
||||
&mut highlight_endpoints,
|
||||
);
|
||||
cursor.seek(&range.start, Bias::Right, &());
|
||||
}
|
||||
}
|
||||
|
||||
highlight_endpoints.sort();
|
||||
let buffer_range = self.to_buffer_offset(range.start)..self.to_buffer_offset(range.end);
|
||||
let buffer_chunks = self.buffer.chunks(buffer_range, language_aware);
|
||||
|
||||
@@ -1074,29 +1051,76 @@ impl InlaySnapshot {
|
||||
buffer_chunk: None,
|
||||
output_offset: range.start,
|
||||
max_output_offset: range.end,
|
||||
hint_highlight_style,
|
||||
suggestion_highlight_style,
|
||||
inlay_highlight_style: highlights.inlay_highlight_style,
|
||||
suggestion_highlight_style: highlights.suggestion_highlight_style,
|
||||
highlight_endpoints: highlight_endpoints.into_iter().peekable(),
|
||||
active_highlights: Default::default(),
|
||||
highlights,
|
||||
snapshot: self,
|
||||
}
|
||||
}
|
||||
|
||||
fn document_to_inlay_range(&self, range: &DocumentRange) -> Range<InlayOffset> {
|
||||
match range {
|
||||
DocumentRange::Text(text_range) => {
|
||||
self.to_inlay_offset(text_range.start.to_offset(&self.buffer))
|
||||
..self.to_inlay_offset(text_range.end.to_offset(&self.buffer))
|
||||
}
|
||||
DocumentRange::Inlay(inlay_range) => {
|
||||
inlay_range.highlight_start..inlay_range.highlight_end
|
||||
fn apply_text_highlights(
|
||||
&self,
|
||||
cursor: &mut Cursor<'_, Transform, (InlayOffset, usize)>,
|
||||
range: &Range<InlayOffset>,
|
||||
text_highlights: &TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>,
|
||||
highlight_endpoints: &mut Vec<HighlightEndpoint>,
|
||||
) {
|
||||
while cursor.start().0 < range.end {
|
||||
let transform_start = self
|
||||
.buffer
|
||||
.anchor_after(self.to_buffer_offset(cmp::max(range.start, cursor.start().0)));
|
||||
let transform_end =
|
||||
{
|
||||
let overshoot = InlayOffset(range.end.0 - cursor.start().0 .0);
|
||||
self.buffer.anchor_before(self.to_buffer_offset(cmp::min(
|
||||
cursor.end(&()).0,
|
||||
cursor.start().0 + overshoot,
|
||||
)))
|
||||
};
|
||||
|
||||
for (tag, text_highlights) in text_highlights.iter() {
|
||||
let style = text_highlights.0;
|
||||
let ranges = &text_highlights.1;
|
||||
|
||||
let start_ix = match ranges.binary_search_by(|probe| {
|
||||
let cmp = probe.end.cmp(&transform_start, &self.buffer);
|
||||
if cmp.is_gt() {
|
||||
cmp::Ordering::Greater
|
||||
} else {
|
||||
cmp::Ordering::Less
|
||||
}
|
||||
}) {
|
||||
Ok(i) | Err(i) => i,
|
||||
};
|
||||
for range in &ranges[start_ix..] {
|
||||
if range.start.cmp(&transform_end, &self.buffer).is_ge() {
|
||||
break;
|
||||
}
|
||||
|
||||
highlight_endpoints.push(HighlightEndpoint {
|
||||
offset: self.to_inlay_offset(range.start.to_offset(&self.buffer)),
|
||||
is_start: true,
|
||||
tag: *tag,
|
||||
style,
|
||||
});
|
||||
highlight_endpoints.push(HighlightEndpoint {
|
||||
offset: self.to_inlay_offset(range.end.to_offset(&self.buffer)),
|
||||
is_start: false,
|
||||
tag: *tag,
|
||||
style,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
cursor.next(&());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn text(&self) -> String {
|
||||
self.chunks(Default::default()..self.len(), false, None, None, None)
|
||||
self.chunks(Default::default()..self.len(), false, Highlights::default())
|
||||
.map(|chunk| chunk.text)
|
||||
.collect()
|
||||
}
|
||||
@@ -1144,7 +1168,11 @@ fn push_isomorphic(sum_tree: &mut SumTree<Transform>, summary: TextSummary) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{link_go_to_definition::InlayRange, InlayId, MultiBuffer};
|
||||
use crate::{
|
||||
display_map::{InlayHighlights, TextHighlights},
|
||||
link_go_to_definition::InlayHighlight,
|
||||
InlayId, MultiBuffer,
|
||||
};
|
||||
use gpui::AppContext;
|
||||
use project::{InlayHint, InlayHintLabel, ResolveState};
|
||||
use rand::prelude::*;
|
||||
@@ -1619,8 +1647,8 @@ mod tests {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut expected_text = Rope::from(buffer_snapshot.text());
|
||||
for (offset, inlay) in inlays.into_iter().rev() {
|
||||
expected_text.replace(offset..offset, &inlay.text.to_string());
|
||||
for (offset, inlay) in inlays.iter().rev() {
|
||||
expected_text.replace(*offset..*offset, &inlay.text.to_string());
|
||||
}
|
||||
assert_eq!(inlay_snapshot.text(), expected_text.to_string());
|
||||
|
||||
@@ -1640,51 +1668,87 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
let mut highlights = TextHighlights::default();
|
||||
let highlight_count = rng.gen_range(0_usize..10);
|
||||
let mut highlight_ranges = (0..highlight_count)
|
||||
let mut text_highlights = TextHighlights::default();
|
||||
let text_highlight_count = rng.gen_range(0_usize..10);
|
||||
let mut text_highlight_ranges = (0..text_highlight_count)
|
||||
.map(|_| buffer_snapshot.random_byte_range(0, &mut rng))
|
||||
.collect::<Vec<_>>();
|
||||
highlight_ranges.sort_by_key(|range| (range.start, Reverse(range.end)));
|
||||
log::info!("highlighting ranges {:?}", highlight_ranges);
|
||||
let highlight_ranges = if rng.gen_bool(0.5) {
|
||||
highlight_ranges
|
||||
.into_iter()
|
||||
.map(|range| InlayRange {
|
||||
inlay_position: buffer_snapshot.anchor_before(range.start),
|
||||
highlight_start: inlay_snapshot.to_inlay_offset(range.start),
|
||||
highlight_end: inlay_snapshot.to_inlay_offset(range.end),
|
||||
})
|
||||
.map(DocumentRange::Inlay)
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
highlight_ranges
|
||||
.into_iter()
|
||||
.map(|range| {
|
||||
buffer_snapshot.anchor_before(range.start)
|
||||
..buffer_snapshot.anchor_after(range.end)
|
||||
})
|
||||
.map(DocumentRange::Text)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
highlights.insert(
|
||||
text_highlight_ranges.sort_by_key(|range| (range.start, Reverse(range.end)));
|
||||
log::info!("highlighting text ranges {text_highlight_ranges:?}");
|
||||
text_highlights.insert(
|
||||
Some(TypeId::of::<()>()),
|
||||
Arc::new((HighlightStyle::default(), highlight_ranges)),
|
||||
Arc::new((
|
||||
HighlightStyle::default(),
|
||||
text_highlight_ranges
|
||||
.into_iter()
|
||||
.map(|range| {
|
||||
buffer_snapshot.anchor_before(range.start)
|
||||
..buffer_snapshot.anchor_after(range.end)
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
);
|
||||
|
||||
let mut inlay_highlights = InlayHighlights::default();
|
||||
if !inlays.is_empty() {
|
||||
let inlay_highlight_count = rng.gen_range(0..inlays.len());
|
||||
let mut inlay_indices = BTreeSet::default();
|
||||
while inlay_indices.len() < inlay_highlight_count {
|
||||
inlay_indices.insert(rng.gen_range(0..inlays.len()));
|
||||
}
|
||||
let new_highlights = inlay_indices
|
||||
.into_iter()
|
||||
.filter_map(|i| {
|
||||
let (_, inlay) = &inlays[i];
|
||||
let inlay_text_len = inlay.text.len();
|
||||
match inlay_text_len {
|
||||
0 => None,
|
||||
1 => Some(InlayHighlight {
|
||||
inlay: inlay.id,
|
||||
inlay_position: inlay.position,
|
||||
range: 0..1,
|
||||
}),
|
||||
n => {
|
||||
let inlay_text = inlay.text.to_string();
|
||||
let mut highlight_end = rng.gen_range(1..n);
|
||||
let mut highlight_start = rng.gen_range(0..highlight_end);
|
||||
while !inlay_text.is_char_boundary(highlight_end) {
|
||||
highlight_end += 1;
|
||||
}
|
||||
while !inlay_text.is_char_boundary(highlight_start) {
|
||||
highlight_start -= 1;
|
||||
}
|
||||
Some(InlayHighlight {
|
||||
inlay: inlay.id,
|
||||
inlay_position: inlay.position,
|
||||
range: highlight_start..highlight_end,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
.map(|highlight| (highlight.inlay, (HighlightStyle::default(), highlight)))
|
||||
.collect();
|
||||
log::info!("highlighting inlay ranges {new_highlights:?}");
|
||||
inlay_highlights.insert(TypeId::of::<()>(), new_highlights);
|
||||
}
|
||||
|
||||
for _ in 0..5 {
|
||||
let mut end = rng.gen_range(0..=inlay_snapshot.len().0);
|
||||
end = expected_text.clip_offset(end, Bias::Right);
|
||||
let mut start = rng.gen_range(0..=end);
|
||||
start = expected_text.clip_offset(start, Bias::Right);
|
||||
|
||||
let range = InlayOffset(start)..InlayOffset(end);
|
||||
log::info!("calling inlay_snapshot.chunks({range:?})");
|
||||
let actual_text = inlay_snapshot
|
||||
.chunks(
|
||||
InlayOffset(start)..InlayOffset(end),
|
||||
range,
|
||||
false,
|
||||
Some(&highlights),
|
||||
None,
|
||||
None,
|
||||
Highlights {
|
||||
text_highlights: Some(&text_highlights),
|
||||
inlay_highlights: Some(&inlay_highlights),
|
||||
..Highlights::default()
|
||||
},
|
||||
)
|
||||
.map(|chunk| chunk.text)
|
||||
.collect::<String>();
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use super::{
|
||||
fold_map::{self, FoldChunks, FoldEdit, FoldPoint, FoldSnapshot},
|
||||
TextHighlights,
|
||||
Highlights,
|
||||
};
|
||||
use crate::MultiBufferSnapshot;
|
||||
use gpui::fonts::HighlightStyle;
|
||||
use language::{Chunk, Point};
|
||||
use std::{cmp, mem, num::NonZeroU32, ops::Range};
|
||||
use sum_tree::Bias;
|
||||
@@ -68,9 +67,7 @@ impl TabMap {
|
||||
'outer: for chunk in old_snapshot.fold_snapshot.chunks(
|
||||
fold_edit.old.end..old_end_row_successor_offset,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Highlights::default(),
|
||||
) {
|
||||
for (ix, _) in chunk.text.match_indices('\t') {
|
||||
let offset_from_edit = offset_from_edit + (ix as u32);
|
||||
@@ -183,7 +180,7 @@ impl TabSnapshot {
|
||||
self.max_point()
|
||||
};
|
||||
for c in self
|
||||
.chunks(range.start..line_end, false, None, None, None)
|
||||
.chunks(range.start..line_end, false, Highlights::default())
|
||||
.flat_map(|chunk| chunk.text.chars())
|
||||
{
|
||||
if c == '\n' {
|
||||
@@ -200,9 +197,7 @@ impl TabSnapshot {
|
||||
.chunks(
|
||||
TabPoint::new(range.end.row(), 0)..range.end,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Highlights::default(),
|
||||
)
|
||||
.flat_map(|chunk| chunk.text.chars())
|
||||
{
|
||||
@@ -223,9 +218,7 @@ impl TabSnapshot {
|
||||
&'a self,
|
||||
range: Range<TabPoint>,
|
||||
language_aware: bool,
|
||||
text_highlights: Option<&'a TextHighlights>,
|
||||
hint_highlight_style: Option<HighlightStyle>,
|
||||
suggestion_highlight_style: Option<HighlightStyle>,
|
||||
highlights: Highlights<'a>,
|
||||
) -> TabChunks<'a> {
|
||||
let (input_start, expanded_char_column, to_next_stop) =
|
||||
self.to_fold_point(range.start, Bias::Left);
|
||||
@@ -245,9 +238,7 @@ impl TabSnapshot {
|
||||
fold_chunks: self.fold_snapshot.chunks(
|
||||
input_start..input_end,
|
||||
language_aware,
|
||||
text_highlights,
|
||||
hint_highlight_style,
|
||||
suggestion_highlight_style,
|
||||
highlights,
|
||||
),
|
||||
input_column,
|
||||
column: expanded_char_column,
|
||||
@@ -270,9 +261,13 @@ impl TabSnapshot {
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn text(&self) -> String {
|
||||
self.chunks(TabPoint::zero()..self.max_point(), false, None, None, None)
|
||||
.map(|chunk| chunk.text)
|
||||
.collect()
|
||||
self.chunks(
|
||||
TabPoint::zero()..self.max_point(),
|
||||
false,
|
||||
Highlights::default(),
|
||||
)
|
||||
.map(|chunk| chunk.text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn max_point(&self) -> TabPoint {
|
||||
@@ -597,9 +592,7 @@ mod tests {
|
||||
.chunks(
|
||||
TabPoint::new(0, ix as u32)..tab_snapshot.max_point(),
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Highlights::default(),
|
||||
)
|
||||
.map(|c| c.text)
|
||||
.collect::<String>(),
|
||||
@@ -674,7 +667,8 @@ mod tests {
|
||||
let mut chunks = Vec::new();
|
||||
let mut was_tab = false;
|
||||
let mut text = String::new();
|
||||
for chunk in snapshot.chunks(start..snapshot.max_point(), false, None, None, None) {
|
||||
for chunk in snapshot.chunks(start..snapshot.max_point(), false, Highlights::default())
|
||||
{
|
||||
if chunk.is_tab != was_tab {
|
||||
if !text.is_empty() {
|
||||
chunks.push((mem::take(&mut text), was_tab));
|
||||
@@ -743,7 +737,7 @@ mod tests {
|
||||
let expected_summary = TextSummary::from(expected_text.as_str());
|
||||
assert_eq!(
|
||||
tabs_snapshot
|
||||
.chunks(start..end, false, None, None, None)
|
||||
.chunks(start..end, false, Highlights::default())
|
||||
.map(|c| c.text)
|
||||
.collect::<String>(),
|
||||
expected_text,
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use super::{
|
||||
fold_map::FoldBufferRows,
|
||||
tab_map::{self, TabEdit, TabPoint, TabSnapshot},
|
||||
TextHighlights,
|
||||
Highlights,
|
||||
};
|
||||
use crate::MultiBufferSnapshot;
|
||||
use gpui::{
|
||||
fonts::{FontId, HighlightStyle},
|
||||
text_layout::LineWrapper,
|
||||
AppContext, Entity, ModelContext, ModelHandle, Task,
|
||||
fonts::FontId, text_layout::LineWrapper, AppContext, Entity, ModelContext, ModelHandle, Task,
|
||||
};
|
||||
use language::{Chunk, Point};
|
||||
use lazy_static::lazy_static;
|
||||
@@ -444,9 +442,7 @@ impl WrapSnapshot {
|
||||
let mut chunks = new_tab_snapshot.chunks(
|
||||
TabPoint::new(edit.new_rows.start, 0)..new_tab_snapshot.max_point(),
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Highlights::default(),
|
||||
);
|
||||
let mut edit_transforms = Vec::<Transform>::new();
|
||||
for _ in edit.new_rows.start..edit.new_rows.end {
|
||||
@@ -575,9 +571,7 @@ impl WrapSnapshot {
|
||||
&'a self,
|
||||
rows: Range<u32>,
|
||||
language_aware: bool,
|
||||
text_highlights: Option<&'a TextHighlights>,
|
||||
hint_highlight_style: Option<HighlightStyle>,
|
||||
suggestion_highlight_style: Option<HighlightStyle>,
|
||||
highlights: Highlights<'a>,
|
||||
) -> WrapChunks<'a> {
|
||||
let output_start = WrapPoint::new(rows.start, 0);
|
||||
let output_end = WrapPoint::new(rows.end, 0);
|
||||
@@ -594,9 +588,7 @@ impl WrapSnapshot {
|
||||
input_chunks: self.tab_snapshot.chunks(
|
||||
input_start..input_end,
|
||||
language_aware,
|
||||
text_highlights,
|
||||
hint_highlight_style,
|
||||
suggestion_highlight_style,
|
||||
highlights,
|
||||
),
|
||||
input_chunk: Default::default(),
|
||||
output_position: output_start,
|
||||
@@ -1323,9 +1315,7 @@ mod tests {
|
||||
self.chunks(
|
||||
wrap_row..self.max_point().row() + 1,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Highlights::default(),
|
||||
)
|
||||
.map(|h| h.text)
|
||||
}
|
||||
@@ -1350,7 +1340,7 @@ mod tests {
|
||||
}
|
||||
|
||||
let actual_text = self
|
||||
.chunks(start_row..end_row, true, None, None, None)
|
||||
.chunks(start_row..end_row, true, Highlights::default())
|
||||
.map(|c| c.text)
|
||||
.collect::<String>();
|
||||
assert_eq!(
|
||||
|
||||
+58
-96
@@ -66,7 +66,7 @@ use language::{
|
||||
TransactionId,
|
||||
};
|
||||
use link_go_to_definition::{
|
||||
hide_link_definition, show_link_definition, DocumentRange, GoToDefinitionLink, InlayRange,
|
||||
hide_link_definition, show_link_definition, GoToDefinitionLink, InlayHighlight,
|
||||
LinkGoToDefinitionState,
|
||||
};
|
||||
use log::error;
|
||||
@@ -99,6 +99,7 @@ use std::{
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
pub use sum_tree::Bias;
|
||||
use sum_tree::TreeMap;
|
||||
use text::Rope;
|
||||
use theme::{DiagnosticStyle, Theme, ThemeSettings};
|
||||
use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
|
||||
@@ -548,7 +549,8 @@ type CompletionId = usize;
|
||||
type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
|
||||
type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
|
||||
|
||||
type BackgroundHighlight = (fn(&Theme) -> Color, Vec<DocumentRange>);
|
||||
type BackgroundHighlight = (fn(&Theme) -> Color, Vec<Range<Anchor>>);
|
||||
type InlayBackgroundHighlight = (fn(&Theme) -> Color, Vec<InlayHighlight>);
|
||||
|
||||
pub struct Editor {
|
||||
handle: WeakViewHandle<Self>,
|
||||
@@ -580,6 +582,7 @@ pub struct Editor {
|
||||
placeholder_text: Option<Arc<str>>,
|
||||
highlighted_rows: Option<Range<u32>>,
|
||||
background_highlights: BTreeMap<TypeId, BackgroundHighlight>,
|
||||
inlay_background_highlights: TreeMap<Option<TypeId>, InlayBackgroundHighlight>,
|
||||
nav_history: Option<ItemNavHistory>,
|
||||
context_menu: Option<ContextMenu>,
|
||||
mouse_context_menu: ViewHandle<context_menu::ContextMenu>,
|
||||
@@ -1523,6 +1526,7 @@ impl Editor {
|
||||
placeholder_text: None,
|
||||
highlighted_rows: None,
|
||||
background_highlights: Default::default(),
|
||||
inlay_background_highlights: Default::default(),
|
||||
nav_history: None,
|
||||
context_menu: None,
|
||||
mouse_context_menu: cx
|
||||
@@ -3823,7 +3827,7 @@ impl Editor {
|
||||
enum CodeActions {}
|
||||
Some(
|
||||
MouseEventHandler::new::<CodeActions, _>(0, cx, |state, _| {
|
||||
Svg::new("icons/bolt_8.svg").with_color(
|
||||
Svg::new("icons/bolt.svg").with_color(
|
||||
style
|
||||
.code_actions
|
||||
.indicator
|
||||
@@ -7070,16 +7074,8 @@ impl Editor {
|
||||
} else {
|
||||
this.update(&mut cx, |this, cx| {
|
||||
let buffer = this.buffer.read(cx).snapshot(cx);
|
||||
let display_snapshot = this
|
||||
.display_map
|
||||
.update(cx, |display_map, cx| display_map.snapshot(cx));
|
||||
let mut buffer_highlights = this
|
||||
.document_highlights_for_position(
|
||||
selection.head(),
|
||||
&buffer,
|
||||
&display_snapshot,
|
||||
)
|
||||
.filter_map(|highlight| highlight.as_text_range())
|
||||
.document_highlights_for_position(selection.head(), &buffer)
|
||||
.filter(|highlight| {
|
||||
highlight.start.excerpt_id() == selection.head().excerpt_id()
|
||||
&& highlight.end.excerpt_id() == selection.head().excerpt_id()
|
||||
@@ -7134,15 +7130,11 @@ impl Editor {
|
||||
let ranges = this
|
||||
.clear_background_highlights::<DocumentHighlightWrite>(cx)
|
||||
.into_iter()
|
||||
.flat_map(|(_, ranges)| {
|
||||
ranges.into_iter().filter_map(|range| range.as_text_range())
|
||||
})
|
||||
.flat_map(|(_, ranges)| ranges.into_iter())
|
||||
.chain(
|
||||
this.clear_background_highlights::<DocumentHighlightRead>(cx)
|
||||
.into_iter()
|
||||
.flat_map(|(_, ranges)| {
|
||||
ranges.into_iter().filter_map(|range| range.as_text_range())
|
||||
}),
|
||||
.flat_map(|(_, ranges)| ranges.into_iter()),
|
||||
)
|
||||
.collect();
|
||||
|
||||
@@ -7243,7 +7235,7 @@ impl Editor {
|
||||
Some(Autoscroll::fit()),
|
||||
cx,
|
||||
);
|
||||
self.clear_text_highlights::<Rename>(cx);
|
||||
self.clear_highlights::<Rename>(cx);
|
||||
self.show_local_selections = true;
|
||||
|
||||
if moving_cursor {
|
||||
@@ -7820,29 +7812,20 @@ impl Editor {
|
||||
color_fetcher: fn(&Theme) -> Color,
|
||||
cx: &mut ViewContext<Self>,
|
||||
) {
|
||||
self.background_highlights.insert(
|
||||
TypeId::of::<T>(),
|
||||
(
|
||||
color_fetcher,
|
||||
ranges.into_iter().map(DocumentRange::Text).collect(),
|
||||
),
|
||||
);
|
||||
self.background_highlights
|
||||
.insert(TypeId::of::<T>(), (color_fetcher, ranges));
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub fn highlight_inlay_background<T: 'static>(
|
||||
&mut self,
|
||||
ranges: Vec<InlayRange>,
|
||||
ranges: Vec<InlayHighlight>,
|
||||
color_fetcher: fn(&Theme) -> Color,
|
||||
cx: &mut ViewContext<Self>,
|
||||
) {
|
||||
self.background_highlights.insert(
|
||||
TypeId::of::<T>(),
|
||||
(
|
||||
color_fetcher,
|
||||
ranges.into_iter().map(DocumentRange::Inlay).collect(),
|
||||
),
|
||||
);
|
||||
// TODO: no actual highlights happen for inlays currently, find a way to do that
|
||||
self.inlay_background_highlights
|
||||
.insert(Some(TypeId::of::<T>()), (color_fetcher, ranges));
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
@@ -7850,15 +7833,18 @@ impl Editor {
|
||||
&mut self,
|
||||
cx: &mut ViewContext<Self>,
|
||||
) -> Option<BackgroundHighlight> {
|
||||
let highlights = self.background_highlights.remove(&TypeId::of::<T>());
|
||||
if highlights.is_some() {
|
||||
let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
|
||||
let inlay_highlights = self
|
||||
.inlay_background_highlights
|
||||
.remove(&Some(TypeId::of::<T>()));
|
||||
if text_highlights.is_some() || inlay_highlights.is_some() {
|
||||
cx.notify();
|
||||
}
|
||||
highlights
|
||||
text_highlights
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-support")]
|
||||
pub fn all_background_highlights(
|
||||
pub fn all_text_background_highlights(
|
||||
&mut self,
|
||||
cx: &mut ViewContext<Self>,
|
||||
) -> Vec<(Range<DisplayPoint>, Color)> {
|
||||
@@ -7874,8 +7860,7 @@ impl Editor {
|
||||
&'a self,
|
||||
position: Anchor,
|
||||
buffer: &'a MultiBufferSnapshot,
|
||||
display_snapshot: &'a DisplaySnapshot,
|
||||
) -> impl 'a + Iterator<Item = &DocumentRange> {
|
||||
) -> impl 'a + Iterator<Item = &Range<Anchor>> {
|
||||
let read_highlights = self
|
||||
.background_highlights
|
||||
.get(&TypeId::of::<DocumentHighlightRead>())
|
||||
@@ -7884,16 +7869,14 @@ impl Editor {
|
||||
.background_highlights
|
||||
.get(&TypeId::of::<DocumentHighlightWrite>())
|
||||
.map(|h| &h.1);
|
||||
let left_position = display_snapshot.anchor_to_inlay_offset(position.bias_left(buffer));
|
||||
let right_position = display_snapshot.anchor_to_inlay_offset(position.bias_right(buffer));
|
||||
let left_position = position.bias_left(buffer);
|
||||
let right_position = position.bias_right(buffer);
|
||||
read_highlights
|
||||
.into_iter()
|
||||
.chain(write_highlights)
|
||||
.flat_map(move |ranges| {
|
||||
let start_ix = match ranges.binary_search_by(|probe| {
|
||||
let cmp = document_to_inlay_range(probe, display_snapshot)
|
||||
.end
|
||||
.cmp(&left_position);
|
||||
let cmp = probe.end.cmp(&left_position, buffer);
|
||||
if cmp.is_ge() {
|
||||
Ordering::Greater
|
||||
} else {
|
||||
@@ -7904,12 +7887,9 @@ impl Editor {
|
||||
};
|
||||
|
||||
let right_position = right_position.clone();
|
||||
ranges[start_ix..].iter().take_while(move |range| {
|
||||
document_to_inlay_range(range, display_snapshot)
|
||||
.start
|
||||
.cmp(&right_position)
|
||||
.is_le()
|
||||
})
|
||||
ranges[start_ix..]
|
||||
.iter()
|
||||
.take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -7919,15 +7899,13 @@ impl Editor {
|
||||
display_snapshot: &DisplaySnapshot,
|
||||
theme: &Theme,
|
||||
) -> Vec<(Range<DisplayPoint>, Color)> {
|
||||
let search_range = display_snapshot.anchor_to_inlay_offset(search_range.start)
|
||||
..display_snapshot.anchor_to_inlay_offset(search_range.end);
|
||||
let mut results = Vec::new();
|
||||
for (color_fetcher, ranges) in self.background_highlights.values() {
|
||||
let color = color_fetcher(theme);
|
||||
let start_ix = match ranges.binary_search_by(|probe| {
|
||||
let cmp = document_to_inlay_range(probe, display_snapshot)
|
||||
let cmp = probe
|
||||
.end
|
||||
.cmp(&search_range.start);
|
||||
.cmp(&search_range.start, &display_snapshot.buffer_snapshot);
|
||||
if cmp.is_gt() {
|
||||
Ordering::Greater
|
||||
} else {
|
||||
@@ -7937,13 +7915,16 @@ impl Editor {
|
||||
Ok(i) | Err(i) => i,
|
||||
};
|
||||
for range in &ranges[start_ix..] {
|
||||
let range = document_to_inlay_range(range, display_snapshot);
|
||||
if range.start.cmp(&search_range.end).is_ge() {
|
||||
if range
|
||||
.start
|
||||
.cmp(&search_range.end, &display_snapshot.buffer_snapshot)
|
||||
.is_ge()
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
let start = display_snapshot.inlay_offset_to_display_point(range.start, Bias::Left);
|
||||
let end = display_snapshot.inlay_offset_to_display_point(range.end, Bias::Right);
|
||||
let start = range.start.to_display_point(&display_snapshot);
|
||||
let end = range.end.to_display_point(&display_snapshot);
|
||||
results.push((start..end, color))
|
||||
}
|
||||
}
|
||||
@@ -7956,17 +7937,15 @@ impl Editor {
|
||||
display_snapshot: &DisplaySnapshot,
|
||||
count: usize,
|
||||
) -> Vec<RangeInclusive<DisplayPoint>> {
|
||||
let search_range = display_snapshot.anchor_to_inlay_offset(search_range.start)
|
||||
..display_snapshot.anchor_to_inlay_offset(search_range.end);
|
||||
let mut results = Vec::new();
|
||||
let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
|
||||
return vec![];
|
||||
};
|
||||
|
||||
let start_ix = match ranges.binary_search_by(|probe| {
|
||||
let cmp = document_to_inlay_range(probe, display_snapshot)
|
||||
let cmp = probe
|
||||
.end
|
||||
.cmp(&search_range.start);
|
||||
.cmp(&search_range.start, &display_snapshot.buffer_snapshot);
|
||||
if cmp.is_gt() {
|
||||
Ordering::Greater
|
||||
} else {
|
||||
@@ -7989,22 +7968,20 @@ impl Editor {
|
||||
return Vec::new();
|
||||
}
|
||||
for range in &ranges[start_ix..] {
|
||||
let range = document_to_inlay_range(range, display_snapshot);
|
||||
if range.start.cmp(&search_range.end).is_ge() {
|
||||
if range
|
||||
.start
|
||||
.cmp(&search_range.end, &display_snapshot.buffer_snapshot)
|
||||
.is_ge()
|
||||
{
|
||||
break;
|
||||
}
|
||||
let end = display_snapshot
|
||||
.inlay_offset_to_display_point(range.end, Bias::Right)
|
||||
.to_point(display_snapshot);
|
||||
let end = range.end.to_point(&display_snapshot.buffer_snapshot);
|
||||
if let Some(current_row) = &end_row {
|
||||
if end.row == current_row.row {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let start = display_snapshot
|
||||
.inlay_offset_to_display_point(range.start, Bias::Left)
|
||||
.to_point(display_snapshot);
|
||||
|
||||
let start = range.start.to_point(&display_snapshot.buffer_snapshot);
|
||||
if start_row.is_none() {
|
||||
assert_eq!(end_row, None);
|
||||
start_row = Some(start);
|
||||
@@ -8043,12 +8020,12 @@ impl Editor {
|
||||
|
||||
pub fn highlight_inlays<T: 'static>(
|
||||
&mut self,
|
||||
ranges: Vec<InlayRange>,
|
||||
highlights: Vec<InlayHighlight>,
|
||||
style: HighlightStyle,
|
||||
cx: &mut ViewContext<Self>,
|
||||
) {
|
||||
self.display_map.update(cx, |map, _| {
|
||||
map.highlight_inlays(TypeId::of::<T>(), ranges, style)
|
||||
map.highlight_inlays(TypeId::of::<T>(), highlights, style)
|
||||
});
|
||||
cx.notify();
|
||||
}
|
||||
@@ -8056,15 +8033,15 @@ impl Editor {
|
||||
pub fn text_highlights<'a, T: 'static>(
|
||||
&'a self,
|
||||
cx: &'a AppContext,
|
||||
) -> Option<(HighlightStyle, &'a [DocumentRange])> {
|
||||
) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
|
||||
self.display_map.read(cx).text_highlights(TypeId::of::<T>())
|
||||
}
|
||||
|
||||
pub fn clear_text_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
|
||||
let text_highlights = self
|
||||
pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
|
||||
let cleared = self
|
||||
.display_map
|
||||
.update(cx, |map, _| map.clear_text_highlights(TypeId::of::<T>()));
|
||||
if text_highlights.is_some() {
|
||||
.update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
|
||||
if cleared {
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
@@ -8281,7 +8258,6 @@ impl Editor {
|
||||
Some(
|
||||
ranges
|
||||
.iter()
|
||||
.filter_map(|range| range.as_text_range())
|
||||
.map(move |range| {
|
||||
range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
|
||||
})
|
||||
@@ -8496,19 +8472,6 @@ impl Editor {
|
||||
}
|
||||
}
|
||||
|
||||
fn document_to_inlay_range(
|
||||
range: &DocumentRange,
|
||||
snapshot: &DisplaySnapshot,
|
||||
) -> Range<InlayOffset> {
|
||||
match range {
|
||||
DocumentRange::Text(text_range) => {
|
||||
snapshot.anchor_to_inlay_offset(text_range.start)
|
||||
..snapshot.anchor_to_inlay_offset(text_range.end)
|
||||
}
|
||||
DocumentRange::Inlay(inlay_range) => inlay_range.highlight_start..inlay_range.highlight_end,
|
||||
}
|
||||
}
|
||||
|
||||
fn inlay_hint_settings(
|
||||
location: Anchor,
|
||||
snapshot: &MultiBufferSnapshot,
|
||||
@@ -8719,7 +8682,7 @@ impl View for Editor {
|
||||
|
||||
self.link_go_to_definition_state.task = None;
|
||||
|
||||
self.clear_text_highlights::<LinkGoToDefinitionState>(cx);
|
||||
self.clear_highlights::<LinkGoToDefinitionState>(cx);
|
||||
}
|
||||
|
||||
false
|
||||
@@ -8788,12 +8751,11 @@ impl View for Editor {
|
||||
fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
|
||||
let snapshot = self.buffer.read(cx).read(cx);
|
||||
let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
|
||||
let range = range.as_text_range()?;
|
||||
Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
|
||||
}
|
||||
|
||||
fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
|
||||
self.clear_text_highlights::<InputComposition>(cx);
|
||||
self.clear_highlights::<InputComposition>(cx);
|
||||
self.ime_transaction.take();
|
||||
}
|
||||
|
||||
|
||||
@@ -1735,7 +1735,7 @@ impl EditorElement {
|
||||
enum JumpIcon {}
|
||||
MouseEventHandler::new::<JumpIcon, _>((*id).into(), cx, |state, _| {
|
||||
let style = style.jump_icon.style_for(state);
|
||||
Svg::new("icons/arrow_up_right_8.svg")
|
||||
Svg::new("icons/arrow_up_right.svg")
|
||||
.with_color(style.color)
|
||||
.constrained()
|
||||
.with_width(style.icon_width)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
display_map::{InlayOffset, ToDisplayPoint},
|
||||
link_go_to_definition::{DocumentRange, InlayRange},
|
||||
link_go_to_definition::{InlayHighlight, RangeInEditor},
|
||||
Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSettings, EditorSnapshot, EditorStyle,
|
||||
ExcerptId, RangeToAnchorExt,
|
||||
};
|
||||
@@ -50,19 +50,18 @@ pub fn hover_at(editor: &mut Editor, point: Option<DisplayPoint>, cx: &mut ViewC
|
||||
|
||||
pub struct InlayHover {
|
||||
pub excerpt: ExcerptId,
|
||||
pub triggered_from: InlayOffset,
|
||||
pub range: InlayRange,
|
||||
pub range: InlayHighlight,
|
||||
pub tooltip: HoverBlock,
|
||||
}
|
||||
|
||||
pub fn find_hovered_hint_part(
|
||||
label_parts: Vec<InlayHintLabelPart>,
|
||||
hint_range: Range<InlayOffset>,
|
||||
hint_start: InlayOffset,
|
||||
hovered_offset: InlayOffset,
|
||||
) -> Option<(InlayHintLabelPart, Range<InlayOffset>)> {
|
||||
if hovered_offset >= hint_range.start && hovered_offset <= hint_range.end {
|
||||
let mut hovered_character = (hovered_offset - hint_range.start).0;
|
||||
let mut part_start = hint_range.start;
|
||||
if hovered_offset >= hint_start {
|
||||
let mut hovered_character = (hovered_offset - hint_start).0;
|
||||
let mut part_start = hint_start;
|
||||
for part in label_parts {
|
||||
let part_len = part.value.chars().count();
|
||||
if hovered_character > part_len {
|
||||
@@ -88,10 +87,8 @@ pub fn hover_at_inlay(editor: &mut Editor, inlay_hover: InlayHover, cx: &mut Vie
|
||||
};
|
||||
|
||||
if let Some(InfoPopover { symbol_range, .. }) = &editor.hover_state.info_popover {
|
||||
if let DocumentRange::Inlay(range) = symbol_range {
|
||||
if (range.highlight_start..range.highlight_end)
|
||||
.contains(&inlay_hover.triggered_from)
|
||||
{
|
||||
if let RangeInEditor::Inlay(range) = symbol_range {
|
||||
if range == &inlay_hover.range {
|
||||
// Hover triggered from same location as last time. Don't show again.
|
||||
return;
|
||||
}
|
||||
@@ -99,18 +96,6 @@ pub fn hover_at_inlay(editor: &mut Editor, inlay_hover: InlayHover, cx: &mut Vie
|
||||
hide_hover(editor, cx);
|
||||
}
|
||||
|
||||
let snapshot = editor.snapshot(cx);
|
||||
// Don't request again if the location is the same as the previous request
|
||||
if let Some(triggered_from) = editor.hover_state.triggered_from {
|
||||
if inlay_hover.triggered_from
|
||||
== snapshot
|
||||
.display_snapshot
|
||||
.anchor_to_inlay_offset(triggered_from)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let task = cx.spawn(|this, mut cx| {
|
||||
async move {
|
||||
cx.background()
|
||||
@@ -122,7 +107,7 @@ pub fn hover_at_inlay(editor: &mut Editor, inlay_hover: InlayHover, cx: &mut Vie
|
||||
|
||||
let hover_popover = InfoPopover {
|
||||
project: project.clone(),
|
||||
symbol_range: DocumentRange::Inlay(inlay_hover.range),
|
||||
symbol_range: RangeInEditor::Inlay(inlay_hover.range.clone()),
|
||||
blocks: vec![inlay_hover.tooltip],
|
||||
language: None,
|
||||
rendered_content: None,
|
||||
@@ -326,7 +311,7 @@ fn show_hover(
|
||||
|
||||
Some(InfoPopover {
|
||||
project: project.clone(),
|
||||
symbol_range: DocumentRange::Text(range),
|
||||
symbol_range: RangeInEditor::Text(range),
|
||||
blocks: hover_result.contents,
|
||||
language: hover_result.language,
|
||||
rendered_content: None,
|
||||
@@ -608,8 +593,8 @@ impl HoverState {
|
||||
self.info_popover
|
||||
.as_ref()
|
||||
.map(|info_popover| match &info_popover.symbol_range {
|
||||
DocumentRange::Text(range) => &range.start,
|
||||
DocumentRange::Inlay(range) => &range.inlay_position,
|
||||
RangeInEditor::Text(range) => &range.start,
|
||||
RangeInEditor::Inlay(range) => &range.inlay_position,
|
||||
})
|
||||
})?;
|
||||
let point = anchor.to_display_point(&snapshot.display_snapshot);
|
||||
@@ -635,7 +620,7 @@ impl HoverState {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct InfoPopover {
|
||||
pub project: ModelHandle<Project>,
|
||||
symbol_range: DocumentRange,
|
||||
symbol_range: RangeInEditor,
|
||||
pub blocks: Vec<HoverBlock>,
|
||||
language: Option<Arc<Language>>,
|
||||
rendered_content: Option<RenderedInfo>,
|
||||
@@ -811,6 +796,7 @@ mod tests {
|
||||
inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
|
||||
link_go_to_definition::update_inlay_link_and_hover_points,
|
||||
test::editor_lsp_test_context::EditorLspTestContext,
|
||||
InlayId,
|
||||
};
|
||||
use collections::BTreeSet;
|
||||
use gpui::fonts::Weight;
|
||||
@@ -1477,25 +1463,16 @@ mod tests {
|
||||
.advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
|
||||
cx.foreground().run_until_parked();
|
||||
cx.update_editor(|editor, cx| {
|
||||
let snapshot = editor.snapshot(cx);
|
||||
let hover_state = &editor.hover_state;
|
||||
assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
|
||||
let popover = hover_state.info_popover.as_ref().unwrap();
|
||||
let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
|
||||
let entire_inlay_start = snapshot.display_point_to_inlay_offset(
|
||||
inlay_range.start.to_display_point(&snapshot),
|
||||
Bias::Left,
|
||||
);
|
||||
|
||||
let expected_new_type_label_start = InlayOffset(entire_inlay_start.0 + ": ".len());
|
||||
assert_eq!(
|
||||
popover.symbol_range,
|
||||
DocumentRange::Inlay(InlayRange {
|
||||
RangeInEditor::Inlay(InlayHighlight {
|
||||
inlay: InlayId::Hint(0),
|
||||
inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
|
||||
highlight_start: expected_new_type_label_start,
|
||||
highlight_end: InlayOffset(
|
||||
expected_new_type_label_start.0 + new_type_label.len()
|
||||
),
|
||||
range: ": ".len()..": ".len() + new_type_label.len(),
|
||||
}),
|
||||
"Popover range should match the new type label part"
|
||||
);
|
||||
@@ -1543,23 +1520,17 @@ mod tests {
|
||||
.advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
|
||||
cx.foreground().run_until_parked();
|
||||
cx.update_editor(|editor, cx| {
|
||||
let snapshot = editor.snapshot(cx);
|
||||
let hover_state = &editor.hover_state;
|
||||
assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
|
||||
let popover = hover_state.info_popover.as_ref().unwrap();
|
||||
let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
|
||||
let entire_inlay_start = snapshot.display_point_to_inlay_offset(
|
||||
inlay_range.start.to_display_point(&snapshot),
|
||||
Bias::Left,
|
||||
);
|
||||
let expected_struct_label_start =
|
||||
InlayOffset(entire_inlay_start.0 + ": ".len() + new_type_label.len() + "<".len());
|
||||
assert_eq!(
|
||||
popover.symbol_range,
|
||||
DocumentRange::Inlay(InlayRange {
|
||||
RangeInEditor::Inlay(InlayHighlight {
|
||||
inlay: InlayId::Hint(0),
|
||||
inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
|
||||
highlight_start: expected_struct_label_start,
|
||||
highlight_end: InlayOffset(expected_struct_label_start.0 + struct_label.len()),
|
||||
range: ": ".len() + new_type_label.len() + "<".len()
|
||||
..": ".len() + new_type_label.len() + "<".len() + struct_label.len(),
|
||||
}),
|
||||
"Popover range should match the struct label part"
|
||||
);
|
||||
|
||||
@@ -43,7 +43,8 @@ pub struct CachedExcerptHints {
|
||||
version: usize,
|
||||
buffer_version: Global,
|
||||
buffer_id: u64,
|
||||
hints: Vec<(InlayId, InlayHint)>,
|
||||
ordered_hints: Vec<InlayId>,
|
||||
hints_by_id: HashMap<InlayId, InlayHint>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -316,7 +317,7 @@ impl InlayHintCache {
|
||||
self.hints.retain(|cached_excerpt, cached_hints| {
|
||||
let retain = excerpts_to_query.contains_key(cached_excerpt);
|
||||
if !retain {
|
||||
invalidated_hints.extend(cached_hints.read().hints.iter().map(|&(id, _)| id));
|
||||
invalidated_hints.extend(cached_hints.read().ordered_hints.iter().copied());
|
||||
}
|
||||
retain
|
||||
});
|
||||
@@ -384,7 +385,7 @@ impl InlayHintCache {
|
||||
let shown_excerpt_hints_to_remove =
|
||||
shown_hints_to_remove.entry(*excerpt_id).or_default();
|
||||
let excerpt_cached_hints = excerpt_cached_hints.read();
|
||||
let mut excerpt_cache = excerpt_cached_hints.hints.iter().fuse().peekable();
|
||||
let mut excerpt_cache = excerpt_cached_hints.ordered_hints.iter().fuse().peekable();
|
||||
shown_excerpt_hints_to_remove.retain(|(shown_anchor, shown_hint_id)| {
|
||||
let Some(buffer) = shown_anchor
|
||||
.buffer_id
|
||||
@@ -395,7 +396,8 @@ impl InlayHintCache {
|
||||
let buffer_snapshot = buffer.read(cx).snapshot();
|
||||
loop {
|
||||
match excerpt_cache.peek() {
|
||||
Some((cached_hint_id, cached_hint)) => {
|
||||
Some(&cached_hint_id) => {
|
||||
let cached_hint = &excerpt_cached_hints.hints_by_id[cached_hint_id];
|
||||
if cached_hint_id == shown_hint_id {
|
||||
excerpt_cache.next();
|
||||
return !new_kinds.contains(&cached_hint.kind);
|
||||
@@ -428,7 +430,8 @@ impl InlayHintCache {
|
||||
}
|
||||
});
|
||||
|
||||
for (cached_hint_id, maybe_missed_cached_hint) in excerpt_cache {
|
||||
for cached_hint_id in excerpt_cache {
|
||||
let maybe_missed_cached_hint = &excerpt_cached_hints.hints_by_id[cached_hint_id];
|
||||
let cached_hint_kind = maybe_missed_cached_hint.kind;
|
||||
if !old_kinds.contains(&cached_hint_kind) && new_kinds.contains(&cached_hint_kind) {
|
||||
to_insert.push(Inlay::hint(
|
||||
@@ -463,7 +466,7 @@ impl InlayHintCache {
|
||||
self.update_tasks.remove(&excerpt_to_remove);
|
||||
if let Some(cached_hints) = self.hints.remove(&excerpt_to_remove) {
|
||||
let cached_hints = cached_hints.read();
|
||||
to_remove.extend(cached_hints.hints.iter().map(|(id, _)| *id));
|
||||
to_remove.extend(cached_hints.ordered_hints.iter().copied());
|
||||
}
|
||||
}
|
||||
if to_remove.is_empty() {
|
||||
@@ -489,10 +492,8 @@ impl InlayHintCache {
|
||||
self.hints
|
||||
.get(&excerpt_id)?
|
||||
.read()
|
||||
.hints
|
||||
.iter()
|
||||
.find(|&(id, _)| id == &hint_id)
|
||||
.map(|(_, hint)| hint)
|
||||
.hints_by_id
|
||||
.get(&hint_id)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
@@ -500,7 +501,13 @@ impl InlayHintCache {
|
||||
let mut hints = Vec::new();
|
||||
for excerpt_hints in self.hints.values() {
|
||||
let excerpt_hints = excerpt_hints.read();
|
||||
hints.extend(excerpt_hints.hints.iter().map(|(_, hint)| hint).cloned());
|
||||
hints.extend(
|
||||
excerpt_hints
|
||||
.ordered_hints
|
||||
.iter()
|
||||
.map(|id| &excerpt_hints.hints_by_id[id])
|
||||
.cloned(),
|
||||
);
|
||||
}
|
||||
hints
|
||||
}
|
||||
@@ -518,12 +525,7 @@ impl InlayHintCache {
|
||||
) {
|
||||
if let Some(excerpt_hints) = self.hints.get(&excerpt_id) {
|
||||
let mut guard = excerpt_hints.write();
|
||||
if let Some(cached_hint) = guard
|
||||
.hints
|
||||
.iter_mut()
|
||||
.find(|(hint_id, _)| hint_id == &id)
|
||||
.map(|(_, hint)| hint)
|
||||
{
|
||||
if let Some(cached_hint) = guard.hints_by_id.get_mut(&id) {
|
||||
if let ResolveState::CanResolve(server_id, _) = &cached_hint.resolve_state {
|
||||
let hint_to_resolve = cached_hint.clone();
|
||||
let server_id = *server_id;
|
||||
@@ -555,12 +557,7 @@ impl InlayHintCache {
|
||||
editor.inlay_hint_cache.hints.get(&excerpt_id)
|
||||
{
|
||||
let mut guard = excerpt_hints.write();
|
||||
if let Some(cached_hint) = guard
|
||||
.hints
|
||||
.iter_mut()
|
||||
.find(|(hint_id, _)| hint_id == &id)
|
||||
.map(|(_, hint)| hint)
|
||||
{
|
||||
if let Some(cached_hint) = guard.hints_by_id.get_mut(&id) {
|
||||
if cached_hint.resolve_state == ResolveState::Resolving {
|
||||
resolved_hint.resolve_state = ResolveState::Resolved;
|
||||
*cached_hint = resolved_hint;
|
||||
@@ -986,12 +983,17 @@ fn calculate_hint_updates(
|
||||
let missing_from_cache = match &cached_excerpt_hints {
|
||||
Some(cached_excerpt_hints) => {
|
||||
let cached_excerpt_hints = cached_excerpt_hints.read();
|
||||
match cached_excerpt_hints.hints.binary_search_by(|probe| {
|
||||
probe.1.position.cmp(&new_hint.position, buffer_snapshot)
|
||||
}) {
|
||||
match cached_excerpt_hints
|
||||
.ordered_hints
|
||||
.binary_search_by(|probe| {
|
||||
cached_excerpt_hints.hints_by_id[probe]
|
||||
.position
|
||||
.cmp(&new_hint.position, buffer_snapshot)
|
||||
}) {
|
||||
Ok(ix) => {
|
||||
let mut missing_from_cache = true;
|
||||
for (cached_inlay_id, cached_hint) in &cached_excerpt_hints.hints[ix..] {
|
||||
for id in &cached_excerpt_hints.ordered_hints[ix..] {
|
||||
let cached_hint = &cached_excerpt_hints.hints_by_id[id];
|
||||
if new_hint
|
||||
.position
|
||||
.cmp(&cached_hint.position, buffer_snapshot)
|
||||
@@ -1000,7 +1002,7 @@ fn calculate_hint_updates(
|
||||
break;
|
||||
}
|
||||
if cached_hint == &new_hint {
|
||||
excerpt_hints_to_persist.insert(*cached_inlay_id, cached_hint.kind);
|
||||
excerpt_hints_to_persist.insert(*id, cached_hint.kind);
|
||||
missing_from_cache = false;
|
||||
}
|
||||
}
|
||||
@@ -1031,12 +1033,12 @@ fn calculate_hint_updates(
|
||||
let cached_excerpt_hints = cached_excerpt_hints.read();
|
||||
remove_from_cache.extend(
|
||||
cached_excerpt_hints
|
||||
.hints
|
||||
.ordered_hints
|
||||
.iter()
|
||||
.filter(|(cached_inlay_id, _)| {
|
||||
.filter(|cached_inlay_id| {
|
||||
!excerpt_hints_to_persist.contains_key(cached_inlay_id)
|
||||
})
|
||||
.map(|(cached_inlay_id, _)| *cached_inlay_id),
|
||||
.copied(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1080,7 +1082,8 @@ fn apply_hint_update(
|
||||
version: query.cache_version,
|
||||
buffer_version: buffer_snapshot.version().clone(),
|
||||
buffer_id: query.buffer_id,
|
||||
hints: Vec::new(),
|
||||
ordered_hints: Vec::new(),
|
||||
hints_by_id: HashMap::default(),
|
||||
}))
|
||||
});
|
||||
let mut cached_excerpt_hints = cached_excerpt_hints.write();
|
||||
@@ -1093,20 +1096,27 @@ fn apply_hint_update(
|
||||
|
||||
let mut cached_inlays_changed = !new_update.remove_from_cache.is_empty();
|
||||
cached_excerpt_hints
|
||||
.hints
|
||||
.retain(|(hint_id, _)| !new_update.remove_from_cache.contains(hint_id));
|
||||
.ordered_hints
|
||||
.retain(|hint_id| !new_update.remove_from_cache.contains(hint_id));
|
||||
cached_excerpt_hints
|
||||
.hints_by_id
|
||||
.retain(|hint_id, _| !new_update.remove_from_cache.contains(hint_id));
|
||||
let mut splice = InlaySplice {
|
||||
to_remove: new_update.remove_from_visible,
|
||||
to_insert: Vec::new(),
|
||||
};
|
||||
for new_hint in new_update.add_to_cache {
|
||||
let cached_hints = &mut cached_excerpt_hints.hints;
|
||||
let insert_position = match cached_hints
|
||||
.binary_search_by(|probe| probe.1.position.cmp(&new_hint.position, &buffer_snapshot))
|
||||
{
|
||||
let insert_position = match cached_excerpt_hints
|
||||
.ordered_hints
|
||||
.binary_search_by(|probe| {
|
||||
cached_excerpt_hints.hints_by_id[probe]
|
||||
.position
|
||||
.cmp(&new_hint.position, &buffer_snapshot)
|
||||
}) {
|
||||
Ok(i) => {
|
||||
let mut insert_position = Some(i);
|
||||
for (_, cached_hint) in &cached_hints[i..] {
|
||||
for id in &cached_excerpt_hints.ordered_hints[i..] {
|
||||
let cached_hint = &cached_excerpt_hints.hints_by_id[id];
|
||||
if new_hint
|
||||
.position
|
||||
.cmp(&cached_hint.position, &buffer_snapshot)
|
||||
@@ -1137,7 +1147,11 @@ fn apply_hint_update(
|
||||
.to_insert
|
||||
.push(Inlay::hint(new_inlay_id, new_hint_position, &new_hint));
|
||||
}
|
||||
cached_hints.insert(insert_position, (InlayId::Hint(new_inlay_id), new_hint));
|
||||
let new_id = InlayId::Hint(new_inlay_id);
|
||||
cached_excerpt_hints.hints_by_id.insert(new_id, new_hint);
|
||||
cached_excerpt_hints
|
||||
.ordered_hints
|
||||
.insert(insert_position, new_id);
|
||||
cached_inlays_changed = true;
|
||||
}
|
||||
}
|
||||
@@ -1157,7 +1171,7 @@ fn apply_hint_update(
|
||||
outdated_excerpt_caches.insert(*excerpt_id);
|
||||
splice
|
||||
.to_remove
|
||||
.extend(excerpt_hints.hints.iter().map(|(id, _)| id));
|
||||
.extend(excerpt_hints.ordered_hints.iter().copied());
|
||||
}
|
||||
}
|
||||
cached_inlays_changed |= !outdated_excerpt_caches.is_empty();
|
||||
@@ -3311,8 +3325,9 @@ all hints should be invalidated and requeried for all of its visible excerpts"
|
||||
pub fn cached_hint_labels(editor: &Editor) -> Vec<String> {
|
||||
let mut labels = Vec::new();
|
||||
for (_, excerpt_hints) in &editor.inlay_hint_cache().hints {
|
||||
for (_, inlay) in &excerpt_hints.read().hints {
|
||||
labels.push(inlay.text());
|
||||
let excerpt_hints = excerpt_hints.read();
|
||||
for id in &excerpt_hints.ordered_hints {
|
||||
labels.push(excerpt_hints.hints_by_id[id].text());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::{
|
||||
display_map::{DisplaySnapshot, InlayOffset},
|
||||
display_map::DisplaySnapshot,
|
||||
element::PointForPosition,
|
||||
hover_popover::{self, InlayHover},
|
||||
Anchor, DisplayPoint, Editor, EditorSnapshot, SelectPhase,
|
||||
Anchor, DisplayPoint, Editor, EditorSnapshot, InlayId, SelectPhase,
|
||||
};
|
||||
use gpui::{Task, ViewContext};
|
||||
use language::{Bias, ToOffset};
|
||||
@@ -17,44 +17,19 @@ use util::TryFutureExt;
|
||||
#[derive(Debug, Default)]
|
||||
pub struct LinkGoToDefinitionState {
|
||||
pub last_trigger_point: Option<TriggerPoint>,
|
||||
pub symbol_range: Option<DocumentRange>,
|
||||
pub symbol_range: Option<RangeInEditor>,
|
||||
pub kind: Option<LinkDefinitionKind>,
|
||||
pub definitions: Vec<GoToDefinitionLink>,
|
||||
pub task: Option<Task<Option<()>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum GoToDefinitionTrigger {
|
||||
Text(DisplayPoint),
|
||||
InlayHint(InlayRange, lsp::Location, LanguageServerId),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum GoToDefinitionLink {
|
||||
Text(LocationLink),
|
||||
InlayHint(lsp::Location, LanguageServerId),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct InlayRange {
|
||||
pub inlay_position: Anchor,
|
||||
pub highlight_start: InlayOffset,
|
||||
pub highlight_end: InlayOffset,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TriggerPoint {
|
||||
Text(Anchor),
|
||||
InlayHint(InlayRange, lsp::Location, LanguageServerId),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DocumentRange {
|
||||
#[derive(Debug, Eq, PartialEq, Clone)]
|
||||
pub enum RangeInEditor {
|
||||
Text(Range<Anchor>),
|
||||
Inlay(InlayRange),
|
||||
Inlay(InlayHighlight),
|
||||
}
|
||||
|
||||
impl DocumentRange {
|
||||
impl RangeInEditor {
|
||||
pub fn as_text_range(&self) -> Option<Range<Anchor>> {
|
||||
match self {
|
||||
Self::Text(range) => Some(range.clone()),
|
||||
@@ -64,28 +39,47 @@ impl DocumentRange {
|
||||
|
||||
fn point_within_range(&self, trigger_point: &TriggerPoint, snapshot: &EditorSnapshot) -> bool {
|
||||
match (self, trigger_point) {
|
||||
(DocumentRange::Text(range), TriggerPoint::Text(point)) => {
|
||||
(Self::Text(range), TriggerPoint::Text(point)) => {
|
||||
let point_after_start = range.start.cmp(point, &snapshot.buffer_snapshot).is_le();
|
||||
point_after_start && range.end.cmp(point, &snapshot.buffer_snapshot).is_ge()
|
||||
}
|
||||
(DocumentRange::Inlay(range), TriggerPoint::InlayHint(point, _, _)) => {
|
||||
range.highlight_start.cmp(&point.highlight_end).is_le()
|
||||
&& range.highlight_end.cmp(&point.highlight_end).is_ge()
|
||||
(Self::Inlay(highlight), TriggerPoint::InlayHint(point, _, _)) => {
|
||||
highlight.inlay == point.inlay
|
||||
&& highlight.range.contains(&point.range.start)
|
||||
&& highlight.range.contains(&point.range.end)
|
||||
}
|
||||
(DocumentRange::Inlay(_), TriggerPoint::Text(_))
|
||||
| (DocumentRange::Text(_), TriggerPoint::InlayHint(_, _, _)) => false,
|
||||
(Self::Inlay(_), TriggerPoint::Text(_))
|
||||
| (Self::Text(_), TriggerPoint::InlayHint(_, _, _)) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TriggerPoint {
|
||||
fn anchor(&self) -> &Anchor {
|
||||
match self {
|
||||
TriggerPoint::Text(anchor) => anchor,
|
||||
TriggerPoint::InlayHint(range, _, _) => &range.inlay_position,
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub enum GoToDefinitionTrigger {
|
||||
Text(DisplayPoint),
|
||||
InlayHint(InlayHighlight, lsp::Location, LanguageServerId),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum GoToDefinitionLink {
|
||||
Text(LocationLink),
|
||||
InlayHint(lsp::Location, LanguageServerId),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InlayHighlight {
|
||||
pub inlay: InlayId,
|
||||
pub inlay_position: Anchor,
|
||||
pub range: Range<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TriggerPoint {
|
||||
Text(Anchor),
|
||||
InlayHint(InlayHighlight, lsp::Location, LanguageServerId),
|
||||
}
|
||||
|
||||
impl TriggerPoint {
|
||||
pub fn definition_kind(&self, shift: bool) -> LinkDefinitionKind {
|
||||
match self {
|
||||
TriggerPoint::Text(_) => {
|
||||
@@ -98,6 +92,13 @@ impl TriggerPoint {
|
||||
TriggerPoint::InlayHint(_, _, _) => LinkDefinitionKind::Type,
|
||||
}
|
||||
}
|
||||
|
||||
fn anchor(&self) -> &Anchor {
|
||||
match self {
|
||||
TriggerPoint::Text(anchor) => anchor,
|
||||
TriggerPoint::InlayHint(inlay_range, _, _) => &inlay_range.inlay_position,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_go_to_definition_link(
|
||||
@@ -135,11 +136,7 @@ pub fn update_go_to_definition_link(
|
||||
}
|
||||
}
|
||||
(TriggerPoint::InlayHint(range_a, _, _), TriggerPoint::InlayHint(range_b, _, _)) => {
|
||||
if range_a
|
||||
.inlay_position
|
||||
.cmp(&range_b.inlay_position, &snapshot.buffer_snapshot)
|
||||
.is_eq()
|
||||
{
|
||||
if range_a == range_b {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -173,10 +170,6 @@ pub fn update_inlay_link_and_hover_points(
|
||||
shift_held: bool,
|
||||
cx: &mut ViewContext<'_, '_, Editor>,
|
||||
) {
|
||||
let hint_start_offset =
|
||||
snapshot.display_point_to_inlay_offset(point_for_position.previous_valid, Bias::Left);
|
||||
let hint_end_offset =
|
||||
snapshot.display_point_to_inlay_offset(point_for_position.next_valid, Bias::Right);
|
||||
let hovered_offset = if point_for_position.column_overshoot_after_line_end == 0 {
|
||||
Some(snapshot.display_point_to_inlay_offset(point_for_position.exact_unclipped, Bias::Left))
|
||||
} else {
|
||||
@@ -224,15 +217,14 @@ pub fn update_inlay_link_and_hover_points(
|
||||
}
|
||||
}
|
||||
ResolveState::Resolved => {
|
||||
let mut actual_hint_start = hint_start_offset;
|
||||
let mut actual_hint_end = hint_end_offset;
|
||||
let mut extra_shift_left = 0;
|
||||
let mut extra_shift_right = 0;
|
||||
if cached_hint.padding_left {
|
||||
actual_hint_start.0 += 1;
|
||||
actual_hint_end.0 += 1;
|
||||
extra_shift_left += 1;
|
||||
extra_shift_right += 1;
|
||||
}
|
||||
if cached_hint.padding_right {
|
||||
actual_hint_start.0 += 1;
|
||||
actual_hint_end.0 += 1;
|
||||
extra_shift_right += 1;
|
||||
}
|
||||
match cached_hint.label {
|
||||
project::InlayHintLabel::String(_) => {
|
||||
@@ -253,11 +245,11 @@ pub fn update_inlay_link_and_hover_points(
|
||||
}
|
||||
}
|
||||
},
|
||||
triggered_from: hovered_offset,
|
||||
range: InlayRange {
|
||||
range: InlayHighlight {
|
||||
inlay: hovered_hint.id,
|
||||
inlay_position: hovered_hint.position,
|
||||
highlight_start: actual_hint_start,
|
||||
highlight_end: actual_hint_end,
|
||||
range: extra_shift_left
|
||||
..hovered_hint.text.len() + extra_shift_right,
|
||||
},
|
||||
},
|
||||
cx,
|
||||
@@ -266,13 +258,24 @@ pub fn update_inlay_link_and_hover_points(
|
||||
}
|
||||
}
|
||||
project::InlayHintLabel::LabelParts(label_parts) => {
|
||||
let hint_start =
|
||||
snapshot.anchor_to_inlay_offset(hovered_hint.position);
|
||||
if let Some((hovered_hint_part, part_range)) =
|
||||
hover_popover::find_hovered_hint_part(
|
||||
label_parts,
|
||||
actual_hint_start..actual_hint_end,
|
||||
hint_start,
|
||||
hovered_offset,
|
||||
)
|
||||
{
|
||||
let highlight_start =
|
||||
(part_range.start - hint_start).0 + extra_shift_left;
|
||||
let highlight_end =
|
||||
(part_range.end - hint_start).0 + extra_shift_right;
|
||||
let highlight = InlayHighlight {
|
||||
inlay: hovered_hint.id,
|
||||
inlay_position: hovered_hint.position,
|
||||
range: highlight_start..highlight_end,
|
||||
};
|
||||
if let Some(tooltip) = hovered_hint_part.tooltip {
|
||||
hover_popover::hover_at_inlay(
|
||||
editor,
|
||||
@@ -292,12 +295,7 @@ pub fn update_inlay_link_and_hover_points(
|
||||
kind: content.kind,
|
||||
},
|
||||
},
|
||||
triggered_from: hovered_offset,
|
||||
range: InlayRange {
|
||||
inlay_position: hovered_hint.position,
|
||||
highlight_start: part_range.start,
|
||||
highlight_end: part_range.end,
|
||||
},
|
||||
range: highlight.clone(),
|
||||
},
|
||||
cx,
|
||||
);
|
||||
@@ -310,11 +308,7 @@ pub fn update_inlay_link_and_hover_points(
|
||||
update_go_to_definition_link(
|
||||
editor,
|
||||
Some(GoToDefinitionTrigger::InlayHint(
|
||||
InlayRange {
|
||||
inlay_position: hovered_hint.position,
|
||||
highlight_start: part_range.start,
|
||||
highlight_end: part_range.end,
|
||||
},
|
||||
highlight,
|
||||
location,
|
||||
language_server_id,
|
||||
)),
|
||||
@@ -425,7 +419,7 @@ pub fn show_link_definition(
|
||||
let end = snapshot
|
||||
.buffer_snapshot
|
||||
.anchor_in_excerpt(excerpt_id.clone(), origin.range.end);
|
||||
DocumentRange::Text(start..end)
|
||||
RangeInEditor::Text(start..end)
|
||||
})
|
||||
}),
|
||||
definition_result
|
||||
@@ -435,8 +429,8 @@ pub fn show_link_definition(
|
||||
)
|
||||
})
|
||||
}
|
||||
TriggerPoint::InlayHint(trigger_source, lsp_location, server_id) => Some((
|
||||
Some(DocumentRange::Inlay(*trigger_source)),
|
||||
TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
|
||||
Some(RangeInEditor::Inlay(highlight.clone())),
|
||||
vec![GoToDefinitionLink::InlayHint(
|
||||
lsp_location.clone(),
|
||||
*server_id,
|
||||
@@ -446,7 +440,7 @@ pub fn show_link_definition(
|
||||
|
||||
this.update(&mut cx, |this, cx| {
|
||||
// Clear any existing highlights
|
||||
this.clear_text_highlights::<LinkGoToDefinitionState>(cx);
|
||||
this.clear_highlights::<LinkGoToDefinitionState>(cx);
|
||||
this.link_go_to_definition_state.kind = Some(definition_kind);
|
||||
this.link_go_to_definition_state.symbol_range = result
|
||||
.as_ref()
|
||||
@@ -498,26 +492,26 @@ pub fn show_link_definition(
|
||||
// If no symbol range returned from language server, use the surrounding word.
|
||||
let (offset_range, _) =
|
||||
snapshot.surrounding_word(*trigger_anchor);
|
||||
DocumentRange::Text(
|
||||
RangeInEditor::Text(
|
||||
snapshot.anchor_before(offset_range.start)
|
||||
..snapshot.anchor_after(offset_range.end),
|
||||
)
|
||||
}
|
||||
TriggerPoint::InlayHint(inlay_coordinates, _, _) => {
|
||||
DocumentRange::Inlay(*inlay_coordinates)
|
||||
TriggerPoint::InlayHint(highlight, _, _) => {
|
||||
RangeInEditor::Inlay(highlight.clone())
|
||||
}
|
||||
});
|
||||
|
||||
match highlight_range {
|
||||
DocumentRange::Text(text_range) => this
|
||||
RangeInEditor::Text(text_range) => this
|
||||
.highlight_text::<LinkGoToDefinitionState>(
|
||||
vec![text_range],
|
||||
style,
|
||||
cx,
|
||||
),
|
||||
DocumentRange::Inlay(inlay_coordinates) => this
|
||||
RangeInEditor::Inlay(highlight) => this
|
||||
.highlight_inlays::<LinkGoToDefinitionState>(
|
||||
vec![inlay_coordinates],
|
||||
vec![highlight],
|
||||
style,
|
||||
cx,
|
||||
),
|
||||
@@ -547,7 +541,7 @@ pub fn hide_link_definition(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
|
||||
|
||||
editor.link_go_to_definition_state.task = None;
|
||||
|
||||
editor.clear_text_highlights::<LinkGoToDefinitionState>(cx);
|
||||
editor.clear_highlights::<LinkGoToDefinitionState>(cx);
|
||||
}
|
||||
|
||||
pub fn go_to_fetched_definition(
|
||||
@@ -1199,30 +1193,19 @@ mod tests {
|
||||
cx.foreground().run_until_parked();
|
||||
cx.update_editor(|editor, cx| {
|
||||
let snapshot = editor.snapshot(cx);
|
||||
let actual_ranges = snapshot
|
||||
.highlight_ranges::<LinkGoToDefinitionState>()
|
||||
.map(|ranges| ranges.as_ref().clone().1)
|
||||
.unwrap_or_default()
|
||||
let actual_highlights = snapshot
|
||||
.inlay_highlights::<LinkGoToDefinitionState>()
|
||||
.into_iter()
|
||||
.map(|range| match range {
|
||||
DocumentRange::Text(range) => {
|
||||
panic!("Unexpected regular text selection range {range:?}")
|
||||
}
|
||||
DocumentRange::Inlay(inlay_range) => inlay_range,
|
||||
})
|
||||
.flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
|
||||
let expected_highlight_start = snapshot.display_point_to_inlay_offset(
|
||||
inlay_range.start.to_display_point(&snapshot),
|
||||
Bias::Left,
|
||||
);
|
||||
let expected_ranges = vec![InlayRange {
|
||||
let expected_highlight = InlayHighlight {
|
||||
inlay: InlayId::Hint(0),
|
||||
inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
|
||||
highlight_start: expected_highlight_start,
|
||||
highlight_end: InlayOffset(expected_highlight_start.0 + hint_label.len()),
|
||||
}];
|
||||
assert_set_eq!(actual_ranges, expected_ranges);
|
||||
range: 0..hint_label.len(),
|
||||
};
|
||||
assert_set_eq!(actual_highlights, vec![&expected_highlight]);
|
||||
});
|
||||
|
||||
// Unpress cmd causes highlight to go away
|
||||
@@ -1242,17 +1225,9 @@ mod tests {
|
||||
cx.update_editor(|editor, cx| {
|
||||
let snapshot = editor.snapshot(cx);
|
||||
let actual_ranges = snapshot
|
||||
.highlight_ranges::<LinkGoToDefinitionState>()
|
||||
.text_highlight_ranges::<LinkGoToDefinitionState>()
|
||||
.map(|ranges| ranges.as_ref().clone().1)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|range| match range {
|
||||
DocumentRange::Text(range) => {
|
||||
panic!("Unexpected regular text selection range {range:?}")
|
||||
}
|
||||
DocumentRange::Inlay(inlay_range) => inlay_range,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
.unwrap_or_default();
|
||||
|
||||
assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
|
||||
});
|
||||
|
||||
@@ -225,7 +225,6 @@ impl<'a> EditorTestContext<'a> {
|
||||
.map(|h| h.1.clone())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|range| range.as_text_range())
|
||||
.map(|range| range.to_offset(&snapshot.buffer_snapshot))
|
||||
.collect()
|
||||
});
|
||||
@@ -237,11 +236,10 @@ impl<'a> EditorTestContext<'a> {
|
||||
let expected_ranges = self.ranges(marked_text);
|
||||
let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
|
||||
let actual_ranges: Vec<Range<usize>> = snapshot
|
||||
.highlight_ranges::<Tag>()
|
||||
.text_highlight_ranges::<Tag>()
|
||||
.map(|ranges| ranges.as_ref().clone().1)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|range| range.as_text_range())
|
||||
.map(|range| range.to_offset(&snapshot.buffer_snapshot))
|
||||
.collect();
|
||||
assert_set_eq!(actual_ranges, expected_ranges);
|
||||
|
||||
@@ -276,7 +276,7 @@ impl Item for FeedbackEditor {
|
||||
) -> AnyElement<T> {
|
||||
Flex::row()
|
||||
.with_child(
|
||||
Svg::new("icons/feedback_16.svg")
|
||||
Svg::new("icons/feedback.svg")
|
||||
.with_color(style.label.text.color)
|
||||
.constrained()
|
||||
.with_width(style.type_icon_width)
|
||||
|
||||
@@ -67,6 +67,7 @@ dhat = "0.3"
|
||||
env_logger.workspace = true
|
||||
png = "0.16"
|
||||
simplelog = "0.9"
|
||||
util = { path = "../util", features = ["test-support"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
media = { path = "../media" }
|
||||
|
||||
@@ -75,7 +75,6 @@ impl KeymapMatcher {
|
||||
keystroke: Keystroke,
|
||||
mut dispatch_path: Vec<(usize, KeymapContext)>,
|
||||
) -> MatchResult {
|
||||
let mut any_pending = false;
|
||||
// Collect matched bindings into an ordered list using the position in the matching binding first,
|
||||
// and then the order the binding matched in the view tree second.
|
||||
// The key is the reverse position of the binding in the bindings list so that later bindings
|
||||
@@ -84,7 +83,8 @@ impl KeymapMatcher {
|
||||
let no_action_id = (NoAction {}).id();
|
||||
|
||||
let first_keystroke = self.pending_keystrokes.is_empty();
|
||||
self.pending_keystrokes.push(keystroke.clone());
|
||||
let mut pending_key = None;
|
||||
let mut previous_keystrokes = self.pending_keystrokes.clone();
|
||||
|
||||
self.contexts.clear();
|
||||
self.contexts
|
||||
@@ -106,24 +106,32 @@ impl KeymapMatcher {
|
||||
}
|
||||
|
||||
for binding in self.keymap.bindings().iter().rev() {
|
||||
match binding.match_keys_and_context(&self.pending_keystrokes, &self.contexts[i..])
|
||||
{
|
||||
BindingMatchResult::Complete(action) => {
|
||||
if action.id() != no_action_id {
|
||||
matched_bindings.push((*view_id, action));
|
||||
for possibility in keystroke.match_possibilities() {
|
||||
previous_keystrokes.push(possibility.clone());
|
||||
match binding.match_keys_and_context(&previous_keystrokes, &self.contexts[i..])
|
||||
{
|
||||
BindingMatchResult::Complete(action) => {
|
||||
if action.id() != no_action_id {
|
||||
matched_bindings.push((*view_id, action));
|
||||
}
|
||||
}
|
||||
BindingMatchResult::Partial => {
|
||||
if pending_key == None || pending_key == Some(possibility.clone()) {
|
||||
self.pending_views
|
||||
.insert(*view_id, self.contexts[i].clone());
|
||||
pending_key = Some(possibility)
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
BindingMatchResult::Partial => {
|
||||
self.pending_views
|
||||
.insert(*view_id, self.contexts[i].clone());
|
||||
any_pending = true;
|
||||
}
|
||||
_ => {}
|
||||
previous_keystrokes.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !any_pending {
|
||||
if pending_key.is_some() {
|
||||
self.pending_keystrokes.push(pending_key.unwrap());
|
||||
} else {
|
||||
self.clear_pending();
|
||||
}
|
||||
|
||||
@@ -131,7 +139,7 @@ impl KeymapMatcher {
|
||||
// Collect the sorted matched bindings into the final vec for ease of use
|
||||
// Matched bindings are in order by precedence
|
||||
MatchResult::Matches(matched_bindings)
|
||||
} else if any_pending {
|
||||
} else if !self.pending_keystrokes.is_empty() {
|
||||
MatchResult::Pending
|
||||
} else {
|
||||
MatchResult::None
|
||||
@@ -340,6 +348,7 @@ mod tests {
|
||||
shift: false,
|
||||
cmd: false,
|
||||
function: false,
|
||||
ime_key: None,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -352,6 +361,7 @@ mod tests {
|
||||
shift: true,
|
||||
cmd: false,
|
||||
function: false,
|
||||
ime_key: None,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -364,6 +374,7 @@ mod tests {
|
||||
shift: true,
|
||||
cmd: true,
|
||||
function: false,
|
||||
ime_key: None,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -466,7 +477,7 @@ mod tests {
|
||||
#[derive(Clone, Deserialize, PartialEq, Eq, Debug)]
|
||||
pub struct A(pub String);
|
||||
impl_actions!(test, [A]);
|
||||
actions!(test, [B, Ab]);
|
||||
actions!(test, [B, Ab, Dollar, Quote, Ess, Backtick]);
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
struct ActionArg {
|
||||
@@ -477,6 +488,10 @@ mod tests {
|
||||
Binding::new("a", A("x".to_string()), Some("a")),
|
||||
Binding::new("b", B, Some("a")),
|
||||
Binding::new("a b", Ab, Some("a || b")),
|
||||
Binding::new("$", Dollar, Some("a")),
|
||||
Binding::new("\"", Quote, Some("a")),
|
||||
Binding::new("alt-s", Ess, Some("a")),
|
||||
Binding::new("ctrl-`", Backtick, Some("a")),
|
||||
]);
|
||||
|
||||
let mut context_a = KeymapContext::default();
|
||||
@@ -543,6 +558,30 @@ mod tests {
|
||||
MatchResult::Matches(vec![(1, Box::new(Ab))])
|
||||
);
|
||||
|
||||
// handle Czech $ (option + 4 key)
|
||||
assert_eq!(
|
||||
matcher.push_keystroke(Keystroke::parse("alt-ç->$")?, vec![(1, context_a.clone())]),
|
||||
MatchResult::Matches(vec![(1, Box::new(Dollar))])
|
||||
);
|
||||
|
||||
// handle Brazillian quote (quote key then space key)
|
||||
assert_eq!(
|
||||
matcher.push_keystroke(Keystroke::parse("space->\"")?, vec![(1, context_a.clone())]),
|
||||
MatchResult::Matches(vec![(1, Box::new(Quote))])
|
||||
);
|
||||
|
||||
// handle ctrl+` on a brazillian keyboard
|
||||
assert_eq!(
|
||||
matcher.push_keystroke(Keystroke::parse("ctrl-->`")?, vec![(1, context_a.clone())]),
|
||||
MatchResult::Matches(vec![(1, Box::new(Backtick))])
|
||||
);
|
||||
|
||||
// handle alt-s on a US keyboard
|
||||
assert_eq!(
|
||||
matcher.push_keystroke(Keystroke::parse("alt-s->ß")?, vec![(1, context_a.clone())]),
|
||||
MatchResult::Matches(vec![(1, Box::new(Ess))])
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +162,8 @@ mod tests {
|
||||
shift: false,
|
||||
cmd: false,
|
||||
function: false,
|
||||
key: "q".to_string()
|
||||
key: "q".to_string(),
|
||||
ime_key: None,
|
||||
}],
|
||||
"{keystroke_duplicate_to_1:?} should have the expected keystroke in the keymap"
|
||||
);
|
||||
@@ -179,7 +180,8 @@ mod tests {
|
||||
shift: false,
|
||||
cmd: false,
|
||||
function: false,
|
||||
key: "w".to_string()
|
||||
key: "w".to_string(),
|
||||
ime_key: None,
|
||||
},
|
||||
&Keystroke {
|
||||
ctrl: true,
|
||||
@@ -187,7 +189,8 @@ mod tests {
|
||||
shift: false,
|
||||
cmd: false,
|
||||
function: false,
|
||||
key: "w".to_string()
|
||||
key: "w".to_string(),
|
||||
ime_key: None,
|
||||
}
|
||||
],
|
||||
"{full_duplicate_to_2:?} should have a duplicated keystroke in the keymap"
|
||||
@@ -339,7 +342,8 @@ mod tests {
|
||||
shift: false,
|
||||
cmd: false,
|
||||
function: false,
|
||||
key: expected_key.to_string()
|
||||
key: expected_key.to_string(),
|
||||
ime_key: None,
|
||||
}],
|
||||
"{expected:?} should have the expected keystroke with key '{expected_key}' in the keymap for element {i}"
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::fmt::Write;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use serde::Deserialize;
|
||||
use smallvec::SmallVec;
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Default, Deserialize, Hash)]
|
||||
pub struct Keystroke {
|
||||
@@ -10,10 +11,47 @@ pub struct Keystroke {
|
||||
pub shift: bool,
|
||||
pub cmd: bool,
|
||||
pub function: bool,
|
||||
/// key is the character printed on the key that was pressed
|
||||
/// e.g. for option-s, key is "s"
|
||||
pub key: String,
|
||||
/// ime_key is the character inserted by the IME engine when that key was pressed.
|
||||
/// e.g. for option-s, ime_key is "ß"
|
||||
pub ime_key: Option<String>,
|
||||
}
|
||||
|
||||
impl Keystroke {
|
||||
// When matching a key we cannot know whether the user intended to type
|
||||
// the ime_key or the key. On some non-US keyboards keys we use in our
|
||||
// bindings are behind option (for example `$` is typed `alt-ç` on a Czech keyboard),
|
||||
// and on some keyboards the IME handler converts a sequence of keys into a
|
||||
// specific character (for example `"` is typed as `" space` on a brazillian keyboard).
|
||||
pub fn match_possibilities(&self) -> SmallVec<[Keystroke; 2]> {
|
||||
let mut possibilities = SmallVec::new();
|
||||
match self.ime_key.as_ref() {
|
||||
None => possibilities.push(self.clone()),
|
||||
Some(ime_key) => {
|
||||
possibilities.push(Keystroke {
|
||||
ctrl: self.ctrl,
|
||||
alt: false,
|
||||
shift: false,
|
||||
cmd: false,
|
||||
function: false,
|
||||
key: ime_key.to_string(),
|
||||
ime_key: None,
|
||||
});
|
||||
possibilities.push(Keystroke {
|
||||
ime_key: None,
|
||||
..self.clone()
|
||||
});
|
||||
}
|
||||
}
|
||||
possibilities
|
||||
}
|
||||
|
||||
/// key syntax is:
|
||||
/// [ctrl-][alt-][shift-][cmd-][fn-]key[->ime_key]
|
||||
/// ime_key is only used for generating test events,
|
||||
/// when matching a key with an ime_key set will be matched without it.
|
||||
pub fn parse(source: &str) -> anyhow::Result<Self> {
|
||||
let mut ctrl = false;
|
||||
let mut alt = false;
|
||||
@@ -21,6 +59,7 @@ impl Keystroke {
|
||||
let mut cmd = false;
|
||||
let mut function = false;
|
||||
let mut key = None;
|
||||
let mut ime_key = None;
|
||||
|
||||
let mut components = source.split('-').peekable();
|
||||
while let Some(component) = components.next() {
|
||||
@@ -31,10 +70,14 @@ impl Keystroke {
|
||||
"cmd" => cmd = true,
|
||||
"fn" => function = true,
|
||||
_ => {
|
||||
if let Some(component) = components.peek() {
|
||||
if component.is_empty() && source.ends_with('-') {
|
||||
if let Some(next) = components.peek() {
|
||||
if next.is_empty() && source.ends_with('-') {
|
||||
key = Some(String::from("-"));
|
||||
break;
|
||||
} else if next.len() > 1 && next.starts_with('>') {
|
||||
key = Some(String::from(component));
|
||||
ime_key = Some(String::from(&next[1..]));
|
||||
components.next();
|
||||
} else {
|
||||
return Err(anyhow!("Invalid keystroke `{}`", source));
|
||||
}
|
||||
@@ -54,6 +97,7 @@ impl Keystroke {
|
||||
cmd,
|
||||
function,
|
||||
key,
|
||||
ime_key,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -327,6 +327,7 @@ unsafe fn parse_keystroke(native_event: id) -> Keystroke {
|
||||
cmd,
|
||||
function,
|
||||
key,
|
||||
ime_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -285,6 +285,7 @@ enum ImeState {
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InsertText {
|
||||
replacement_range: Option<Range<usize>>,
|
||||
text: String,
|
||||
@@ -1006,40 +1007,7 @@ extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent:
|
||||
.flatten()
|
||||
.is_some();
|
||||
if !is_composing {
|
||||
// if the IME has changed the key, we'll first emit an event with the character
|
||||
// generated by the IME system; then fallback to the keystroke if that is not
|
||||
// handled.
|
||||
// cases that we have working:
|
||||
// - " on a brazillian layout by typing <quote><space>
|
||||
// - ctrl-` on a brazillian layout by typing <ctrl-`>
|
||||
// - $ on a czech QWERTY layout by typing <alt-4>
|
||||
// - 4 on a czech QWERTY layout by typing <shift-4>
|
||||
// - ctrl-4 on a czech QWERTY layout by typing <ctrl-alt-4> (or <ctrl-shift-4>)
|
||||
if ime_text.is_some() && ime_text.as_ref() != Some(&event.keystroke.key) {
|
||||
let event_with_ime_text = KeyDownEvent {
|
||||
is_held: false,
|
||||
keystroke: Keystroke {
|
||||
// we match ctrl because some use-cases need it.
|
||||
// we don't match alt because it's often used to generate the optional character
|
||||
// we don't match shift because we're not here with letters (usually)
|
||||
// we don't match cmd/fn because they don't seem to use IME
|
||||
ctrl: event.keystroke.ctrl,
|
||||
alt: false,
|
||||
shift: false,
|
||||
cmd: false,
|
||||
function: false,
|
||||
key: ime_text.clone().unwrap(),
|
||||
},
|
||||
};
|
||||
handled = callback(Event::KeyDown(event_with_ime_text));
|
||||
}
|
||||
if !handled {
|
||||
// empty key happens when you type a deadkey in input composition.
|
||||
// (e.g. on a brazillian keyboard typing quote is a deadkey)
|
||||
if !event.keystroke.key.is_empty() {
|
||||
handled = callback(Event::KeyDown(event));
|
||||
}
|
||||
}
|
||||
handled = callback(Event::KeyDown(event));
|
||||
}
|
||||
|
||||
if !handled {
|
||||
@@ -1197,6 +1165,7 @@ extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
|
||||
shift: false,
|
||||
function: false,
|
||||
key: ".".into(),
|
||||
ime_key: None,
|
||||
};
|
||||
let event = Event::KeyDown(KeyDownEvent {
|
||||
keystroke: keystroke.clone(),
|
||||
@@ -1479,6 +1448,9 @@ extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NS
|
||||
replacement_range,
|
||||
text: text.to_string(),
|
||||
});
|
||||
if text.to_string().to_ascii_lowercase() != pending_key_down.0.keystroke.key {
|
||||
pending_key_down.0.keystroke.ime_key = Some(text.to_string());
|
||||
}
|
||||
window_state.borrow_mut().pending_key_down = Some(pending_key_down);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -912,7 +912,6 @@ impl Project {
|
||||
self.user_store.clone()
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn opened_buffers(&self, cx: &AppContext) -> Vec<ModelHandle<Buffer>> {
|
||||
self.opened_buffers
|
||||
.values()
|
||||
|
||||
@@ -94,7 +94,7 @@ impl View for QuickActionBar {
|
||||
|
||||
bar.add_child(render_quick_action_bar_button(
|
||||
2,
|
||||
"icons/radix/magic-wand.svg",
|
||||
"icons/magic-wand.svg",
|
||||
false,
|
||||
("Inline Assist".into(), Some(Box::new(InlineAssist))),
|
||||
cx,
|
||||
|
||||
@@ -1012,7 +1012,7 @@ mod tests {
|
||||
.unwrap();
|
||||
editor.update(cx, |editor, cx| {
|
||||
assert_eq!(
|
||||
editor.all_background_highlights(cx),
|
||||
editor.all_text_background_highlights(cx),
|
||||
&[
|
||||
(
|
||||
DisplayPoint::new(2, 17)..DisplayPoint::new(2, 19),
|
||||
@@ -1033,7 +1033,7 @@ mod tests {
|
||||
editor.next_notification(cx).await;
|
||||
editor.update(cx, |editor, cx| {
|
||||
assert_eq!(
|
||||
editor.all_background_highlights(cx),
|
||||
editor.all_text_background_highlights(cx),
|
||||
&[(
|
||||
DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
|
||||
Color::red(),
|
||||
@@ -1049,7 +1049,7 @@ mod tests {
|
||||
.unwrap();
|
||||
editor.update(cx, |editor, cx| {
|
||||
assert_eq!(
|
||||
editor.all_background_highlights(cx),
|
||||
editor.all_text_background_highlights(cx),
|
||||
&[
|
||||
(
|
||||
DisplayPoint::new(0, 24)..DisplayPoint::new(0, 26),
|
||||
@@ -1090,7 +1090,7 @@ mod tests {
|
||||
editor.next_notification(cx).await;
|
||||
editor.update(cx, |editor, cx| {
|
||||
assert_eq!(
|
||||
editor.all_background_highlights(cx),
|
||||
editor.all_text_background_highlights(cx),
|
||||
&[
|
||||
(
|
||||
DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
|
||||
@@ -1301,7 +1301,7 @@ mod tests {
|
||||
.unwrap();
|
||||
editor.update(cx, |editor, cx| {
|
||||
assert_eq!(
|
||||
editor.all_background_highlights(cx),
|
||||
editor.all_text_background_highlights(cx),
|
||||
&[(
|
||||
DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
|
||||
Color::red(),
|
||||
@@ -1328,7 +1328,7 @@ mod tests {
|
||||
editor.next_notification(cx).await;
|
||||
editor.update(cx, |editor, cx| {
|
||||
assert_eq!(
|
||||
editor.all_background_highlights(cx),
|
||||
editor.all_text_background_highlights(cx),
|
||||
&[(
|
||||
DisplayPoint::new(0, 35)..DisplayPoint::new(0, 40),
|
||||
Color::red(),
|
||||
|
||||
@@ -511,7 +511,7 @@ impl Item for ProjectSearchView {
|
||||
) -> AnyElement<T> {
|
||||
Flex::row()
|
||||
.with_child(
|
||||
Svg::new("icons/magnifying_glass_12.svg")
|
||||
Svg::new("icons/magnifying_glass.svg")
|
||||
.with_color(tab_theme.label.text.color)
|
||||
.constrained()
|
||||
.with_width(tab_theme.type_icon_width)
|
||||
@@ -1440,7 +1440,7 @@ impl View for ProjectSearchBar {
|
||||
let search = _search.read(cx);
|
||||
let filter_button = render_option_button_icon(
|
||||
search.filters_enabled,
|
||||
"icons/filter_12.svg",
|
||||
"icons/filter.svg",
|
||||
0,
|
||||
"Toggle filters",
|
||||
Box::new(ToggleFilters),
|
||||
@@ -1471,14 +1471,14 @@ impl View for ProjectSearchBar {
|
||||
};
|
||||
let case_sensitive = is_semantic_disabled.then(|| {
|
||||
render_option_button_icon(
|
||||
"icons/case_insensitive_12.svg",
|
||||
"icons/case_insensitive.svg",
|
||||
SearchOptions::CASE_SENSITIVE,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let whole_word = is_semantic_disabled.then(|| {
|
||||
render_option_button_icon("icons/word_search_12.svg", SearchOptions::WHOLE_WORD, cx)
|
||||
render_option_button_icon("icons/word_search.svg", SearchOptions::WHOLE_WORD, cx)
|
||||
});
|
||||
|
||||
let search_button_for_mode = |mode, side, cx: &mut ViewContext<ProjectSearchBar>| {
|
||||
@@ -1725,7 +1725,7 @@ pub mod tests {
|
||||
assert_eq!(
|
||||
search_view
|
||||
.results_editor
|
||||
.update(cx, |editor, cx| editor.all_background_highlights(cx)),
|
||||
.update(cx, |editor, cx| editor.all_text_background_highlights(cx)),
|
||||
&[
|
||||
(
|
||||
DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
|
||||
|
||||
@@ -63,8 +63,8 @@ impl SearchOptions {
|
||||
|
||||
pub fn icon(&self) -> &'static str {
|
||||
match *self {
|
||||
SearchOptions::WHOLE_WORD => "icons/word_search_12.svg",
|
||||
SearchOptions::CASE_SENSITIVE => "icons/case_insensitive_12.svg",
|
||||
SearchOptions::WHOLE_WORD => "icons/word_search.svg",
|
||||
SearchOptions::CASE_SENSITIVE => "icons/case_insensitive.svg",
|
||||
_ => panic!("{:?} is not a named SearchOption", self),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ settings = { path = "../settings" }
|
||||
anyhow.workspace = true
|
||||
postage.workspace = true
|
||||
futures.workspace = true
|
||||
ordered-float.workspace = true
|
||||
smol.workspace = true
|
||||
rusqlite = { version = "0.27.0", features = ["blob", "array", "modern_sqlite"] }
|
||||
isahc.workspace = true
|
||||
|
||||
@@ -7,12 +7,13 @@ use anyhow::{anyhow, Context, Result};
|
||||
use collections::HashMap;
|
||||
use futures::channel::oneshot;
|
||||
use gpui::executor;
|
||||
use ordered_float::OrderedFloat;
|
||||
use project::{search::PathMatcher, Fs};
|
||||
use rpc::proto::Timestamp;
|
||||
use rusqlite::params;
|
||||
use rusqlite::types::Value;
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
cmp::Reverse,
|
||||
future::Future,
|
||||
ops::Range,
|
||||
path::{Path, PathBuf},
|
||||
@@ -190,6 +191,10 @@ impl VectorDatabase {
|
||||
)",
|
||||
[],
|
||||
)?;
|
||||
db.execute(
|
||||
"CREATE INDEX spans_digest ON spans (digest)",
|
||||
[],
|
||||
)?;
|
||||
|
||||
log::trace!("vector database initialized with updated schema.");
|
||||
Ok(())
|
||||
@@ -274,6 +279,39 @@ impl VectorDatabase {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn embeddings_for_digests(
|
||||
&self,
|
||||
digests: Vec<SpanDigest>,
|
||||
) -> impl Future<Output = Result<HashMap<SpanDigest, Embedding>>> {
|
||||
self.transact(move |db| {
|
||||
let mut query = db.prepare(
|
||||
"
|
||||
SELECT digest, embedding
|
||||
FROM spans
|
||||
WHERE digest IN rarray(?)
|
||||
",
|
||||
)?;
|
||||
let mut embeddings_by_digest = HashMap::default();
|
||||
let digests = Rc::new(
|
||||
digests
|
||||
.into_iter()
|
||||
.map(|p| Value::Blob(p.0.to_vec()))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
let rows = query.query_map(params![digests], |row| {
|
||||
Ok((row.get::<_, SpanDigest>(0)?, row.get::<_, Embedding>(1)?))
|
||||
})?;
|
||||
|
||||
for row in rows {
|
||||
if let Ok(row) = row {
|
||||
embeddings_by_digest.insert(row.0, row.1);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(embeddings_by_digest)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn embeddings_for_files(
|
||||
&self,
|
||||
worktree_id_file_paths: HashMap<i64, Vec<Arc<Path>>>,
|
||||
@@ -370,16 +408,16 @@ impl VectorDatabase {
|
||||
query_embedding: &Embedding,
|
||||
limit: usize,
|
||||
file_ids: &[i64],
|
||||
) -> impl Future<Output = Result<Vec<(i64, f32)>>> {
|
||||
) -> impl Future<Output = Result<Vec<(i64, OrderedFloat<f32>)>>> {
|
||||
let query_embedding = query_embedding.clone();
|
||||
let file_ids = file_ids.to_vec();
|
||||
self.transact(move |db| {
|
||||
let mut results = Vec::<(i64, f32)>::with_capacity(limit + 1);
|
||||
let mut results = Vec::<(i64, OrderedFloat<f32>)>::with_capacity(limit + 1);
|
||||
Self::for_each_span(db, &file_ids, |id, embedding| {
|
||||
let similarity = embedding.similarity(&query_embedding);
|
||||
let ix = match results.binary_search_by(|(_, s)| {
|
||||
similarity.partial_cmp(&s).unwrap_or(Ordering::Equal)
|
||||
}) {
|
||||
let ix = match results
|
||||
.binary_search_by_key(&Reverse(similarity), |(_, s)| Reverse(*s))
|
||||
{
|
||||
Ok(ix) => ix,
|
||||
Err(ix) => ix,
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@ use isahc::http::StatusCode;
|
||||
use isahc::prelude::Configurable;
|
||||
use isahc::{AsyncBody, Response};
|
||||
use lazy_static::lazy_static;
|
||||
use ordered_float::OrderedFloat;
|
||||
use parking_lot::Mutex;
|
||||
use parse_duration::parse;
|
||||
use postage::watch;
|
||||
@@ -35,7 +36,7 @@ impl From<Vec<f32>> for Embedding {
|
||||
}
|
||||
|
||||
impl Embedding {
|
||||
pub fn similarity(&self, other: &Self) -> f32 {
|
||||
pub fn similarity(&self, other: &Self) -> OrderedFloat<f32> {
|
||||
let len = self.0.len();
|
||||
assert_eq!(len, other.0.len());
|
||||
|
||||
@@ -58,7 +59,7 @@ impl Embedding {
|
||||
1,
|
||||
);
|
||||
}
|
||||
result
|
||||
OrderedFloat(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,13 +380,13 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn round_to_decimals(n: f32, decimal_places: i32) -> f32 {
|
||||
fn round_to_decimals(n: OrderedFloat<f32>, decimal_places: i32) -> f32 {
|
||||
let factor = (10.0 as f32).powi(decimal_places);
|
||||
(n * factor).round() / factor
|
||||
}
|
||||
|
||||
fn reference_dot(a: &[f32], b: &[f32]) -> f32 {
|
||||
a.iter().zip(b.iter()).map(|(a, b)| a * b).sum()
|
||||
fn reference_dot(a: &[f32], b: &[f32]) -> OrderedFloat<f32> {
|
||||
OrderedFloat(a.iter().zip(b.iter()).map(|(a, b)| a * b).sum())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use rusqlite::{
|
||||
};
|
||||
use sha1::{Digest, Sha1};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
cmp::{self, Reverse},
|
||||
collections::HashSet,
|
||||
ops::Range,
|
||||
@@ -16,7 +17,7 @@ use std::{
|
||||
use tree_sitter::{Parser, QueryCursor};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
|
||||
pub struct SpanDigest([u8; 20]);
|
||||
pub struct SpanDigest(pub [u8; 20]);
|
||||
|
||||
impl FromSql for SpanDigest {
|
||||
fn column_result(value: ValueRef) -> FromSqlResult<Self> {
|
||||
@@ -94,12 +95,15 @@ impl CodeContextRetriever {
|
||||
|
||||
fn parse_entire_file(
|
||||
&self,
|
||||
relative_path: &Path,
|
||||
relative_path: Option<&Path>,
|
||||
language_name: Arc<str>,
|
||||
content: &str,
|
||||
) -> Result<Vec<Span>> {
|
||||
let document_span = ENTIRE_FILE_TEMPLATE
|
||||
.replace("<path>", relative_path.to_string_lossy().as_ref())
|
||||
.replace(
|
||||
"<path>",
|
||||
&relative_path.map_or(Cow::Borrowed("untitled"), |path| path.to_string_lossy()),
|
||||
)
|
||||
.replace("<language>", language_name.as_ref())
|
||||
.replace("<item>", &content);
|
||||
let digest = SpanDigest::from(document_span.as_str());
|
||||
@@ -114,9 +118,16 @@ impl CodeContextRetriever {
|
||||
}])
|
||||
}
|
||||
|
||||
fn parse_markdown_file(&self, relative_path: &Path, content: &str) -> Result<Vec<Span>> {
|
||||
fn parse_markdown_file(
|
||||
&self,
|
||||
relative_path: Option<&Path>,
|
||||
content: &str,
|
||||
) -> Result<Vec<Span>> {
|
||||
let document_span = MARKDOWN_CONTEXT_TEMPLATE
|
||||
.replace("<path>", relative_path.to_string_lossy().as_ref())
|
||||
.replace(
|
||||
"<path>",
|
||||
&relative_path.map_or(Cow::Borrowed("untitled"), |path| path.to_string_lossy()),
|
||||
)
|
||||
.replace("<item>", &content);
|
||||
let digest = SpanDigest::from(document_span.as_str());
|
||||
let (document_span, token_count) = self.embedding_provider.truncate(&document_span);
|
||||
@@ -188,7 +199,7 @@ impl CodeContextRetriever {
|
||||
|
||||
pub fn parse_file_with_template(
|
||||
&mut self,
|
||||
relative_path: &Path,
|
||||
relative_path: Option<&Path>,
|
||||
content: &str,
|
||||
language: Arc<Language>,
|
||||
) -> Result<Vec<Span>> {
|
||||
@@ -196,14 +207,17 @@ impl CodeContextRetriever {
|
||||
|
||||
if PARSEABLE_ENTIRE_FILE_TYPES.contains(&language_name.as_ref()) {
|
||||
return self.parse_entire_file(relative_path, language_name, &content);
|
||||
} else if language_name.as_ref() == "Markdown" {
|
||||
} else if ["Markdown", "Plain Text"].contains(&language_name.as_ref()) {
|
||||
return self.parse_markdown_file(relative_path, &content);
|
||||
}
|
||||
|
||||
let mut spans = self.parse_file(content, language)?;
|
||||
for span in &mut spans {
|
||||
let document_content = CODE_CONTEXT_TEMPLATE
|
||||
.replace("<path>", relative_path.to_string_lossy().as_ref())
|
||||
.replace(
|
||||
"<path>",
|
||||
&relative_path.map_or(Cow::Borrowed("untitled"), |path| path.to_string_lossy()),
|
||||
)
|
||||
.replace("<language>", language_name.as_ref())
|
||||
.replace("item", &span.content);
|
||||
|
||||
|
||||
@@ -16,14 +16,16 @@ use embedding_queue::{EmbeddingQueue, FileToEmbed};
|
||||
use futures::{future, FutureExt, StreamExt};
|
||||
use gpui::{AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task, WeakModelHandle};
|
||||
use language::{Anchor, Bias, Buffer, Language, LanguageRegistry};
|
||||
use ordered_float::OrderedFloat;
|
||||
use parking_lot::Mutex;
|
||||
use parsing::{CodeContextRetriever, SpanDigest, PARSEABLE_ENTIRE_FILE_TYPES};
|
||||
use parsing::{CodeContextRetriever, Span, SpanDigest, PARSEABLE_ENTIRE_FILE_TYPES};
|
||||
use postage::watch;
|
||||
use project::{search::PathMatcher, Fs, PathChange, Project, ProjectEntryId, Worktree, WorktreeId};
|
||||
use smol::channel;
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
cmp::Reverse,
|
||||
future::Future,
|
||||
mem,
|
||||
ops::Range,
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Weak},
|
||||
@@ -37,7 +39,7 @@ use util::{
|
||||
};
|
||||
use workspace::WorkspaceCreated;
|
||||
|
||||
const SEMANTIC_INDEX_VERSION: usize = 10;
|
||||
const SEMANTIC_INDEX_VERSION: usize = 11;
|
||||
const BACKGROUND_INDEXING_DELAY: Duration = Duration::from_secs(5 * 60);
|
||||
const EMBEDDING_QUEUE_FLUSH_TIMEOUT: Duration = Duration::from_millis(250);
|
||||
|
||||
@@ -262,9 +264,11 @@ pub struct PendingFile {
|
||||
job_handle: JobHandle,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SearchResult {
|
||||
pub buffer: ModelHandle<Buffer>,
|
||||
pub range: Range<Anchor>,
|
||||
pub similarity: OrderedFloat<f32>,
|
||||
}
|
||||
|
||||
impl SemanticIndex {
|
||||
@@ -402,7 +406,7 @@ impl SemanticIndex {
|
||||
|
||||
if let Some(content) = fs.load(&pending_file.absolute_path).await.log_err() {
|
||||
if let Some(mut spans) = retriever
|
||||
.parse_file_with_template(&pending_file.relative_path, &content, language)
|
||||
.parse_file_with_template(Some(&pending_file.relative_path), &content, language)
|
||||
.log_err()
|
||||
{
|
||||
log::trace!(
|
||||
@@ -422,7 +426,7 @@ impl SemanticIndex {
|
||||
path: pending_file.relative_path,
|
||||
mtime: pending_file.modified_time,
|
||||
job_handle: pending_file.job_handle,
|
||||
spans: spans,
|
||||
spans,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -687,39 +691,71 @@ impl SemanticIndex {
|
||||
pub fn search_project(
|
||||
&mut self,
|
||||
project: ModelHandle<Project>,
|
||||
phrase: String,
|
||||
query: String,
|
||||
limit: usize,
|
||||
includes: Vec<PathMatcher>,
|
||||
excludes: Vec<PathMatcher>,
|
||||
cx: &mut ModelContext<Self>,
|
||||
) -> Task<Result<Vec<SearchResult>>> {
|
||||
if query.is_empty() {
|
||||
return Task::ready(Ok(Vec::new()));
|
||||
}
|
||||
|
||||
let index = self.index_project(project.clone(), cx);
|
||||
let embedding_provider = self.embedding_provider.clone();
|
||||
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
let query = embedding_provider
|
||||
.embed_batch(vec![query])
|
||||
.await?
|
||||
.pop()
|
||||
.ok_or_else(|| anyhow!("could not embed query"))?;
|
||||
index.await?;
|
||||
|
||||
let search_start = Instant::now();
|
||||
let modified_buffer_results = this.update(&mut cx, |this, cx| {
|
||||
this.search_modified_buffers(&project, query.clone(), limit, &excludes, cx)
|
||||
});
|
||||
let file_results = this.update(&mut cx, |this, cx| {
|
||||
this.search_files(project, query, limit, includes, excludes, cx)
|
||||
});
|
||||
let (modified_buffer_results, file_results) =
|
||||
futures::join!(modified_buffer_results, file_results);
|
||||
|
||||
// Weave together the results from modified buffers and files.
|
||||
let mut results = Vec::new();
|
||||
let mut modified_buffers = HashSet::default();
|
||||
for result in modified_buffer_results.log_err().unwrap_or_default() {
|
||||
modified_buffers.insert(result.buffer.clone());
|
||||
results.push(result);
|
||||
}
|
||||
for result in file_results.log_err().unwrap_or_default() {
|
||||
if !modified_buffers.contains(&result.buffer) {
|
||||
results.push(result);
|
||||
}
|
||||
}
|
||||
results.sort_by_key(|result| Reverse(result.similarity));
|
||||
results.truncate(limit);
|
||||
log::trace!("Semantic search took {:?}", search_start.elapsed());
|
||||
Ok(results)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn search_files(
|
||||
&mut self,
|
||||
project: ModelHandle<Project>,
|
||||
query: Embedding,
|
||||
limit: usize,
|
||||
includes: Vec<PathMatcher>,
|
||||
excludes: Vec<PathMatcher>,
|
||||
cx: &mut ModelContext<Self>,
|
||||
) -> Task<Result<Vec<SearchResult>>> {
|
||||
let db_path = self.db.path().clone();
|
||||
let fs = self.fs.clone();
|
||||
cx.spawn(|this, mut cx| async move {
|
||||
index.await?;
|
||||
|
||||
let t0 = Instant::now();
|
||||
let database =
|
||||
VectorDatabase::new(fs.clone(), db_path.clone(), cx.background()).await?;
|
||||
|
||||
if phrase.len() == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let phrase_embedding = embedding_provider
|
||||
.embed_batch(vec![phrase])
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.unwrap();
|
||||
|
||||
log::trace!(
|
||||
"Embedding search phrase took: {:?} milliseconds",
|
||||
t0.elapsed().as_millis()
|
||||
);
|
||||
|
||||
let worktree_db_ids = this.read_with(&cx, |this, _| {
|
||||
let project_state = this
|
||||
.projects
|
||||
@@ -738,6 +774,7 @@ impl SemanticIndex {
|
||||
.collect::<Vec<i64>>();
|
||||
anyhow::Ok(worktree_db_ids)
|
||||
})?;
|
||||
|
||||
let file_ids = database
|
||||
.retrieve_included_file_ids(&worktree_db_ids, &includes, &excludes)
|
||||
.await?;
|
||||
@@ -756,26 +793,26 @@ impl SemanticIndex {
|
||||
let limit = limit.clone();
|
||||
let fs = fs.clone();
|
||||
let db_path = db_path.clone();
|
||||
let phrase_embedding = phrase_embedding.clone();
|
||||
let query = query.clone();
|
||||
if let Some(db) = VectorDatabase::new(fs, db_path.clone(), cx.background())
|
||||
.await
|
||||
.log_err()
|
||||
{
|
||||
batch_results.push(async move {
|
||||
db.top_k_search(&phrase_embedding, limit, batch.as_slice())
|
||||
.await
|
||||
db.top_k_search(&query, limit, batch.as_slice()).await
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let batch_results = futures::future::join_all(batch_results).await;
|
||||
|
||||
let mut results = Vec::new();
|
||||
for batch_result in batch_results {
|
||||
if batch_result.is_ok() {
|
||||
for (id, similarity) in batch_result.unwrap() {
|
||||
let ix = match results.binary_search_by(|(_, s)| {
|
||||
similarity.partial_cmp(&s).unwrap_or(Ordering::Equal)
|
||||
}) {
|
||||
let ix = match results
|
||||
.binary_search_by_key(&Reverse(similarity), |(_, s)| Reverse(*s))
|
||||
{
|
||||
Ok(ix) => ix,
|
||||
Err(ix) => ix,
|
||||
};
|
||||
@@ -785,7 +822,11 @@ impl SemanticIndex {
|
||||
}
|
||||
}
|
||||
|
||||
let ids = results.into_iter().map(|(id, _)| id).collect::<Vec<i64>>();
|
||||
let ids = results.iter().map(|(id, _)| *id).collect::<Vec<i64>>();
|
||||
let scores = results
|
||||
.into_iter()
|
||||
.map(|(_, score)| score)
|
||||
.collect::<Vec<_>>();
|
||||
let spans = database.spans_for_ids(ids.as_slice()).await?;
|
||||
|
||||
let mut tasks = Vec::new();
|
||||
@@ -810,24 +851,106 @@ impl SemanticIndex {
|
||||
|
||||
let buffers = futures::future::join_all(tasks).await;
|
||||
|
||||
log::trace!(
|
||||
"Semantic Searching took: {:?} milliseconds in total",
|
||||
t0.elapsed().as_millis()
|
||||
);
|
||||
|
||||
Ok(buffers
|
||||
.into_iter()
|
||||
.zip(ranges)
|
||||
.filter_map(|(buffer, range)| {
|
||||
.zip(scores)
|
||||
.filter_map(|((buffer, range), similarity)| {
|
||||
let buffer = buffer.log_err()?;
|
||||
let range = buffer.read_with(&cx, |buffer, _| {
|
||||
let start = buffer.clip_offset(range.start, Bias::Left);
|
||||
let end = buffer.clip_offset(range.end, Bias::Right);
|
||||
buffer.anchor_before(start)..buffer.anchor_after(end)
|
||||
});
|
||||
Some(SearchResult { buffer, range })
|
||||
Some(SearchResult {
|
||||
buffer,
|
||||
range,
|
||||
similarity,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>())
|
||||
.collect())
|
||||
})
|
||||
}
|
||||
|
||||
fn search_modified_buffers(
|
||||
&self,
|
||||
project: &ModelHandle<Project>,
|
||||
query: Embedding,
|
||||
limit: usize,
|
||||
excludes: &[PathMatcher],
|
||||
cx: &mut ModelContext<Self>,
|
||||
) -> Task<Result<Vec<SearchResult>>> {
|
||||
let modified_buffers = project
|
||||
.read(cx)
|
||||
.opened_buffers(cx)
|
||||
.into_iter()
|
||||
.filter_map(|buffer_handle| {
|
||||
let buffer = buffer_handle.read(cx);
|
||||
let snapshot = buffer.snapshot();
|
||||
let excluded = snapshot.resolve_file_path(cx, false).map_or(false, |path| {
|
||||
excludes.iter().any(|matcher| matcher.is_match(&path))
|
||||
});
|
||||
if buffer.is_dirty() && !excluded {
|
||||
Some((buffer_handle, snapshot))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
let embedding_provider = self.embedding_provider.clone();
|
||||
let fs = self.fs.clone();
|
||||
let db_path = self.db.path().clone();
|
||||
let background = cx.background().clone();
|
||||
cx.background().spawn(async move {
|
||||
let db = VectorDatabase::new(fs, db_path.clone(), background).await?;
|
||||
let mut results = Vec::<SearchResult>::new();
|
||||
|
||||
let mut retriever = CodeContextRetriever::new(embedding_provider.clone());
|
||||
for (buffer, snapshot) in modified_buffers {
|
||||
let language = snapshot
|
||||
.language_at(0)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| language::PLAIN_TEXT.clone());
|
||||
let mut spans = retriever
|
||||
.parse_file_with_template(None, &snapshot.text(), language)
|
||||
.log_err()
|
||||
.unwrap_or_default();
|
||||
if Self::embed_spans(&mut spans, embedding_provider.as_ref(), &db)
|
||||
.await
|
||||
.log_err()
|
||||
.is_some()
|
||||
{
|
||||
for span in spans {
|
||||
let similarity = span.embedding.unwrap().similarity(&query);
|
||||
let ix = match results
|
||||
.binary_search_by_key(&Reverse(similarity), |result| {
|
||||
Reverse(result.similarity)
|
||||
}) {
|
||||
Ok(ix) => ix,
|
||||
Err(ix) => ix,
|
||||
};
|
||||
|
||||
let range = {
|
||||
let start = snapshot.clip_offset(span.range.start, Bias::Left);
|
||||
let end = snapshot.clip_offset(span.range.end, Bias::Right);
|
||||
snapshot.anchor_before(start)..snapshot.anchor_after(end)
|
||||
};
|
||||
|
||||
results.insert(
|
||||
ix,
|
||||
SearchResult {
|
||||
buffer: buffer.clone(),
|
||||
range,
|
||||
similarity,
|
||||
},
|
||||
);
|
||||
results.truncate(limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1011,6 +1134,63 @@ impl SemanticIndex {
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
async fn embed_spans(
|
||||
spans: &mut [Span],
|
||||
embedding_provider: &dyn EmbeddingProvider,
|
||||
db: &VectorDatabase,
|
||||
) -> Result<()> {
|
||||
let mut batch = Vec::new();
|
||||
let mut batch_tokens = 0;
|
||||
let mut embeddings = Vec::new();
|
||||
|
||||
let digests = spans
|
||||
.iter()
|
||||
.map(|span| span.digest.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let embeddings_for_digests = db
|
||||
.embeddings_for_digests(digests)
|
||||
.await
|
||||
.log_err()
|
||||
.unwrap_or_default();
|
||||
|
||||
for span in &*spans {
|
||||
if embeddings_for_digests.contains_key(&span.digest) {
|
||||
continue;
|
||||
};
|
||||
|
||||
if batch_tokens + span.token_count > embedding_provider.max_tokens_per_batch() {
|
||||
let batch_embeddings = embedding_provider
|
||||
.embed_batch(mem::take(&mut batch))
|
||||
.await?;
|
||||
embeddings.extend(batch_embeddings);
|
||||
batch_tokens = 0;
|
||||
}
|
||||
|
||||
batch_tokens += span.token_count;
|
||||
batch.push(span.content.clone());
|
||||
}
|
||||
|
||||
if !batch.is_empty() {
|
||||
let batch_embeddings = embedding_provider
|
||||
.embed_batch(mem::take(&mut batch))
|
||||
.await?;
|
||||
|
||||
embeddings.extend(batch_embeddings);
|
||||
}
|
||||
|
||||
let mut embeddings = embeddings.into_iter();
|
||||
for span in spans {
|
||||
let embedding = if let Some(embedding) = embeddings_for_digests.get(&span.digest) {
|
||||
Some(embedding.clone())
|
||||
} else {
|
||||
embeddings.next()
|
||||
};
|
||||
let embedding = embedding.ok_or_else(|| anyhow!("failed to embed spans"))?;
|
||||
span.embedding = Some(embedding);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Entity for SemanticIndex {
|
||||
|
||||
@@ -132,9 +132,9 @@ impl<V: 'static> CollabPanelElement<V> {
|
||||
div().flex().h_full().gap_1().items_center().child(
|
||||
svg()
|
||||
.path(if expanded {
|
||||
"icons/radix/caret-down.svg"
|
||||
"icons/caret_down.svg"
|
||||
} else {
|
||||
"icons/radix/caret-up.svg"
|
||||
"icons/caret_up.svg"
|
||||
})
|
||||
.w_3p5()
|
||||
.h_3p5()
|
||||
|
||||
@@ -217,7 +217,7 @@ impl TitleBar {
|
||||
.fill(theme.lowest.base.pressed.background)
|
||||
.child(
|
||||
svg()
|
||||
.path("icons/radix/speaker-loud.svg")
|
||||
.path("icons/speaker-loud.svg")
|
||||
.size_3p5()
|
||||
.fill(theme.lowest.base.default.foreground),
|
||||
),
|
||||
@@ -237,7 +237,7 @@ impl TitleBar {
|
||||
.fill(theme.lowest.base.pressed.background)
|
||||
.child(
|
||||
svg()
|
||||
.path("icons/radix/desktop.svg")
|
||||
.path("icons/desktop.svg")
|
||||
.size_3p5()
|
||||
.fill(theme.lowest.base.default.foreground),
|
||||
),
|
||||
@@ -269,7 +269,7 @@ impl TitleBar {
|
||||
)
|
||||
.child(
|
||||
svg()
|
||||
.path("icons/caret_down_8.svg")
|
||||
.path("icons/caret_down.svg")
|
||||
.w_2()
|
||||
.h_2()
|
||||
.fill(theme.lowest.variant.default.foreground),
|
||||
|
||||
@@ -333,6 +333,7 @@ mod test {
|
||||
cmd: false,
|
||||
function: false,
|
||||
key: "🖖🏻".to_string(), //2 char string
|
||||
ime_key: None,
|
||||
};
|
||||
assert_eq!(to_esc_str(&ks, &TermMode::NONE, false), None);
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ impl TerminalPanel {
|
||||
Flex::row()
|
||||
.with_child(Pane::render_tab_bar_button(
|
||||
0,
|
||||
"icons/plus_12.svg",
|
||||
"icons/plus.svg",
|
||||
false,
|
||||
Some(("New Terminal", Some(Box::new(workspace::NewTerminal)))),
|
||||
cx,
|
||||
@@ -90,9 +90,9 @@ impl TerminalPanel {
|
||||
.with_child(Pane::render_tab_bar_button(
|
||||
1,
|
||||
if pane.is_zoomed() {
|
||||
"icons/minimize_8.svg"
|
||||
"icons/minimize.svg"
|
||||
} else {
|
||||
"icons/maximize_8.svg"
|
||||
"icons/maximize.svg"
|
||||
},
|
||||
pane.is_zoomed(),
|
||||
Some(("Toggle Zoom".into(), Some(Box::new(workspace::ToggleZoom)))),
|
||||
|
||||
@@ -227,7 +227,7 @@ mod test {
|
||||
deterministic.run_until_parked();
|
||||
|
||||
cx.update_editor(|editor, cx| {
|
||||
let highlights = editor.all_background_highlights(cx);
|
||||
let highlights = editor.all_text_background_highlights(cx);
|
||||
assert_eq!(3, highlights.len());
|
||||
assert_eq!(
|
||||
DisplayPoint::new(2, 0)..DisplayPoint::new(2, 2),
|
||||
|
||||
@@ -186,7 +186,6 @@ impl EditorState {
|
||||
if self.active_operator().is_none() && self.pre_count.is_some()
|
||||
|| self.active_operator().is_some() && self.post_count.is_some()
|
||||
{
|
||||
dbg!("VimCount");
|
||||
context.add_identifier("VimCount");
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ async fn test_selection_on_search(cx: &mut gpui::TestAppContext) {
|
||||
search_bar.next_notification(&cx).await;
|
||||
|
||||
cx.update_editor(|editor, cx| {
|
||||
let highlights = editor.all_background_highlights(cx);
|
||||
let highlights = editor.all_text_background_highlights(cx);
|
||||
assert_eq!(3, highlights.len());
|
||||
assert_eq!(
|
||||
DisplayPoint::new(2, 0)..DisplayPoint::new(2, 2),
|
||||
|
||||
@@ -292,7 +292,7 @@ pub mod simple_message_notification {
|
||||
.with_child(
|
||||
MouseEventHandler::new::<Cancel, _>(0, cx, |state, _| {
|
||||
let style = theme.dismiss_button.style_for(state);
|
||||
Svg::new("icons/x_mark_8.svg")
|
||||
Svg::new("icons/x.svg")
|
||||
.with_color(style.color)
|
||||
.constrained()
|
||||
.with_width(style.icon_width)
|
||||
|
||||
@@ -337,7 +337,7 @@ impl Pane {
|
||||
// New menu
|
||||
.with_child(Self::render_tab_bar_button(
|
||||
0,
|
||||
"icons/plus_12.svg",
|
||||
"icons/plus.svg",
|
||||
false,
|
||||
Some(("New...".into(), None)),
|
||||
cx,
|
||||
@@ -352,7 +352,7 @@ impl Pane {
|
||||
))
|
||||
.with_child(Self::render_tab_bar_button(
|
||||
1,
|
||||
"icons/split_12.svg",
|
||||
"icons/split.svg",
|
||||
false,
|
||||
Some(("Split Pane".into(), None)),
|
||||
cx,
|
||||
@@ -369,10 +369,10 @@ impl Pane {
|
||||
let icon_path;
|
||||
let tooltip_label;
|
||||
if pane.is_zoomed() {
|
||||
icon_path = "icons/minimize_8.svg";
|
||||
icon_path = "icons/minimize.svg";
|
||||
tooltip_label = "Zoom In";
|
||||
} else {
|
||||
icon_path = "icons/maximize_8.svg";
|
||||
icon_path = "icons/maximize.svg";
|
||||
tooltip_label = "Zoom In";
|
||||
}
|
||||
|
||||
@@ -1535,7 +1535,7 @@ impl Pane {
|
||||
let close_element = if hovered {
|
||||
let item_id = item.id();
|
||||
enum TabCloseButton {}
|
||||
let icon = Svg::new("icons/x_mark_8.svg");
|
||||
let icon = Svg::new("icons/x.svg");
|
||||
MouseEventHandler::new::<TabCloseButton, _>(item_id, cx, |mouse_state, _| {
|
||||
if mouse_state.hovered() {
|
||||
icon.with_color(tab_style.icon_close_active)
|
||||
@@ -1701,7 +1701,7 @@ impl View for Pane {
|
||||
|
||||
let mut tab_row = Flex::row()
|
||||
.with_child(nav_button(
|
||||
"icons/arrow_left_16.svg",
|
||||
"icons/arrow_left.svg",
|
||||
button_style.clone(),
|
||||
nav_button_height,
|
||||
tooltip_style.clone(),
|
||||
@@ -1726,7 +1726,7 @@ impl View for Pane {
|
||||
))
|
||||
.with_child(
|
||||
nav_button(
|
||||
"icons/arrow_right_16.svg",
|
||||
"icons/arrow_right.svg",
|
||||
button_style.clone(),
|
||||
nav_button_height,
|
||||
tooltip_style,
|
||||
|
||||
Reference in New Issue
Block a user