Merge branch 'main' into editor2-autocomplete

# Conflicts:
#	crates/editor2/src/editor.rs
This commit is contained in:
Antonio Scandurra
2023-11-21 17:43:09 +01:00
227 changed files with 15900 additions and 11913 deletions
+3 -3
View File
@@ -50,7 +50,7 @@ struct BlockRow(u32);
#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
struct WrapRow(u32);
pub type RenderBlock = Arc<dyn Fn(&mut BlockContext) -> AnyElement<Editor>>;
pub type RenderBlock = Arc<dyn Fn(&mut BlockContext) -> AnyElement>;
pub struct Block {
id: BlockId,
@@ -69,7 +69,7 @@ where
pub position: P,
pub height: u8,
pub style: BlockStyle,
pub render: Arc<dyn Fn(&mut BlockContext) -> AnyElement<Editor>>,
pub render: Arc<dyn Fn(&mut BlockContext) -> AnyElement>,
pub disposition: BlockDisposition,
}
@@ -947,7 +947,7 @@ impl DerefMut for BlockContext<'_, '_> {
}
impl Block {
pub fn render(&self, cx: &mut BlockContext) -> AnyElement<Editor> {
pub fn render(&self, cx: &mut BlockContext) -> AnyElement {
self.render.lock()(cx)
}
+190 -173
View File
@@ -24,7 +24,7 @@ use ::git::diff::DiffHunk;
use aho_corasick::AhoCorasick;
use anyhow::{anyhow, Context as _, Result};
use blink_manager::BlinkManager;
use client::{ClickhouseEvent, Client, Collaborator, ParticipantIndex, TelemetrySettings};
use client::{Client, Collaborator, ParticipantIndex, TelemetrySettings};
use clock::ReplicaId;
use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
use convert_case::{Case, Casing};
@@ -42,9 +42,9 @@ use gpui::{
actions, div, point, prelude::*, px, relative, rems, size, uniform_list, Action, AnyElement,
AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Component, Context,
EventEmitter, FocusHandle, FocusableView, FontFeatures, FontStyle, FontWeight, HighlightStyle,
Hsla, InputHandler, KeyContext, Model, MouseButton, ParentComponent, Pixels, Render, Styled,
Subscription, Task, TextStyle, UniformListScrollHandle, View, ViewContext, VisualContext,
WeakView, WindowContext,
Hsla, InputHandler, KeyContext, Model, MouseButton, ParentElement, Pixels, Render,
SharedString, Styled, Subscription, Task, TextStyle, UniformListScrollHandle, View,
ViewContext, VisualContext, WeakView, WindowContext,
};
use highlight_matching_bracket::refresh_matching_bracket_highlights;
use hover_popover::{hide_hover, HoverState};
@@ -585,7 +585,7 @@ pub enum SoftWrap {
Column(u32),
}
#[derive(Clone)]
#[derive(Clone, Default)]
pub struct EditorStyle {
pub background: Hsla,
pub local_player: PlayerColor,
@@ -907,7 +907,7 @@ impl ContextMenu {
style: &EditorStyle,
workspace: Option<WeakView<Workspace>>,
cx: &mut ViewContext<Editor>,
) -> (DisplayPoint, AnyElement<Editor>) {
) -> (DisplayPoint, AnyElement) {
match self {
ContextMenu::Completions(menu) => (cursor_position, menu.render(style, workspace, cx)),
ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, cx),
@@ -1223,9 +1223,7 @@ impl CompletionsMenu {
style: &EditorStyle,
workspace: Option<WeakView<Workspace>>,
cx: &mut ViewContext<Editor>,
) -> AnyElement<Editor> {
// enum CompletionTag {}
) -> AnyElement {
let settings = EditorSettings::get_global(cx);
let show_completion_documentation = settings.show_completion_documentation;
@@ -1253,121 +1251,126 @@ impl CompletionsMenu {
let matches = self.matches.clone();
let selected_item = self.selected_item;
let list = uniform_list("completions", matches.len(), move |editor, range, cx| {
let start_ix = range.start;
let completions_guard = completions.read();
let list = uniform_list(
cx.view().clone(),
"completions",
matches.len(),
move |editor, range, cx| {
let start_ix = range.start;
let completions_guard = completions.read();
matches[range]
.iter()
.enumerate()
.map(|(ix, mat)| {
let item_ix = start_ix + ix;
let candidate_id = mat.candidate_id;
let completion = &completions_guard[candidate_id];
matches[range]
.iter()
.enumerate()
.map(|(ix, mat)| {
let item_ix = start_ix + ix;
let candidate_id = mat.candidate_id;
let completion = &completions_guard[candidate_id];
let documentation = if show_completion_documentation {
&completion.documentation
} else {
&None
};
let documentation = if show_completion_documentation {
&completion.documentation
} else {
&None
};
// todo!("highlights")
// let highlights = combine_syntax_and_fuzzy_match_highlights(
// &completion.label.text,
// style.text.color.into(),
// styled_runs_for_code_label(&completion.label, &style.syntax),
// &mat.positions,
// )
// todo!("highlights")
// let highlights = combine_syntax_and_fuzzy_match_highlights(
// &completion.label.text,
// style.text.color.into(),
// styled_runs_for_code_label(&completion.label, &style.syntax),
// &mat.positions,
// )
// todo!("documentation")
// MouseEventHandler::new::<CompletionTag, _>(mat.candidate_id, cx, |state, _| {
// let completion_label = HighlightedLabel::new(
// completion.label.text.clone(),
// combine_syntax_and_fuzzy_match_highlights(
// &completion.label.text,
// style.text.color.into(),
// styled_runs_for_code_label(&completion.label, &style.syntax),
// &mat.positions,
// ),
// );
// Text::new(completion.label.text.clone(), style.text.clone())
// .with_soft_wrap(false)
// .with_highlights();
// todo!("documentation")
// MouseEventHandler::new::<CompletionTag, _>(mat.candidate_id, cx, |state, _| {
// let completion_label = HighlightedLabel::new(
// completion.label.text.clone(),
// combine_syntax_and_fuzzy_match_highlights(
// &completion.label.text,
// style.text.color.into(),
// styled_runs_for_code_label(&completion.label, &style.syntax),
// &mat.positions,
// ),
// );
// Text::new(completion.label.text.clone(), style.text.clone())
// .with_soft_wrap(false)
// .with_highlights();
// if let Some(Documentation::SingleLine(text)) = documentation {
// h_stack()
// .child(completion_label)
// .with_children((|| {
// let text_style = TextStyle {
// color: style.autocomplete.inline_docs_color,
// font_size: style.text.font_size
// * style.autocomplete.inline_docs_size_percent,
// ..style.text.clone()
// };
// if let Some(Documentation::SingleLine(text)) = documentation {
// h_stack()
// .child(completion_label)
// .with_children((|| {
// let text_style = TextStyle {
// color: style.autocomplete.inline_docs_color,
// font_size: style.text.font_size
// * style.autocomplete.inline_docs_size_percent,
// ..style.text.clone()
// };
// let label = Text::new(text.clone(), text_style)
// .aligned()
// .constrained()
// .dynamically(move |constraint, _, _| gpui::SizeConstraint {
// min: constraint.min,
// max: vec2f(constraint.max.x(), constraint.min.y()),
// });
// let label = Text::new(text.clone(), text_style)
// .aligned()
// .constrained()
// .dynamically(move |constraint, _, _| gpui::SizeConstraint {
// min: constraint.min,
// max: vec2f(constraint.max.x(), constraint.min.y()),
// });
// if Some(item_ix) == widest_completion_ix {
// Some(
// label
// .contained()
// .with_style(style.autocomplete.inline_docs_container)
// .into_any(),
// )
// } else {
// Some(label.flex_float().into_any())
// }
// })())
// .into_any()
// } else {
// completion_label.into_any()
// }
// .contained()
// .with_style(item_style)
// .constrained()
// .dynamically(move |constraint, _, _| {
// if Some(item_ix) == widest_completion_ix {
// constraint
// } else {
// gpui::SizeConstraint {
// min: constraint.min,
// max: constraint.min,
// }
// }
// })
// })
// .with_cursor_style(CursorStyle::PointingHand)
// .on_down(MouseButton::Left, move |_, this, cx| {
// this.confirm_completion(
// &ConfirmCompletion {
// item_ix: Some(item_ix),
// },
// cx,
// )
// .map(|task| task.detach());
// })
// .constrained()
//
div()
.id(mat.candidate_id)
.bg(gpui::green())
.hover(|style| style.bg(gpui::blue()))
.when(item_ix == selected_item, |div| div.bg(gpui::blue()))
.child(completion.label.text.clone())
.min_w(px(300.))
.max_w(px(700.))
})
.collect()
})
// if Some(item_ix) == widest_completion_ix {
// Some(
// label
// .contained()
// .with_style(style.autocomplete.inline_docs_container)
// .into_any(),
// )
// } else {
// Some(label.flex_float().into_any())
// }
// })())
// .into_any()
// } else {
// completion_label.into_any()
// }
// .contained()
// .with_style(item_style)
// .constrained()
// .dynamically(move |constraint, _, _| {
// if Some(item_ix) == widest_completion_ix {
// constraint
// } else {
// gpui::SizeConstraint {
// min: constraint.min,
// max: constraint.min,
// }
// }
// })
// })
// .with_cursor_style(CursorStyle::PointingHand)
// .on_down(MouseButton::Left, move |_, this, cx| {
// this.confirm_completion(
// &ConfirmCompletion {
// item_ix: Some(item_ix),
// },
// cx,
// )
// .map(|task| task.detach());
// })
// .constrained()
//
div()
.id(mat.candidate_id)
.bg(gpui::green())
.hover(|style| style.bg(gpui::blue()))
.when(item_ix == selected_item, |div| div.bg(gpui::blue()))
.child(SharedString::from(completion.label.text.clone()))
.min_w(px(300.))
.max_w(px(700.))
})
.collect()
},
)
.with_width_from_item(widest_completion_ix);
list.render()
list.render_into_any()
// todo!("multiline documentation")
// enum MultiLineDocumentation {}
@@ -1529,13 +1532,15 @@ impl CodeActionsMenu {
mut cursor_position: DisplayPoint,
style: &EditorStyle,
cx: &mut ViewContext<Editor>,
) -> (DisplayPoint, AnyElement<Editor>) {
) -> (DisplayPoint, AnyElement) {
let actions = self.actions.clone();
let selected_item = self.selected_item;
let element = uniform_list(
cx.view().clone(),
"code_actions_menu",
self.actions.len(),
move |editor, range, cx| {
move |this, range, cx| {
actions[range.clone()]
.iter()
.enumerate()
@@ -1557,18 +1562,22 @@ impl CodeActionsMenu {
.bg(colors.element_hover)
.text_color(colors.text_accent)
})
.on_mouse_down(MouseButton::Left, move |editor: &mut Editor, _, cx| {
cx.stop_propagation();
editor
.confirm_code_action(
&ConfirmCodeAction {
item_ix: Some(item_ix),
},
cx,
)
.map(|task| task.detach_and_log_err(cx));
})
.child(action.lsp_action.title.clone())
.on_mouse_down(
MouseButton::Left,
cx.listener(move |editor, _, cx| {
cx.stop_propagation();
editor
.confirm_code_action(
&ConfirmCodeAction {
item_ix: Some(item_ix),
},
cx,
)
.map(|task| task.detach_and_log_err(cx));
}),
)
// TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
.child(SharedString::from(action.lsp_action.title.clone()))
})
.collect()
},
@@ -1583,7 +1592,7 @@ impl CodeActionsMenu {
.max_by_key(|(_, action)| action.lsp_action.title.chars().count())
.map(|(ix, _)| ix),
)
.render();
.render_into_any();
if self.deployed_from_indicator {
*cursor_position.column_mut() = 0;
@@ -2306,7 +2315,8 @@ impl Editor {
}
self.blink_manager.update(cx, BlinkManager::pause_blinking);
cx.emit(Event::SelectionsChanged { local });
cx.emit(EditorEvent::SelectionsChanged { local });
cx.emit(SearchEvent::MatchesInvalidated);
if self.selections.disjoint_anchors().len() == 1 {
cx.emit(SearchEvent::ActiveMatchChanged)
@@ -4230,7 +4240,7 @@ impl Editor {
self.report_copilot_event(Some(completion.uuid.clone()), true, cx)
}
cx.emit(Event::InputHandled {
cx.emit(EditorEvent::InputHandled {
utf16_range_to_replace: None,
text: suggestion.text.to_string().into(),
});
@@ -4341,19 +4351,19 @@ impl Editor {
style: &EditorStyle,
is_active: bool,
cx: &mut ViewContext<Self>,
) -> Option<AnyElement<Self>> {
) -> Option<IconButton> {
if self.available_code_actions.is_some() {
Some(
IconButton::new("code_actions_indicator", ui::Icon::Bolt)
.on_click(|editor: &mut Editor, cx| {
IconButton::new("code_actions_indicator", ui::Icon::Bolt).on_click(cx.listener(
|editor, e, cx| {
editor.toggle_code_actions(
&ToggleCodeActions {
deployed_from_indicator: true,
},
cx,
);
})
.render(),
},
)),
)
} else {
None
@@ -4368,7 +4378,7 @@ impl Editor {
line_height: Pixels,
gutter_margin: Pixels,
cx: &mut ViewContext<Self>,
) -> Vec<Option<AnyElement<Self>>> {
) -> Vec<Option<IconButton>> {
fold_data
.iter()
.enumerate()
@@ -4381,15 +4391,15 @@ impl Editor {
FoldStatus::Foldable => ui::Icon::ChevronDown,
};
IconButton::new(ix as usize, icon)
.on_click(move |editor: &mut Editor, cx| match fold_status {
.on_click(cx.listener(move |editor, e, cx| match fold_status {
FoldStatus::Folded => {
editor.unfold_at(&UnfoldAt { buffer_row }, cx);
}
FoldStatus::Foldable => {
editor.fold_at(&FoldAt { buffer_row }, cx);
}
})
.render()
}))
.color(ui::Color::Muted)
})
})
.flatten()
@@ -4409,7 +4419,7 @@ impl Editor {
cursor_position: DisplayPoint,
style: &EditorStyle,
cx: &mut ViewContext<Editor>,
) -> Option<(DisplayPoint, AnyElement<Editor>)> {
) -> Option<(DisplayPoint, AnyElement)> {
self.context_menu.read().as_ref().map(|menu| {
menu.render(
cursor_position,
@@ -5627,7 +5637,7 @@ impl Editor {
self.request_autoscroll(Autoscroll::fit(), cx);
self.unmark_text(cx);
self.refresh_copilot_suggestions(true, cx);
cx.emit(Event::Edited);
cx.emit(EditorEvent::Edited);
}
}
@@ -5642,7 +5652,7 @@ impl Editor {
self.request_autoscroll(Autoscroll::fit(), cx);
self.unmark_text(cx);
self.refresh_copilot_suggestions(true, cx);
cx.emit(Event::Edited);
cx.emit(EditorEvent::Edited);
}
}
@@ -7768,7 +7778,7 @@ impl Editor {
}
div()
.pl(cx.anchor_x)
.child(rename_editor.render_with(EditorElement::new(
.child(EditorElement::new(
&rename_editor,
EditorStyle {
background: cx.theme().system().transparent,
@@ -7776,11 +7786,13 @@ impl Editor {
text: text_style,
scrollbar_width: cx.editor_style.scrollbar_width,
syntax: cx.editor_style.syntax.clone(),
diagnostic_style:
cx.editor_style.diagnostic_style.clone(),
diagnostic_style: cx
.editor_style
.diagnostic_style
.clone(),
},
)))
.render()
))
.render_into_any()
}
}),
disposition: BlockDisposition::Below,
@@ -8111,7 +8123,7 @@ impl Editor {
log::error!("unexpectedly ended a transaction that wasn't started by this editor");
}
cx.emit(Event::Edited);
cx.emit(EditorEvent::Edited);
Some(tx_id)
} else {
None
@@ -8699,7 +8711,7 @@ impl Editor {
if self.has_active_copilot_suggestion(cx) {
self.update_visible_copilot_suggestion(cx);
}
cx.emit(Event::BufferEdited);
cx.emit(EditorEvent::BufferEdited);
cx.emit(ItemEvent::Edit);
cx.emit(ItemEvent::UpdateBreadcrumbs);
cx.emit(SearchEvent::MatchesInvalidated);
@@ -8738,7 +8750,7 @@ impl Editor {
predecessor,
excerpts,
} => {
cx.emit(Event::ExcerptsAdded {
cx.emit(EditorEvent::ExcerptsAdded {
buffer: buffer.clone(),
predecessor: *predecessor,
excerpts: excerpts.clone(),
@@ -8747,7 +8759,7 @@ impl Editor {
}
multi_buffer::Event::ExcerptsRemoved { ids } => {
self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
cx.emit(Event::ExcerptsRemoved { ids: ids.clone() })
cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
}
multi_buffer::Event::Reparsed => {
cx.emit(ItemEvent::UpdateBreadcrumbs);
@@ -8761,7 +8773,7 @@ impl Editor {
cx.emit(ItemEvent::UpdateTab);
cx.emit(ItemEvent::UpdateBreadcrumbs);
}
multi_buffer::Event::DiffBaseChanged => cx.emit(Event::DiffBaseChanged),
multi_buffer::Event::DiffBaseChanged => cx.emit(EditorEvent::DiffBaseChanged),
multi_buffer::Event::Closed => cx.emit(ItemEvent::CloseItem),
multi_buffer::Event::DiagnosticsUpdated => {
self.refresh_active_diagnostics(cx);
@@ -8955,12 +8967,12 @@ impl Editor {
let telemetry = project.read(cx).client().telemetry().clone();
let telemetry_settings = *TelemetrySettings::get_global(cx);
let event = ClickhouseEvent::Copilot {
telemetry.report_copilot_event(
telemetry_settings,
suggestion_id,
suggestion_accepted,
file_extension,
};
telemetry.report_clickhouse_event(event, telemetry_settings);
)
}
#[cfg(any(test, feature = "test-support"))]
@@ -9007,14 +9019,14 @@ impl Editor {
.show_copilot_suggestions;
let telemetry = project.read(cx).client().telemetry().clone();
let event = ClickhouseEvent::Editor {
telemetry.report_editor_event(
telemetry_settings,
file_extension,
vim_mode,
operation,
copilot_enabled,
copilot_enabled_for_language,
};
telemetry.report_clickhouse_event(event, telemetry_settings)
)
}
/// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
@@ -9101,7 +9113,7 @@ impl Editor {
cx: &mut ViewContext<Self>,
) {
if !self.input_enabled {
cx.emit(Event::InputIgnored { text: text.into() });
cx.emit(EditorEvent::InputIgnored { text: text.into() });
return;
}
if let Some(relative_utf16_range) = relative_utf16_range {
@@ -9161,7 +9173,7 @@ impl Editor {
}
fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
cx.emit(Event::Focused);
cx.emit(EditorEvent::Focused);
if let Some(rename) = self.pending_rename.as_ref() {
let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
@@ -9191,7 +9203,7 @@ impl Editor {
.update(cx, |buffer, cx| buffer.remove_active_selections(cx));
self.hide_context_menu(cx);
hide_hover(self, cx);
cx.emit(Event::Blurred);
cx.emit(EditorEvent::Blurred);
cx.notify();
}
}
@@ -9314,7 +9326,7 @@ impl Deref for EditorSnapshot {
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
pub enum EditorEvent {
InputIgnored {
text: Arc<str>,
},
@@ -9332,8 +9344,12 @@ pub enum Event {
},
BufferEdited,
Edited,
Reparsed,
Focused,
Blurred,
DirtyChanged,
Saved,
TitleChanged,
DiffBaseChanged,
SelectionsChanged {
local: bool,
@@ -9342,6 +9358,7 @@ pub enum Event {
local: bool,
autoscroll: bool,
},
Closed,
}
pub struct EditorFocused(pub View<Editor>);
@@ -9356,7 +9373,7 @@ pub struct EditorReleased(pub WeakView<Editor>);
// }
// }
//
impl EventEmitter<Event> for Editor {}
impl EventEmitter<EditorEvent> for Editor {}
impl FocusableView for Editor {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
@@ -9559,7 +9576,7 @@ impl InputHandler for Editor {
cx: &mut ViewContext<Self>,
) {
if !self.input_enabled {
cx.emit(Event::InputIgnored { text: text.into() });
cx.emit(EditorEvent::InputIgnored { text: text.into() });
return;
}
@@ -9589,7 +9606,7 @@ impl InputHandler for Editor {
})
});
cx.emit(Event::InputHandled {
cx.emit(EditorEvent::InputHandled {
utf16_range_to_replace: range_to_replace,
text: text.into(),
});
@@ -9620,7 +9637,7 @@ impl InputHandler for Editor {
cx: &mut ViewContext<Self>,
) {
if !self.input_enabled {
cx.emit(Event::InputIgnored { text: text.into() });
cx.emit(EditorEvent::InputIgnored { text: text.into() });
return;
}
@@ -9663,7 +9680,7 @@ impl InputHandler for Editor {
})
});
cx.emit(Event::InputHandled {
cx.emit(EditorEvent::InputHandled {
utf16_range_to_replace: range_to_replace,
text: text.into(),
});
@@ -9978,11 +9995,11 @@ pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> Rend
.ml(cx.anchor_x)
}))
.cursor_pointer()
.on_click(move |_, _, cx| {
.on_click(cx.listener(move |_, _, cx| {
cx.write_to_clipboard(ClipboardItem::new(message.clone()));
})
.tooltip(|_, cx| Tooltip::text("Copy diagnostic message", cx))
.render()
}))
.tooltip(|cx| Tooltip::text("Copy diagnostic message", cx))
.render_into_any()
})
}
+6 -6
View File
@@ -3048,7 +3048,7 @@ fn test_move_line_up_down_with_blocks(cx: &mut TestAppContext) {
position: snapshot.anchor_after(Point::new(2, 0)),
disposition: BlockDisposition::Below,
height: 1,
render: Arc::new(|_| div().render()),
render: Arc::new(|_| div().into_any()),
}],
Some(Autoscroll::fit()),
cx,
@@ -3853,7 +3853,7 @@ async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
let (view, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
view.condition::<crate::Event>(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
view.condition::<crate::EditorEvent>(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
view.update(cx, |view, cx| {
@@ -4019,7 +4019,7 @@ async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
let (editor, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
editor
.condition::<crate::Event>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
.condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
.await;
editor.update(cx, |editor, cx| {
@@ -4583,7 +4583,7 @@ async fn test_surround_with_pair(cx: &mut gpui::TestAppContext) {
});
let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
let (view, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
view.condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
view.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
view.update(cx, |view, cx| {
@@ -4734,7 +4734,7 @@ async fn test_delete_autoclose_pair(cx: &mut gpui::TestAppContext) {
let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
let (editor, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
editor
.condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
editor.update(cx, |editor, cx| {
@@ -6295,7 +6295,7 @@ async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
});
let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
let (view, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
view.condition::<crate::Event>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
view.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
view.update(cx, |view, cx| {
+313 -270
View File
@@ -20,10 +20,10 @@ use collections::{BTreeMap, HashMap};
use gpui::{
div, point, px, relative, size, transparent_black, Action, AnyElement, AvailableSpace,
BorrowWindow, Bounds, Component, ContentMask, Corners, DispatchPhase, Edges, Element,
ElementId, ElementInputHandler, Entity, EntityId, Hsla, InteractiveComponent, LineLayout,
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentComponent, Pixels,
ScrollWheelEvent, ShapedLine, SharedString, Size, StatefulInteractiveComponent, Style, Styled,
TextRun, TextStyle, View, ViewContext, WindowContext, WrappedLine,
ElementId, ElementInputHandler, Entity, EntityId, Hsla, InteractiveElement, LineLayout,
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, RenderOnce,
ScrollWheelEvent, ShapedLine, SharedString, Size, StatefulInteractiveElement, Style, Styled,
TextRun, TextStyle, View, ViewContext, WeakView, WindowContext, WrappedLine,
};
use itertools::Itertools;
use language::language_settings::ShowWhitespaceSetting;
@@ -112,14 +112,14 @@ impl SelectionLayout {
}
pub struct EditorElement {
editor_id: EntityId,
editor: View<Editor>,
style: EditorStyle,
}
impl EditorElement {
pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
Self {
editor_id: editor.entity_id(),
editor: editor.clone(),
style,
}
}
@@ -349,7 +349,7 @@ impl EditorElement {
gutter_bounds: Bounds<Pixels>,
text_bounds: Bounds<Pixels>,
layout: &LayoutState,
cx: &mut ViewContext<Editor>,
cx: &mut WindowContext,
) {
let bounds = gutter_bounds.union(&text_bounds);
let scroll_top =
@@ -460,7 +460,7 @@ impl EditorElement {
bounds: Bounds<Pixels>,
layout: &mut LayoutState,
editor: &mut Editor,
cx: &mut ViewContext<Editor>,
cx: &mut WindowContext,
) {
let line_height = layout.position_map.line_height;
@@ -488,13 +488,14 @@ impl EditorElement {
}
}
for (ix, fold_indicator) in layout.fold_indicators.iter_mut().enumerate() {
if let Some(fold_indicator) = fold_indicator.as_mut() {
for (ix, fold_indicator) in layout.fold_indicators.drain(..).enumerate() {
if let Some(mut fold_indicator) = fold_indicator {
let mut fold_indicator = fold_indicator.render_into_any();
let available_space = size(
AvailableSpace::MinContent,
AvailableSpace::Definite(line_height * 0.55),
);
let fold_indicator_size = fold_indicator.measure(available_space, editor, cx);
let fold_indicator_size = fold_indicator.measure(available_space, cx);
let position = point(
bounds.size.width - layout.gutter_padding,
@@ -505,32 +506,29 @@ impl EditorElement {
(line_height - fold_indicator_size.height) / 2.,
);
let origin = bounds.origin + position + centering_offset;
fold_indicator.draw(origin, available_space, editor, cx);
fold_indicator.draw(origin, available_space, cx);
}
}
if let Some(indicator) = layout.code_actions_indicator.as_mut() {
if let Some(indicator) = layout.code_actions_indicator.take() {
let mut button = indicator.button.render_into_any();
let available_space = size(
AvailableSpace::MinContent,
AvailableSpace::Definite(line_height),
);
let indicator_size = indicator.element.measure(available_space, editor, cx);
let indicator_size = button.measure(available_space, cx);
let mut x = Pixels::ZERO;
let mut y = indicator.row as f32 * line_height - scroll_top;
// Center indicator.
x += ((layout.gutter_padding + layout.gutter_margin) - indicator_size.width) / 2.;
y += (line_height - indicator_size.height) / 2.;
indicator
.element
.draw(bounds.origin + point(x, y), available_space, editor, cx);
button.draw(bounds.origin + point(x, y), available_space, cx);
}
}
fn paint_diff_hunks(
bounds: Bounds<Pixels>,
layout: &LayoutState,
cx: &mut ViewContext<Editor>,
) {
fn paint_diff_hunks(bounds: Bounds<Pixels>, layout: &LayoutState, cx: &mut WindowContext) {
// todo!()
// let diff_style = &theme::current(cx).editor.diff.clone();
// let line_height = layout.position_map.line_height;
@@ -619,7 +617,7 @@ impl EditorElement {
text_bounds: Bounds<Pixels>,
layout: &mut LayoutState,
editor: &mut Editor,
cx: &mut ViewContext<Editor>,
cx: &mut WindowContext,
) {
let scroll_position = layout.position_map.snapshot.scroll_position();
let start_row = layout.visible_display_row_range.start;
@@ -674,20 +672,22 @@ impl EditorElement {
div()
.id(fold.id)
.size_full()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(move |editor: &mut Editor, _, cx| {
editor.unfold_ranges(
[fold_range.start..fold_range.end],
true,
false,
cx,
);
cx.stop_propagation();
})
.on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
.on_click(cx.listener_for(
&self.editor,
move |editor: &mut Editor, _, cx| {
editor.unfold_ranges(
[fold_range.start..fold_range.end],
true,
false,
cx,
);
cx.stop_propagation();
},
))
.draw(
fold_bounds.origin,
fold_bounds.size,
editor,
cx,
|fold_element_state, cx| {
if fold_element_state.is_active() {
@@ -840,7 +840,7 @@ impl EditorElement {
}
});
if let Some((position, context_menu)) = layout.context_menu.as_mut() {
if let Some((position, mut context_menu)) = layout.context_menu.take() {
cx.with_z_index(1, |cx| {
let line_height = self.style.text.line_height_in_pixels(cx.rem_size());
let available_space = size(
@@ -850,7 +850,7 @@ impl EditorElement {
.min((text_bounds.size.height - line_height) / 2.),
),
);
let context_menu_size = context_menu.measure(available_space, editor, cx);
let context_menu_size = context_menu.measure(available_space, cx);
let cursor_row_layout = &layout.position_map.line_layouts
[(position.row() - start_row) as usize]
@@ -874,7 +874,7 @@ impl EditorElement {
list_origin.y -= layout.position_map.line_height - list_height;
}
context_menu.draw(list_origin, available_space, editor, cx);
context_menu.draw(list_origin, available_space, cx);
})
}
@@ -1165,7 +1165,7 @@ impl EditorElement {
layout: &LayoutState,
content_origin: gpui::Point<Pixels>,
bounds: Bounds<Pixels>,
cx: &mut ViewContext<Editor>,
cx: &mut WindowContext,
) {
let start_row = layout.visible_display_row_range.start;
let end_row = layout.visible_display_row_range.end;
@@ -1218,13 +1218,13 @@ impl EditorElement {
bounds: Bounds<Pixels>,
layout: &mut LayoutState,
editor: &mut Editor,
cx: &mut ViewContext<Editor>,
cx: &mut WindowContext,
) {
let scroll_position = layout.position_map.snapshot.scroll_position();
let scroll_left = scroll_position.x * layout.position_map.em_width;
let scroll_top = scroll_position.y * layout.position_map.line_height;
for block in &mut layout.blocks {
for block in layout.blocks.drain(..) {
let mut origin = bounds.origin
+ point(
Pixels::ZERO,
@@ -1233,9 +1233,7 @@ impl EditorElement {
if !matches!(block.style, BlockStyle::Sticky) {
origin += point(-scroll_left, Pixels::ZERO);
}
block
.element
.draw(origin, block.available_space, editor, cx);
block.element.draw(origin, block.available_space, cx);
}
}
@@ -1810,7 +1808,7 @@ impl EditorElement {
.render_code_actions_indicator(&style, active, cx)
.map(|element| CodeActionsIndicator {
row: newest_selection_head.row(),
element,
button: element,
});
}
}
@@ -1970,6 +1968,7 @@ impl EditorElement {
TransformBlock::ExcerptHeader { .. } => false,
TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
});
let mut render_block = |block: &TransformBlock,
available_space: Size<AvailableSpace>,
block_id: usize,
@@ -2003,6 +2002,7 @@ impl EditorElement {
editor_style: &self.style,
})
}
TransformBlock::ExcerptHeader {
buffer,
range,
@@ -2026,12 +2026,10 @@ impl EditorElement {
let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
IconButton::new(block_id, ui::Icon::ArrowUpRight)
.on_click(move |editor: &mut Editor, cx| {
.on_click(cx.listener_for(&self.editor, move |editor, e, cx| {
editor.jump(jump_path.clone(), jump_position, jump_anchor, cx);
})
.tooltip(move |_, cx| {
Tooltip::for_action("Jump to Buffer", &OpenExcerpts, cx)
})
}))
.tooltip(|cx| Tooltip::for_action("Jump to Buffer", &OpenExcerpts, cx))
});
let element = if *starts_new_buffer {
@@ -2041,29 +2039,36 @@ impl EditorElement {
// Can't use .and_then() because `.file_name()` and `.parent()` return references :(
if let Some(path) = path {
filename = path.file_name().map(|f| f.to_string_lossy().to_string());
parent_path =
path.parent().map(|p| p.to_string_lossy().to_string() + "/");
parent_path = path
.parent()
.map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
}
h_stack()
.id("path header block")
.size_full()
.bg(gpui::red())
.child(filename.unwrap_or_else(|| "untitled".to_string()))
.child(
filename
.map(SharedString::from)
.unwrap_or_else(|| "untitled".into()),
)
.children(parent_path)
.children(jump_icon) // .p_x(gutter_padding)
} else {
let text_style = style.text.clone();
h_stack()
.id("collapsed context")
.size_full()
.bg(gpui::red())
.child("⋯")
.children(jump_icon) // .p_x(gutter_padding)
};
element.render()
element.into_any()
}
};
let size = element.measure(available_space, editor, cx);
let size = element.measure(available_space, cx);
(element, size)
};
@@ -2122,47 +2127,61 @@ impl EditorElement {
gutter_bounds: Bounds<Pixels>,
text_bounds: Bounds<Pixels>,
layout: &LayoutState,
cx: &mut ViewContext<Editor>,
cx: &mut WindowContext,
) {
let content_origin = text_bounds.origin + point(layout.gutter_margin, Pixels::ZERO);
cx.on_mouse_event({
let position_map = layout.position_map.clone();
move |editor, event: &ScrollWheelEvent, phase, cx| {
let editor = self.editor.clone();
move |event: &ScrollWheelEvent, phase, cx| {
if phase != DispatchPhase::Bubble {
return;
}
if Self::scroll(editor, event, &position_map, bounds, cx) {
let should_cancel = editor.update(cx, |editor, cx| {
Self::scroll(editor, event, &position_map, bounds, cx)
});
if should_cancel {
cx.stop_propagation();
}
}
});
cx.on_mouse_event({
let position_map = layout.position_map.clone();
move |editor, event: &MouseDownEvent, phase, cx| {
let editor = self.editor.clone();
move |event: &MouseDownEvent, phase, cx| {
if phase != DispatchPhase::Bubble {
return;
}
if Self::mouse_down(editor, event, &position_map, text_bounds, gutter_bounds, cx) {
let should_cancel = editor.update(cx, |editor, cx| {
Self::mouse_down(editor, event, &position_map, text_bounds, gutter_bounds, cx)
});
if should_cancel {
cx.stop_propagation()
}
}
});
cx.on_mouse_event({
let position_map = layout.position_map.clone();
move |editor, event: &MouseUpEvent, phase, cx| {
if phase != DispatchPhase::Bubble {
return;
}
let editor = self.editor.clone();
move |event: &MouseUpEvent, phase, cx| {
let should_cancel = editor.update(cx, |editor, cx| {
Self::mouse_up(editor, event, &position_map, text_bounds, cx)
});
if Self::mouse_up(editor, event, &position_map, text_bounds, cx) {
if should_cancel {
cx.stop_propagation()
}
}
});
// todo!()
//todo!()
// on_down(MouseButton::Right, {
// let position_map = layout.position_map.clone();
// move |event, editor, cx| {
@@ -2179,12 +2198,17 @@ impl EditorElement {
// });
cx.on_mouse_event({
let position_map = layout.position_map.clone();
move |editor, event: &MouseMoveEvent, phase, cx| {
let editor = self.editor.clone();
move |event: &MouseMoveEvent, phase, cx| {
if phase != DispatchPhase::Bubble {
return;
}
if Self::mouse_moved(editor, event, &position_map, text_bounds, gutter_bounds, cx) {
let stop_propogating = editor.update(cx, |editor, cx| {
Self::mouse_moved(editor, event, &position_map, text_bounds, gutter_bounds, cx)
});
if stop_propogating {
cx.stop_propagation()
}
}
@@ -2313,7 +2337,7 @@ impl LineWithInvisibles {
content_origin: gpui::Point<Pixels>,
whitespace_setting: ShowWhitespaceSetting,
selection_ranges: &[Range<DisplayPoint>],
cx: &mut ViewContext<Editor>,
cx: &mut WindowContext,
) {
let line_height = layout.position_map.line_height;
let line_y = line_height * row as f32 - layout.position_map.scroll_position.y;
@@ -2345,7 +2369,7 @@ impl LineWithInvisibles {
row: u32,
line_height: Pixels,
whitespace_setting: ShowWhitespaceSetting,
cx: &mut ViewContext<Editor>,
cx: &mut WindowContext,
) {
let allowed_invisibles_regions = match whitespace_setting {
ShowWhitespaceSetting::None => return,
@@ -2388,87 +2412,102 @@ enum Invisible {
Whitespace { line_offset: usize },
}
impl Element<Editor> for EditorElement {
type ElementState = ();
fn element_id(&self) -> Option<gpui::ElementId> {
Some(self.editor_id.into())
}
impl Element for EditorElement {
type State = ();
fn layout(
&mut self,
editor: &mut Editor,
element_state: Option<Self::ElementState>,
cx: &mut gpui::ViewContext<Editor>,
) -> (gpui::LayoutId, Self::ElementState) {
editor.style = Some(self.style.clone()); // Long-term, we'd like to eliminate this.
element_state: Option<Self::State>,
cx: &mut gpui::WindowContext,
) -> (gpui::LayoutId, Self::State) {
self.editor.update(cx, |editor, cx| {
editor.style = Some(self.style.clone()); // Long-term, we'd like to eliminate this.
let rem_size = cx.rem_size();
let mut style = Style::default();
style.size.width = relative(1.).into();
style.size.height = match editor.mode {
EditorMode::SingleLine => self.style.text.line_height_in_pixels(cx.rem_size()).into(),
EditorMode::AutoHeight { .. } => todo!(),
EditorMode::Full => relative(1.).into(),
};
let layout_id = cx.request_layout(&style, None);
(layout_id, ())
let rem_size = cx.rem_size();
let mut style = Style::default();
style.size.width = relative(1.).into();
style.size.height = match editor.mode {
EditorMode::SingleLine => {
self.style.text.line_height_in_pixels(cx.rem_size()).into()
}
EditorMode::AutoHeight { .. } => todo!(),
EditorMode::Full => relative(1.).into(),
};
let layout_id = cx.request_layout(&style, None);
(layout_id, ())
})
}
fn paint(
&mut self,
mut self,
bounds: Bounds<gpui::Pixels>,
editor: &mut Editor,
element_state: &mut Self::ElementState,
cx: &mut gpui::ViewContext<Editor>,
element_state: &mut Self::State,
cx: &mut gpui::WindowContext,
) {
let mut layout = self.compute_layout(editor, cx, bounds);
let gutter_bounds = Bounds {
origin: bounds.origin,
size: layout.gutter_size,
};
let text_bounds = Bounds {
origin: gutter_bounds.upper_right(),
size: layout.text_size,
};
let editor = self.editor.clone();
editor.update(cx, |editor, cx| {
let mut layout = self.compute_layout(editor, cx, bounds);
let gutter_bounds = Bounds {
origin: bounds.origin,
size: layout.gutter_size,
};
let text_bounds = Bounds {
origin: gutter_bounds.upper_right(),
size: layout.text_size,
};
let dispatch_context = editor.dispatch_context(cx);
cx.with_key_dispatch(
dispatch_context,
Some(editor.focus_handle.clone()),
|_, cx| {
register_actions(cx);
let dispatch_context = editor.dispatch_context(cx);
let editor_handle = cx.view().clone();
cx.with_key_dispatch(
dispatch_context,
Some(editor.focus_handle.clone()),
|_, cx| {
register_actions(&editor_handle, cx);
// We call with_z_index to establish a new stacking context.
cx.with_z_index(0, |cx| {
cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
// Paint mouse listeners first, so any elements we paint on top of the editor
// take precedence.
self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx);
let input_handler = ElementInputHandler::new(bounds, cx);
cx.handle_input(&editor.focus_handle, input_handler);
// We call with_z_index to establish a new stacking context.
cx.with_z_index(0, |cx| {
cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
// Paint mouse listeners first, so any elements we paint on top of the editor
// take precedence.
self.paint_mouse_listeners(
bounds,
gutter_bounds,
text_bounds,
&layout,
cx,
);
let input_handler = ElementInputHandler::new(bounds, editor_handle, cx);
cx.handle_input(&editor.focus_handle, input_handler);
self.paint_background(gutter_bounds, text_bounds, &layout, cx);
if layout.gutter_size.width > Pixels::ZERO {
self.paint_gutter(gutter_bounds, &mut layout, editor, cx);
}
self.paint_text(text_bounds, &mut layout, editor, cx);
self.paint_background(gutter_bounds, text_bounds, &layout, cx);
if layout.gutter_size.width > Pixels::ZERO {
self.paint_gutter(gutter_bounds, &mut layout, editor, cx);
}
self.paint_text(text_bounds, &mut layout, editor, cx);
if !layout.blocks.is_empty() {
cx.with_element_id(Some("editor_blocks"), |cx| {
self.paint_blocks(bounds, &mut layout, editor, cx);
})
}
if !layout.blocks.is_empty() {
cx.with_element_id(Some("editor_blocks"), |cx| {
self.paint_blocks(bounds, &mut layout, editor, cx);
})
}
});
});
});
},
)
},
)
})
}
}
impl Component<Editor> for EditorElement {
fn render(self) -> AnyElement<Editor> {
AnyElement::new(self)
impl RenderOnce for EditorElement {
type Element = Self;
fn element_id(&self) -> Option<gpui::ElementId> {
self.editor.element_id()
}
fn render_once(self) -> Self::Element {
self
}
}
@@ -3093,17 +3132,17 @@ pub struct LayoutState {
show_scrollbars: bool,
is_singleton: bool,
max_row: u32,
context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
context_menu: Option<(DisplayPoint, AnyElement)>,
code_actions_indicator: Option<CodeActionsIndicator>,
// hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
fold_indicators: Vec<Option<AnyElement<Editor>>>,
// hover_popovers: Option<(DisplayPoint, Vec<AnyElement>)>,
fold_indicators: Vec<Option<IconButton>>,
tab_invisible: ShapedLine,
space_invisible: ShapedLine,
}
struct CodeActionsIndicator {
row: u32,
element: AnyElement<Editor>,
button: IconButton,
}
struct PositionMap {
@@ -3188,7 +3227,7 @@ impl PositionMap {
struct BlockLayout {
row: u32,
element: AnyElement<Editor>,
element: AnyElement,
available_space: Size<AvailableSpace>,
style: BlockStyle,
}
@@ -3893,187 +3932,191 @@ fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
// }
// }
fn register_actions(cx: &mut ViewContext<Editor>) {
register_action(cx, Editor::move_left);
register_action(cx, Editor::move_right);
register_action(cx, Editor::move_down);
register_action(cx, Editor::move_up);
fn register_actions(view: &View<Editor>, cx: &mut WindowContext) {
register_action(view, cx, Editor::move_left);
register_action(view, cx, Editor::move_right);
register_action(view, cx, Editor::move_down);
register_action(view, cx, Editor::move_up);
// on_action(cx, Editor::new_file); todo!()
// on_action(cx, Editor::new_file_in_direction); todo!()
register_action(cx, Editor::cancel);
register_action(cx, Editor::newline);
register_action(cx, Editor::newline_above);
register_action(cx, Editor::newline_below);
register_action(cx, Editor::backspace);
register_action(cx, Editor::delete);
register_action(cx, Editor::tab);
register_action(cx, Editor::tab_prev);
register_action(cx, Editor::indent);
register_action(cx, Editor::outdent);
register_action(cx, Editor::delete_line);
register_action(cx, Editor::join_lines);
register_action(cx, Editor::sort_lines_case_sensitive);
register_action(cx, Editor::sort_lines_case_insensitive);
register_action(cx, Editor::reverse_lines);
register_action(cx, Editor::shuffle_lines);
register_action(cx, Editor::convert_to_upper_case);
register_action(cx, Editor::convert_to_lower_case);
register_action(cx, Editor::convert_to_title_case);
register_action(cx, Editor::convert_to_snake_case);
register_action(cx, Editor::convert_to_kebab_case);
register_action(cx, Editor::convert_to_upper_camel_case);
register_action(cx, Editor::convert_to_lower_camel_case);
register_action(cx, Editor::delete_to_previous_word_start);
register_action(cx, Editor::delete_to_previous_subword_start);
register_action(cx, Editor::delete_to_next_word_end);
register_action(cx, Editor::delete_to_next_subword_end);
register_action(cx, Editor::delete_to_beginning_of_line);
register_action(cx, Editor::delete_to_end_of_line);
register_action(cx, Editor::cut_to_end_of_line);
register_action(cx, Editor::duplicate_line);
register_action(cx, Editor::move_line_up);
register_action(cx, Editor::move_line_down);
register_action(cx, Editor::transpose);
register_action(cx, Editor::cut);
register_action(cx, Editor::copy);
register_action(cx, Editor::paste);
register_action(cx, Editor::undo);
register_action(cx, Editor::redo);
register_action(cx, Editor::move_page_up);
register_action(cx, Editor::move_page_down);
register_action(cx, Editor::next_screen);
register_action(cx, Editor::scroll_cursor_top);
register_action(cx, Editor::scroll_cursor_center);
register_action(cx, Editor::scroll_cursor_bottom);
register_action(cx, |editor, _: &LineDown, cx| {
register_action(view, cx, Editor::cancel);
register_action(view, cx, Editor::newline);
register_action(view, cx, Editor::newline_above);
register_action(view, cx, Editor::newline_below);
register_action(view, cx, Editor::backspace);
register_action(view, cx, Editor::delete);
register_action(view, cx, Editor::tab);
register_action(view, cx, Editor::tab_prev);
register_action(view, cx, Editor::indent);
register_action(view, cx, Editor::outdent);
register_action(view, cx, Editor::delete_line);
register_action(view, cx, Editor::join_lines);
register_action(view, cx, Editor::sort_lines_case_sensitive);
register_action(view, cx, Editor::sort_lines_case_insensitive);
register_action(view, cx, Editor::reverse_lines);
register_action(view, cx, Editor::shuffle_lines);
register_action(view, cx, Editor::convert_to_upper_case);
register_action(view, cx, Editor::convert_to_lower_case);
register_action(view, cx, Editor::convert_to_title_case);
register_action(view, cx, Editor::convert_to_snake_case);
register_action(view, cx, Editor::convert_to_kebab_case);
register_action(view, cx, Editor::convert_to_upper_camel_case);
register_action(view, cx, Editor::convert_to_lower_camel_case);
register_action(view, cx, Editor::delete_to_previous_word_start);
register_action(view, cx, Editor::delete_to_previous_subword_start);
register_action(view, cx, Editor::delete_to_next_word_end);
register_action(view, cx, Editor::delete_to_next_subword_end);
register_action(view, cx, Editor::delete_to_beginning_of_line);
register_action(view, cx, Editor::delete_to_end_of_line);
register_action(view, cx, Editor::cut_to_end_of_line);
register_action(view, cx, Editor::duplicate_line);
register_action(view, cx, Editor::move_line_up);
register_action(view, cx, Editor::move_line_down);
register_action(view, cx, Editor::transpose);
register_action(view, cx, Editor::cut);
register_action(view, cx, Editor::copy);
register_action(view, cx, Editor::paste);
register_action(view, cx, Editor::undo);
register_action(view, cx, Editor::redo);
register_action(view, cx, Editor::move_page_up);
register_action(view, cx, Editor::move_page_down);
register_action(view, cx, Editor::next_screen);
register_action(view, cx, Editor::scroll_cursor_top);
register_action(view, cx, Editor::scroll_cursor_center);
register_action(view, cx, Editor::scroll_cursor_bottom);
register_action(view, cx, |editor, _: &LineDown, cx| {
editor.scroll_screen(&ScrollAmount::Line(1.), cx)
});
register_action(cx, |editor, _: &LineUp, cx| {
register_action(view, cx, |editor, _: &LineUp, cx| {
editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
});
register_action(cx, |editor, _: &HalfPageDown, cx| {
register_action(view, cx, |editor, _: &HalfPageDown, cx| {
editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
});
register_action(cx, |editor, _: &HalfPageUp, cx| {
register_action(view, cx, |editor, _: &HalfPageUp, cx| {
editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
});
register_action(cx, |editor, _: &PageDown, cx| {
register_action(view, cx, |editor, _: &PageDown, cx| {
editor.scroll_screen(&ScrollAmount::Page(1.), cx)
});
register_action(cx, |editor, _: &PageUp, cx| {
register_action(view, cx, |editor, _: &PageUp, cx| {
editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
});
register_action(cx, Editor::move_to_previous_word_start);
register_action(cx, Editor::move_to_previous_subword_start);
register_action(cx, Editor::move_to_next_word_end);
register_action(cx, Editor::move_to_next_subword_end);
register_action(cx, Editor::move_to_beginning_of_line);
register_action(cx, Editor::move_to_end_of_line);
register_action(cx, Editor::move_to_start_of_paragraph);
register_action(cx, Editor::move_to_end_of_paragraph);
register_action(cx, Editor::move_to_beginning);
register_action(cx, Editor::move_to_end);
register_action(cx, Editor::select_up);
register_action(cx, Editor::select_down);
register_action(cx, Editor::select_left);
register_action(cx, Editor::select_right);
register_action(cx, Editor::select_to_previous_word_start);
register_action(cx, Editor::select_to_previous_subword_start);
register_action(cx, Editor::select_to_next_word_end);
register_action(cx, Editor::select_to_next_subword_end);
register_action(cx, Editor::select_to_beginning_of_line);
register_action(cx, Editor::select_to_end_of_line);
register_action(cx, Editor::select_to_start_of_paragraph);
register_action(cx, Editor::select_to_end_of_paragraph);
register_action(cx, Editor::select_to_beginning);
register_action(cx, Editor::select_to_end);
register_action(cx, Editor::select_all);
register_action(cx, |editor, action, cx| {
register_action(view, cx, Editor::move_to_previous_word_start);
register_action(view, cx, Editor::move_to_previous_subword_start);
register_action(view, cx, Editor::move_to_next_word_end);
register_action(view, cx, Editor::move_to_next_subword_end);
register_action(view, cx, Editor::move_to_beginning_of_line);
register_action(view, cx, Editor::move_to_end_of_line);
register_action(view, cx, Editor::move_to_start_of_paragraph);
register_action(view, cx, Editor::move_to_end_of_paragraph);
register_action(view, cx, Editor::move_to_beginning);
register_action(view, cx, Editor::move_to_end);
register_action(view, cx, Editor::select_up);
register_action(view, cx, Editor::select_down);
register_action(view, cx, Editor::select_left);
register_action(view, cx, Editor::select_right);
register_action(view, cx, Editor::select_to_previous_word_start);
register_action(view, cx, Editor::select_to_previous_subword_start);
register_action(view, cx, Editor::select_to_next_word_end);
register_action(view, cx, Editor::select_to_next_subword_end);
register_action(view, cx, Editor::select_to_beginning_of_line);
register_action(view, cx, Editor::select_to_end_of_line);
register_action(view, cx, Editor::select_to_start_of_paragraph);
register_action(view, cx, Editor::select_to_end_of_paragraph);
register_action(view, cx, Editor::select_to_beginning);
register_action(view, cx, Editor::select_to_end);
register_action(view, cx, Editor::select_all);
register_action(view, cx, |editor, action, cx| {
editor.select_all_matches(action, cx).log_err();
});
register_action(cx, Editor::select_line);
register_action(cx, Editor::split_selection_into_lines);
register_action(cx, Editor::add_selection_above);
register_action(cx, Editor::add_selection_below);
register_action(cx, |editor, action, cx| {
register_action(view, cx, Editor::select_line);
register_action(view, cx, Editor::split_selection_into_lines);
register_action(view, cx, Editor::add_selection_above);
register_action(view, cx, Editor::add_selection_below);
register_action(view, cx, |editor, action, cx| {
editor.select_next(action, cx).log_err();
});
register_action(cx, |editor, action, cx| {
register_action(view, cx, |editor, action, cx| {
editor.select_previous(action, cx).log_err();
});
register_action(cx, Editor::toggle_comments);
register_action(cx, Editor::select_larger_syntax_node);
register_action(cx, Editor::select_smaller_syntax_node);
register_action(cx, Editor::move_to_enclosing_bracket);
register_action(cx, Editor::undo_selection);
register_action(cx, Editor::redo_selection);
register_action(cx, Editor::go_to_diagnostic);
register_action(cx, Editor::go_to_prev_diagnostic);
register_action(cx, Editor::go_to_hunk);
register_action(cx, Editor::go_to_prev_hunk);
register_action(cx, Editor::go_to_definition);
register_action(cx, Editor::go_to_definition_split);
register_action(cx, Editor::go_to_type_definition);
register_action(cx, Editor::go_to_type_definition_split);
register_action(cx, Editor::fold);
register_action(cx, Editor::fold_at);
register_action(cx, Editor::unfold_lines);
register_action(cx, Editor::unfold_at);
register_action(cx, Editor::fold_selected_ranges);
register_action(cx, Editor::show_completions);
register_action(cx, Editor::toggle_code_actions);
register_action(view, cx, Editor::toggle_comments);
register_action(view, cx, Editor::select_larger_syntax_node);
register_action(view, cx, Editor::select_smaller_syntax_node);
register_action(view, cx, Editor::move_to_enclosing_bracket);
register_action(view, cx, Editor::undo_selection);
register_action(view, cx, Editor::redo_selection);
register_action(view, cx, Editor::go_to_diagnostic);
register_action(view, cx, Editor::go_to_prev_diagnostic);
register_action(view, cx, Editor::go_to_hunk);
register_action(view, cx, Editor::go_to_prev_hunk);
register_action(view, cx, Editor::go_to_definition);
register_action(view, cx, Editor::go_to_definition_split);
register_action(view, cx, Editor::go_to_type_definition);
register_action(view, cx, Editor::go_to_type_definition_split);
register_action(view, cx, Editor::fold);
register_action(view, cx, Editor::fold_at);
register_action(view, cx, Editor::unfold_lines);
register_action(view, cx, Editor::unfold_at);
register_action(view, cx, Editor::fold_selected_ranges);
register_action(view, cx, Editor::show_completions);
register_action(view, cx, Editor::toggle_code_actions);
// on_action(cx, Editor::open_excerpts); todo!()
register_action(cx, Editor::toggle_soft_wrap);
register_action(cx, Editor::toggle_inlay_hints);
register_action(cx, Editor::reveal_in_finder);
register_action(cx, Editor::copy_path);
register_action(cx, Editor::copy_relative_path);
register_action(cx, Editor::copy_highlight_json);
register_action(cx, |editor, action, cx| {
register_action(view, cx, Editor::toggle_soft_wrap);
register_action(view, cx, Editor::toggle_inlay_hints);
register_action(view, cx, Editor::reveal_in_finder);
register_action(view, cx, Editor::copy_path);
register_action(view, cx, Editor::copy_relative_path);
register_action(view, cx, Editor::copy_highlight_json);
register_action(view, cx, |editor, action, cx| {
editor
.format(action, cx)
.map(|task| task.detach_and_log_err(cx));
});
register_action(cx, Editor::restart_language_server);
register_action(cx, Editor::show_character_palette);
register_action(view, cx, Editor::restart_language_server);
register_action(view, cx, Editor::show_character_palette);
// on_action(cx, Editor::confirm_completion); todo!()
register_action(cx, |editor, action, cx| {
register_action(view, cx, |editor, action, cx| {
editor
.confirm_code_action(action, cx)
.map(|task| task.detach_and_log_err(cx));
});
register_action(cx, |editor, action, cx| {
register_action(view, cx, |editor, action, cx| {
editor
.rename(action, cx)
.map(|task| task.detach_and_log_err(cx));
});
register_action(cx, |editor, action, cx| {
register_action(view, cx, |editor, action, cx| {
editor
.confirm_rename(action, cx)
.map(|task| task.detach_and_log_err(cx));
});
register_action(cx, |editor, action, cx| {
register_action(view, cx, |editor, action, cx| {
editor
.find_all_references(action, cx)
.map(|task| task.detach_and_log_err(cx));
});
register_action(cx, Editor::next_copilot_suggestion);
register_action(cx, Editor::previous_copilot_suggestion);
register_action(cx, Editor::copilot_suggest);
register_action(cx, Editor::context_menu_first);
register_action(cx, Editor::context_menu_prev);
register_action(cx, Editor::context_menu_next);
register_action(cx, Editor::context_menu_last);
register_action(view, cx, Editor::next_copilot_suggestion);
register_action(view, cx, Editor::previous_copilot_suggestion);
register_action(view, cx, Editor::copilot_suggest);
register_action(view, cx, Editor::context_menu_first);
register_action(view, cx, Editor::context_menu_prev);
register_action(view, cx, Editor::context_menu_next);
register_action(view, cx, Editor::context_menu_last);
}
fn register_action<T: Action>(
cx: &mut ViewContext<Editor>,
view: &View<Editor>,
cx: &mut WindowContext,
listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
) {
cx.on_action(TypeId::of::<T>(), move |editor, action, phase, cx| {
let view = view.clone();
cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
let action = action.downcast_ref().unwrap();
if phase == DispatchPhase::Bubble {
listener(editor, action, cx);
view.update(cx, |editor, cx| {
listener(editor, action, cx);
})
}
})
}
+2 -2
View File
@@ -422,7 +422,7 @@ impl HoverState {
visible_rows: Range<u32>,
workspace: Option<WeakView<Workspace>>,
cx: &mut ViewContext<Editor>,
) -> Option<(DisplayPoint, Vec<AnyElement<Editor>>)> {
) -> Option<(DisplayPoint, Vec<AnyElement>)> {
todo!("old version below")
}
// // If there is a diagnostic, position the popovers based on that.
@@ -504,7 +504,7 @@ pub struct DiagnosticPopover {
}
impl DiagnosticPopover {
pub fn render(&self, style: &EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {
pub fn render(&self, style: &EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement {
todo!()
// enum PrimaryDiagnostic {}
+33 -36
View File
@@ -1,7 +1,7 @@
use crate::{
editor_settings::SeedQuerySetting, link_go_to_definition::hide_link_definition,
movement::surrounding_word, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll, Editor,
EditorSettings, Event, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot,
EditorEvent, EditorSettings, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot,
NavigationData, ToPoint as _,
};
use anyhow::{anyhow, Context, Result};
@@ -9,8 +9,8 @@ use collections::HashSet;
use futures::future::try_join_all;
use gpui::{
div, point, AnyElement, AppContext, AsyncAppContext, Entity, EntityId, EventEmitter,
FocusHandle, Model, ParentComponent, Pixels, SharedString, Styled, Subscription, Task, View,
ViewContext, VisualContext, WeakView,
FocusHandle, Model, ParentElement, Pixels, SharedString, Styled, Subscription, Task, View,
ViewContext, VisualContext, WeakView, WindowContext,
};
use language::{
proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, OffsetRangeExt,
@@ -30,7 +30,7 @@ use std::{
};
use text::Selection;
use theme::{ActiveTheme, Theme};
use ui::{Label, TextColor};
use ui::{Color, Label};
use util::{paths::PathExt, ResultExt, TryFutureExt};
use workspace::item::{BreadcrumbText, FollowEvent, FollowableEvents, FollowableItemHandle};
use workspace::{
@@ -41,11 +41,12 @@ use workspace::{
pub const MAX_TAB_TITLE_LEN: usize = 24;
impl FollowableEvents for Event {
impl FollowableEvents for EditorEvent {
fn to_follow_event(&self) -> Option<workspace::item::FollowEvent> {
match self {
Event::Edited => Some(FollowEvent::Unfollow),
Event::SelectionsChanged { local } | Event::ScrollPositionChanged { local, .. } => {
EditorEvent::Edited => Some(FollowEvent::Unfollow),
EditorEvent::SelectionsChanged { local }
| EditorEvent::ScrollPositionChanged { local, .. } => {
if *local {
Some(FollowEvent::Unfollow)
} else {
@@ -60,7 +61,7 @@ impl FollowableEvents for Event {
impl EventEmitter<ItemEvent> for Editor {}
impl FollowableItem for Editor {
type FollowableEvent = Event;
type FollowableEvent = EditorEvent;
fn remote_id(&self) -> Option<ViewId> {
self.remote_id
}
@@ -248,7 +249,7 @@ impl FollowableItem for Editor {
match update {
proto::update_view::Variant::Editor(update) => match event {
Event::ExcerptsAdded {
EditorEvent::ExcerptsAdded {
buffer,
predecessor,
excerpts,
@@ -269,20 +270,20 @@ impl FollowableItem for Editor {
}
true
}
Event::ExcerptsRemoved { ids } => {
EditorEvent::ExcerptsRemoved { ids } => {
update
.deleted_excerpts
.extend(ids.iter().map(ExcerptId::to_proto));
true
}
Event::ScrollPositionChanged { .. } => {
EditorEvent::ScrollPositionChanged { .. } => {
let scroll_anchor = self.scroll_manager.anchor();
update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
update.scroll_x = scroll_anchor.offset.x;
update.scroll_y = scroll_anchor.offset.y;
true
}
Event::SelectionsChanged { .. } => {
EditorEvent::SelectionsChanged { .. } => {
update.selections = self
.selections
.disjoint_anchors()
@@ -583,7 +584,7 @@ impl Item for Editor {
Some(path.to_string_lossy().to_string().into())
}
fn tab_content<T: 'static>(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<T> {
fn tab_content(&self, detail: Option<usize>, cx: &WindowContext) -> AnyElement {
let theme = cx.theme();
AnyElement::new(
@@ -603,7 +604,7 @@ impl Item for Editor {
&description,
MAX_TAB_TITLE_LEN,
))
.color(TextColor::Muted),
.color(Color::Muted),
),
)
})),
@@ -760,7 +761,7 @@ impl Item for Editor {
}
fn breadcrumb_location(&self) -> ToolbarItemLocation {
ToolbarItemLocation::PrimaryLeft { flex: None }
ToolbarItemLocation::PrimaryLeft
}
fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
@@ -906,17 +907,15 @@ impl SearchableItem for Editor {
type Match = Range<Anchor>;
fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
todo!()
// self.clear_background_highlights::<BufferSearchHighlights>(cx);
self.clear_background_highlights::<BufferSearchHighlights>(cx);
}
fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
todo!()
// self.highlight_background::<BufferSearchHighlights>(
// matches,
// |theme| theme.search.match_background,
// cx,
// );
self.highlight_background::<BufferSearchHighlights>(
matches,
|theme| theme.title_bar_background, // todo: update theme
cx,
);
}
fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
@@ -951,22 +950,20 @@ impl SearchableItem for Editor {
matches: Vec<Range<Anchor>>,
cx: &mut ViewContext<Self>,
) {
todo!()
// self.unfold_ranges([matches[index].clone()], false, true, cx);
// let range = self.range_for_match(&matches[index]);
// self.change_selections(Some(Autoscroll::fit()), cx, |s| {
// s.select_ranges([range]);
// })
self.unfold_ranges([matches[index].clone()], false, true, cx);
let range = self.range_for_match(&matches[index]);
self.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.select_ranges([range]);
})
}
fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
todo!()
// self.unfold_ranges(matches.clone(), false, false, cx);
// let mut ranges = Vec::new();
// for m in &matches {
// ranges.push(self.range_for_match(&m))
// }
// self.change_selections(None, cx, |s| s.select_ranges(ranges));
self.unfold_ranges(matches.clone(), false, false, cx);
let mut ranges = Vec::new();
for m in &matches {
ranges.push(self.range_for_match(&m))
}
self.change_selections(None, cx, |s| s.select_ranges(ranges));
}
fn replace(
&mut self,
+3 -3
View File
@@ -6,8 +6,8 @@ use crate::{
display_map::{DisplaySnapshot, ToDisplayPoint},
hover_popover::hide_hover,
persistence::DB,
Anchor, DisplayPoint, Editor, EditorMode, Event, InlayHintRefreshReason, MultiBufferSnapshot,
ToPoint,
Anchor, DisplayPoint, Editor, EditorEvent, EditorMode, InlayHintRefreshReason,
MultiBufferSnapshot, ToPoint,
};
use gpui::{point, px, AppContext, Entity, Pixels, Styled, Task, ViewContext};
use language::{Bias, Point};
@@ -224,7 +224,7 @@ impl ScrollManager {
cx: &mut ViewContext<Editor>,
) {
self.anchor = anchor;
cx.emit(Event::ScrollPositionChanged { local, autoscroll });
cx.emit(EditorEvent::ScrollPositionChanged { local, autoscroll });
self.show_scrollbar(cx);
self.autoscroll_request.take();
if let Some(workspace_id) = workspace_id {
@@ -71,7 +71,8 @@ impl<'a> EditorTestContext<'a> {
&self,
predicate: impl FnMut(&Editor, &AppContext) -> bool,
) -> impl Future<Output = ()> {
self.editor.condition::<crate::Event>(&self.cx, predicate)
self.editor
.condition::<crate::EditorEvent>(&self.cx, predicate)
}
#[track_caller]